import tensorflow as tf
import numpy as np
import warnings
warnings.filterwarnings(“ignore”)
x_train=np.random.random((10,8))
y_train=np.random.randint(10,size=(10,1))
x_test=np.random.random((5,8))
y_test=np.random.randint(10,size=(5,1))
model=tf.keras.Sequential()
model.add(tf.keras.layers.Dense(10,input_shape=(8,)))
model.add(tf.keras.layers.Dense(5,activation=“relu”))
model.add(tf.keras.layers.Dense(3,activation=“relu”))
model.add(tf.keras.layers.Dense(5,activation=“softmax”))
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),loss=tf.keras.losses.categorical_crossentropy,metrics=tf.keras.metrics.categorical_accuracy)
model.fit(x_train,y_train,epochs=10,batch_size=1,validation_data=(x_test,y_test))
model.save(“model.h5”)
报错:
Traceback (most recent call last):
File “D:/python/flask/app.py”, line 26, in
model.fit(x_train,y_train,epochs=10,batch_size=1,validation_data=(x_test,y_test))
File “C:\Users\dky\AppData\Roaming\Python\Python37\site-packages\keras\utils\traceback_utils.py”, line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File “C:\Users\dky\AppData\Roaming\Python\Python37\site-packages\keras\backend.py”, line 4994, in categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
ValueError: Shapes (1, 1) and (1, 5) are incompatible
这个错误的原因是测试数据是一个 (1, 1)形状的数据
[[8]
[3]
[1]
[9]
[4]],
但模型设置输出是一个(1,5)形状的数据。
将model.add(tf.keras.layers.Dense(5,activation=“softmax”))修改为model.add(tf.keras.layers.Dense(1,activation=“softmax”))即可。