在尝试使用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 model
model = 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))
Line 142, where I call model.fit() is where I am getting this error
Things I have tried to fix this error 引用了这些堆栈溢出帖子:
我尝试使用以下代码重塑Y_test和Y_train numpy数组:
Y_train.reshape(2592, 2)
Y_test.reshape(648, 2)
但是,我收到以下错误:
ValueError:无法将大小为2592的数组重塑为形状(2592,2)
2 回答
当您使用
categorical_crossentropy
丢失时,您必须使用单热编码标签 . 为此,您可以使用keras.utils.np_utils
中的函数to_categorical
然后使用单热编码标签来训练您的模型 .
在我看来,你需要改变NN的最后一层: