Python Tensorflow和Keras错误|模块“tree”没有属性“flatten”

vpfxa7rd  于 5个月前  发布在  Python
关注(0)|答案(1)|浏览(170)

所以我最近想在一段时间后再次尝试Tensorflow和Keras。我过去尝试过,但在我分心并尝试其他事情之前,我只触及了表面。现在,正如我所说,我想再次尝试,所以我只是确保我有最新版本的Tensorflow和Keras使用pip,然后从官方Tensorflow网站复制一个示例。这是代码:

# TensorFlow and tf.keras
import tensorflow as tf

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

train_images, test_images = train_images/255, test_images/255

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

model.compile(optimizer="adam",
              loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics = ["accuracy"])

model.fit(train_images, train_labels, epochs=10)

字符串
现在,当我运行代码时,我得到这个错误:

Traceback (most recent call last):
  File "C:\Users\me\AppData\Local\Programs\Python\Python311\Tensorflow\example.py", line 21, in <module>
    tf.keras.layers.Input(shape=(28, 28)),
  File "C:\Users\me\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\layers\core\input_layer.py", line 143, in Input
    layer = InputLayer(
  File "C:\Users\me\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\layers\layer.py", line 216, in __new__
    obj = super().__new__(cls, *args, **kwargs)
  File "C:\Users\me\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\ops\operation.py", line 100, in __new__
    flat_arg_values = tree.flatten(kwargs)
AttributeError: module 'tree' has no attribute 'flatten'


我对编程或Python也不陌生,所以我也尝试安装不同版本的Tensorflow,并使用pip升级“树”模块。
第一个月
但是似乎没有什么能解决这个问题。如果有人知道问题是什么,能帮我解决,我会很高兴的。

u5i3ibmn

u5i3ibmn1#

我已经在Google Colab中执行了您的代码,并且在这一行没有遇到任何错误。您面临的问题可能是由于您的库安装。
如果您单独安装了TensorFlow和Keras,版本之间可能会有冲突。我建议只安装TensorFlow库,因为Keras已集成到其中。
对于使用全连接网络的简单图像分类,在Dense层之前包含Flatten层至关重要。
此外,常见的方法是将最后一个Dense层的激活函数设置为softmax以进行多类分类,从而输出概率而不是原始logits。
下面是修改后的代码片段:

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(28, 28)),
    tf.keras.layers.Flatten(), # Add this Flatten layer
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax') # Optional: Change the last activation to softmax
])

model.compile(
    optimizer="adam",
    loss=tf.keras.losses.SparseCategoricalCrossentropy(), # Optional: Remove the from_logits parameter if we set the final activation as softmax
    metrics=["accuracy"]
)

字符串
我创建了一个Google Colab笔记本,您可以探索here
我希望这能彻底解决你的问题。如果你需要进一步的澄清,请让我知道!

相关问题