我在尝试使用Keras 2.0.8、Python 3.6.1和Tensorflow后端训练我的模型时遇到了问题。
错误信息:
ValueError: 检查目标时出错:期望dense_4的形状为(None, 2),但得到的数组形状为(2592, 1)
X_train = numpy.swapaxes(X_train, 1, 3)X_test = numpy.swapaxes(X_test, 1, 3)print("X_train shape: ") --> size = (2592, 1, 1366, 96)print("-----")print("X_test shape") --> size = (648, 1, 1366, 96)print("-----")print(Y_train.shape) --> size = (2592,)print("-----")print("Y_test shape") --> size = (648,)
相关代码片段:
K.set_image_dim_ordering('th')K.set_image_data_format('channels_first')def create_model(weights_path=None): model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3),activation='relu', padding="same", input_shape=(1, 1366, 96))) model.add(Conv2D(64, (3, 3), activation='relu', dim_ordering="th")) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.1)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.1)) model.add(Dense(16, activation='relu')) model.add(Dense(2, activation='softmax')) if weights_path: model.load_weights(weights_path) return modelmodel = create_model()model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.SGD(lr=0.01), metrics=['accuracy'])history = model.fit(X_train, Y_train, batch_size=32, epochs=100, verbose=1, validation_data=(X_test, Y_test))
第142行,我调用model.fit()的地方出现了这个错误
我尝试过的解决此错误的方法参考了这些Stack Overflow帖子:
我尝试使用以下代码重塑Y_test和Y_train的numpy数组:
Y_train.reshape(2592, 2)Y_test.reshape(648, 2)
然而,我得到了以下错误:
ValueError: 无法将大小为2592的数组重塑为形状(2592,2)
回答:
由于您使用了categorical_crossentropy
损失函数,您必须使用one-hot编码的标签。为此,您可以使用keras.utils.np_utils
中的to_categorical
函数
from keras.utils import np_utilsy_train_onehot = np_utils.to_categorical(y_train)y_test_onehot = np_utils.to_categorical(y_test)
然后使用one-hot编码的标签来训练您的模型。