我正在尝试对卷积网络中的手写数字的MNIST数据库进行分类,但是却出现此错误:ValueError: Error when checking input: expected conv2d_40_input to have 4 dimensions, but got array with shape (28, 28, 1)
我的任务是使用交叉采样,这就是为什么将数据分为5组。
def train_conv_subsample():
#splitting data into chunks
chunks = []
chunk_labels = []
num_chunks = 5
chunk_size = int(train_data.shape[0]/num_chunks)
for i in range(num_chunks):
chunks.append(train_data[(i*chunk_size):(i+1)*chunk_size])
chunk_labels.append(train_labels[(i*chunk_size):(i+1)*chunk_size])
#Create another convolutional model to train.
for i in range(num_chunks):
current_train_data = []
current_train_lables = []
for j in range(num_chunks):
if(i == j):
validation_data = chunks[i]
validation_labels = chunk_labels[i]
else:
current_train_data.extend(chunks[j])
current_train_lables.extend(chunks[j])
print(np.shape(current_train_data)) #Says it has a shape of (48000,28,28, 1)
model = models.Sequential([
layers.Conv2D(16, kernel_size=(3, 3), activation='relu', input_shape=(28,28,1)),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dense(32, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=['accuracy'])
#But when it goes to fit it raises the error: expected 4 dim, but got array with shape (28, 28, 1)
model.fit(current_train_data, current_train_lables, epochs=1, validation_data=(validation_data, validation_labels))
tf.keras.backend.clear_session()
那是我的代码,使用的数据集可以从keras数据集,datasets.mnist.load_data()导入
感谢您的帮助
答案 0 :(得分:1)
我认为问题在于,对于mnist数据集中的图像形状,您需要使用numpy数组库中的reshape将它们重塑为4个dim数组,如下所示:
import numpy as np
np.reshape(dataset,(-1,28,28,1)
如果这不起作用,请在使用OpenCV库进行重塑之前尝试将其转换为灰度