在fashion_mnist的学习中遇到这样一个问题,代码如下:
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.datasets import fashion_mnist
(trainData,trainLabel),(testData,testLabel)=fashion_mnist.load_data()
print(trainData.shape,trainLabel.shape,testData.shape,testLabel.shape)
trainData=trainData.reshape(60000,28*28)
testData=testData.reshape(10000,28*28)
print(trainData.shape,trainLabel.shape,testData.shape,testLabel.shape)
trainData=trainData/255
testData=testData/255
trainLabel=to_categorical(trainLabel,10)
testLabel=to_categorical(testLabel,10)
print(trainLabel[0])
model=Sequential()
model.add(Dense(1000,activation="relu",input_shape=(28*28,)))
model.add(Dense(900,activation="relu"))
model.add(Dense(800,activation="relu"))
model.add(Dense(700,activation="relu"))
model.add(Dense(600,activation="relu"))
model.add(Dense(500,activation="relu"))
model.add(Dense(400,activation="relu"))
model.add(Dense(300,activation="relu"))
model.add(Dense(200,activation="relu"))
model.add(Dense(100,activation="relu"))
model.add(Dense(50,activation="relu"))
model.add(Dense(10,activation="softmax"))
model.summary()
model.compile(optimizer=SGD(),loss="categorical_crossentropy",metrics=["accuracy"])
model.fit(trainData,trainLabel,batch_size=64,epochs=10,validation_data=[testData,testLabel])
score=model.evaluate(testData,testLabel)
print(f"损失值:{score[0]}")
print(f"准确值:{score[1]}")
model.save("model.h5")
print("Saved!")
报错如下:
2022-04-02 19:28:55.872921: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] None of the MLIR Optimization Passes are enabled (registered 2)
Epoch 1/10
938/938 [==============================] - ETA: 0s - loss: 1.2550 - accuracy: 0.5621Traceback (most recent call last):
File "F:/MyProject/learning/327/1.py", line 36, in <module>
model.fit(trainData,trainLabel,batch_size=64,epochs=10,validation_data=[testData,testLabel])
File "D:\python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1225, in fit
_use_cached_eval_dataset=True)
File "D:\python36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1489, in evaluate
tmp_logs = self.test_function(iterator)
File "D:\python36\lib\site-packages\tensorflow\python\eager\def_function.py", line 889, in __call__
result = self._call(*args, **kwds)
File "D:\python36\lib\site-packages\tensorflow\python\eager\def_function.py", line 933, in _call
self._initialize(args, kwds, add_initializers_to=initializers)
File "D:\python36\lib\site-packages\tensorflow\python\eager\def_function.py", line 764, in _initialize
*args, **kwds))
File "D:\python36\lib\site-packages\tensorflow\python\eager\function.py", line 3050, in _get_concrete_function_internal_garbage_collected
graph_function, _ = self._maybe_define_function(args, kwargs)
File "D:\python36\lib\site-packages\tensorflow\python\eager\function.py", line 3444, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "D:\python36\lib\site-packages\tensorflow\python\eager\function.py", line 3289, in _create_graph_function
capture_by_value=self._capture_by_value),
File "D:\python36\lib\site-packages\tensorflow\python\framework\func_graph.py", line 999, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "D:\python36\lib\site-packages\tensorflow\python\eager\def_function.py", line 672, in wrapped_fn
out = weak_wrapped_fn().__wrapped__(*args, **kwds)
File "D:\python36\lib\site-packages\tensorflow\python\framework\func_graph.py", line 986, in wrapper
raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:
D:\python36\lib\site-packages\tensorflow\python\keras\engine\training.py:1323 test_function *
return step_function(self, iterator)
D:\python36\lib\site-packages\tensorflow\python\keras\engine\training.py:1314 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
D:\python36\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1285 run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
D:\python36\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2833 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
D:\python36\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3608 _call_for_each_replica
return fn(*args, **kwargs)
D:\python36\lib\site-packages\tensorflow\python\keras\engine\training.py:1307 run_step **
outputs = model.test_step(data)
D:\python36\lib\site-packages\tensorflow\python\keras\engine\training.py:1266 test_step
y_pred = self(x, training=False)
D:\python36\lib\site-packages\tensorflow\python\keras\engine\base_layer.py:1013 __call__
input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
D:\python36\lib\site-packages\tensorflow\python\keras\engine\input_spec.py:203 assert_input_compatibility
' input tensors. Inputs received: ' + str(inputs))
ValueError: Layer sequential expects 1 input(s), but it received 2 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 784) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 10) dtype=float32>]
Process finished with exit code 1
解决方法:
在调用fit函数时,validation_data的类型应该是元组而不是列表,原来的代码:
model.fit(trainData,trainLabel,batch_size=64,epochs=10,validation_data=[testData,testLabel])
改为:
model.fit(trainData,trainLabel,batch_size=64,epochs=10,validation_data=(testData,testLabel))
再次运行就成功啦!
喜欢的话就点赞关注吧!