为(60000、28、28)数组在keras中定义输入形状时出错 [英] Error defining an input shape in keras for (60000, 28, 28) array

查看:89
本文介绍了为(60000、28、28)数组在keras中定义输入形状时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用keras和tensorflow建立我的第一个神经网络.我将输入输入到一个形状数组(60000、28、28)中,但是当我尝试将其输入到模型中时,出现输入格式错误的错误.

I am setting up my first neural network with keras and tensorflow. I got my input into an array of shape (60000, 28, 28), but when I try and feed it to the model I get an error that the input shape is wrong.

我尝试了多种不同的输入形状,包括(60000,28,28)(1,28,28)(28,28)(28,28,1),但似乎都不起作用.

I have tried multiple different input shapes including (60000, 28, 28) (1, 28, 28) (28, 28) (28, 28, 1) but none of them seem to work.

model = kr.Sequential()

model.add(InputLayer(input_shape=(60000, 28, 28)))
model.add(Dense(units=784, activation='relu'))
model.add(Dense(units=392, activation='relu'))
model.add(Dense(units=196, activation='relu'))
model.add(Dense(units=10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])

training = model.fit(x=images_array, y=labels_array, epochs=10, batch_size=256)

我希望它能与输入形状(60000、28、28)一起使用,但我总是会收到此错误:

I would expect it to work with input shape (60000, 28, 28) but I always get this error:

ValueError:检查输入时出错:预期input_1具有4尺寸,但数组的形状为(60000,28,28)

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (60000, 28, 28)

感谢所有回答的人.cho_uc的答案确实有效,这就是为什么我接受了它.我在帖子中提到的是,我正在尝试构建仅由密集层组成的模型,因此可以将其用作将来模型的基准.

Thanks to everyone who answerd. cho_uc answer indeed worked, which is why I accepted it. What I shold have mentioned in the post was, that I was trying to build a model consisting only of Dense layers, so I can use it as a benchmark for future models.

我使用以下方法解决了输入层问题:

I solved the input layer problem with:

images_array = images_array.reshape(-1, 28 * 28)

model.add(InputLayer(input_shape=(784, )))

推荐答案

Keras Conv2D 层执行卷积操作.它要求其输入为4维数组.根据您的设置和后端(theano或tensorlow图像布局约定),我们必须将输入的形状重塑为(,1、28、28)或可能重塑为(,28、28、1).

Keras Conv2D layer performs the convolution operation. It requires its input to be a 4-dimensional array. We have to reshape the input to ( , 1, 28, 28) or possibly to ( , 28, 28, 1), depending on your setup and backend (theano or tensorlow image layout convention).

from keras import backend as K
if K.image_data_format() == 'channels_first' :
   input_shape = (1, 28, 28)
   X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
   X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
else:
   input_shape = (28, 28, 1)
   X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
   X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)

因此,您应该将数据重塑为(60000,28,28,1)或(60000,1,28,28)

So, you should reshape your data to (60000, 28, 28, 1) or (60000, 1, 28, 28)

这篇关于为(60000、28、28)数组在keras中定义输入形状时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆