keras 在机器学习中,形状(无,2)和(无,10)不兼容

m528fe3b  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(173)

我在下面的Keras模型中得到一个错误(Shapes (None, 2) and (None, 10)) are incompatible

from keras.layers import Dense, Activation
model=Sequential()
model.add(Dense(1000, input_dim=25088, 
activation='relu',kernel_initializer='uniform'))
keras.layers.core.Dropout(0.3, noise_shape=None, seed=None)
model.add(Dense(500,input_dim=1000,activation='sigmoid'))
keras.layers.core.Dropout(0.4, noise_shape=None, seed=None)
model.add(Dense(150,input_dim=500,activation='sigmoid'))
keras.layers.core.Dropout(0.2, noise_shape=None, seed=None)
model.add(Dense(units=10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer="adam", metrics= 
['accuracy'])
# fitting the model 
model.fit(X_train, Y_train, epochs=20, batch_size=128,validation_data= 
(X_valid,Y_valid))
jei2mxaa

jei2mxaa1#

您的模型的输出形状是(None, 10),但Y_train的形状是(None, 2)。形状不匹配,这就是您遇到此错误的原因。将最终密集图层中的单元数设置为2,问题应该会得到解决。尝试以下操作:

from keras.layers import Dense, Activation
model=Sequential()
model.add(Dense(1000, input_dim=25088, 
activation='relu',kernel_initializer='uniform'))
keras.layers.core.Dropout(0.3, noise_shape=None, seed=None)
model.add(Dense(500,input_dim=1000,activation='sigmoid'))
keras.layers.core.Dropout(0.4, noise_shape=None, seed=None)
model.add(Dense(150,input_dim=500,activation='sigmoid'))
keras.layers.core.Dropout(0.2, noise_shape=None, seed=None)
model.add(Dense(units=2))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer="adam", metrics= 
['accuracy'])
# fitting the model 
model.fit(X_train, Y_train, epochs=20, batch_size=128,validation_data= 
(X_valid,Y_valid))

相关问题