我不明白Tensorflow应该是model.fit的输入

时间:2019-11-23 22:43:00

标签: python tensorflow keras

我是一个初学者,我正在尝试将一些图像分类为20类

这是我要使用的代码:

from tensorflow.python.keras import Sequential
from tensorflow.python.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
x=x/255.0
model=Sequential()
model.add(Conv2D(64,(3,3), input_shape=x.shape[1:]))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64,(3,3), input_shape=x.shape[1:]))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))

model.add(Dense(20))
model.add(Activation('softmax'))




loss = tf.keras.losses.CategoricalCrossentropy()

lr = 1e-3
optimizer = tf.keras.optimizers.Adam(learning_rate=lr)

metrics = ['accuracy']

model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
Y= np.asarray(y)

model.fit(x,Y,batch_size=32,validation_split=0.1)

但是我收到此错误:

ValueError: You are passing a target array of shape (1554, 1) while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:

x.shape返回 (1554、50、50、1)

和 Y.shape返回

感谢您的帮助! (1554,)

1 个答案:

答案 0 :(得分:1)

您可能忘记了对标签数据进行一次热编码。如果标签是0到19之间的整数(代表不同的类),则可以在keras.utils中使用to_categorical来相应地转换标签