所以我最近想在一段时间后再次尝试 Tensorflow 和 Keras。我过去曾尝试过,但在我分心并尝试其他事情之前,我只触及了表面。现在,正如我所说,我想再次尝试一下,所以我只是使用 pip 确保我拥有最新版本的 Tensorflow 和 Keras,然后从官方 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来升级“tree”模块。我还尝试使用类似的东西替换该函数(是的,我知道这是一个不好的做法)
tree.flatten = lambda kwargs: kwargs
如果您分别安装了 Tensorflow 和 Keras,我怀疑您的 TensorFlow 和 Keras 库之间存在冲突。因此,最好
仅安装tensorflow库,因为其中包含Keras。
此外,我在您的代码中发现了一个错误。如果你打算用全连接网络做一个简单的图像分类,你需要在Dense层之前添加flatten层,并将softmax设置为最终的激活函数。
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(28, 28)),
tf.keras.layers.Flatten(), # Add this layer flatten layer
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax') # Change the last activation to softmax for multi-class classification
])
model.compile(
optimizer="adam",
loss = tf.keras.losses.SparseCategoricalCrossentropy(), # Remove from logits parameters
metrics = ["accuracy"])
我创建了这个 Google Colab Notebook,您可以尝试一下:
https://colab.research.google.com/gist/naufalso/a9d7cd1ba9ac1c5fcd5a33bb1cd2cf01/stackoverflowissue-77754795.ipynb
希望这能回答您的问题。