这里是新的 Python 开发人员。我在这里查看了其他类似的帖子,但我无法正确理解。将不胜感激任何帮助。
print('X_train:', X_train.shape)
print('y_train:', y_train1.shape)
print('X_test:', X_train.shape)
print('y_test:', y_train1.shape)
X_train: (42000, 32, 32) y_train: (42000,) X_test: (42000, 32, 32) y_test: (42000,)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
def featuremodel() :
model = Sequential()
model.add(Conv2D(32, kernel_size=4, activation='relu', input_shape=(X_train.shape[0],32,64)))
model.add(MaxPooling2D(pool_size=3))
model.add(Conv2D(64, kernel_size=4, activation='relu'))
model.add(Flatten())
model.add(Dense(len(y_train[0]), activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['acc'])
model.summary()
model.fit(X_train, y_train, epochs = 10, validation_data = (X_test,y_test))
返回模型
ValueError: 层序列 7 的输入 0 与层不兼容:预期 min_ndim=4,发现 ndim=2。收到完整形状:(无,1024)
答案 0 :(得分:0)
您指定的输入形状应该更改。您的输入有 42000 个样本,每个样本都有 (32,32)
形状。您不应将样本数 (42000)
传递给输入层,而应添加通道维度。所以输入形状应该是 (32,32,1)
。
修改后的代码应该是这样的:
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
# test data
X_train = tf.random.uniform((42000,32,32))
y_train1 = tf.random.uniform((42000,))
X_train = tf.expand_dims(X_train, axis=3) #add channel axis (42000,32,32) => (42000,32,32,1)
model = Sequential()
model.add(Conv2D(32, kernel_size=4, activation='relu', input_shape=(32,32,1))) #change input shape
model.add(MaxPooling2D(pool_size=3))
model.add(Conv2D(64, kernel_size=4, activation='relu'))
model.add(Flatten())
#last layer should have output like your y data. in this case it should be 1, since you have 1 y for each sample
model.add(Dense(1, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adadelta',
metrics=['acc'])
model.summary()
model.fit(X_train, y_train1, epochs = 10) #, validation_data = (X_test,y_test))