Numpy 预期conv2d_1_输入具有形状(28,28,1),但获得具有形状(1,28,28)的数组
所以我在keras上使用mnist的例子,我试图预测我自己的一个数字。我真的很挣扎如何匹配尺寸大小,因为我似乎找不到一种方法来调整图像大小,使行和列位于图像编号之后。我尝试过使用via numpy调整大小,但我只是一个接一个地出错 代码Numpy 预期conv2d_1_输入具有形状(28,28,1),但获得具有形状(1,28,28)的数组,numpy,tensorflow,deep-learning,keras,mnist,Numpy,Tensorflow,Deep Learning,Keras,Mnist,所以我在keras上使用mnist的例子,我试图预测我自己的一个数字。我真的很挣扎如何匹配尺寸大小,因为我似乎找不到一种方法来调整图像大小,使行和列位于图像编号之后。我尝试过使用via numpy调整大小,但我只是一个接一个地出错 代码 from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
import cv2
batch_size = 20
num_classes = 10
epochs = 1
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("Processing image")
im = cv2.imread('C:/Users/Luke/pic4.png', 0) #loading the image
print(im.shape) #28*28
im = cv2.resize(im, (img_rows, img_cols))
list = [im]
batch = np.array([list for i in range(1)])
print(batch.shape)#1*28*28
batch = batch.astype('float32')
batch /= 255
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
#print("x_train shape")
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
def base_model():
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
return model
cnn_m = base_model()
cnn_m.summary()
print("Predicting image")
cnn_m.predict(batch)
print("Predicted image")
错误
$python mnist\u cnn\u test.py
使用TensorFlow后端。
x_列车形状:(60000,28,28,1)
60000列车样本
10000个测试样本
_________________________________________________________________
图层(类型)输出形状参数#
=================================================================
conv2d_1(conv2d)(无、26、26、32)320
_________________________________________________________________
conv2d_2(conv2d)(无、24、24、64)18496
_________________________________________________________________
最大池2D池1(最大池2(无、12、12、64)0
_________________________________________________________________
辍学1(辍学)(无、12、12、64)0
_________________________________________________________________
展平1(展平)(无,9216)0
_________________________________________________________________
密集型_1(密集型)(无,128)1179776
_________________________________________________________________
辍学2(辍学)(无,128)0
_________________________________________________________________
致密_2(致密)(无,10)1290
=================================================================
总参数:1199882
可培训参数:1199882
不可训练参数:0
_________________________________________________________________
预测图像
回溯(最近一次呼叫最后一次):
文件“mnist_cnn_test.py”,第100行,在
cnn_m.预测(批量)
文件“C:\Python35\lib\site packages\keras\models.py”,第1027行,在predict中
步骤=步骤)
文件“C:\Python35\lib\site packages\keras\engine\training.py”,第1782行,在predict中
检查(批次轴=假)
文件“C:\Python35\lib\site packages\keras\engine\training.py”,第120行,输入数据
str(数据形状))
ValueError:检查时出错:预期conv2d_1_输入具有形状(28,28,1),但获取具有形状(1,28,28)的数组
看起来您的数据格式不对。数据首先作为通道_传递(即每个图像为1 x 28 x 28),但Conv2D层希望通道_最后(28 x 28 x 1)
一种修复方法是首先将data\u format=channels\u
传递到Conv2D和MaxPooling层。但是,如果在CPU上运行,则可能不支持此操作。或者,更改此部分
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
要始终执行else
块(该块将重新整形为最后一种格式)。在这种情况下,不要将data\u format
参数包含到Conv层(默认为channels\u last)。解决方案:
推理:
指任何批量(样品编号)、28*28形状和1个通道。
在您的情况下,使用1作为样本号。您只需添加
K.set_image_dim_ordering('th')
谢谢channels first方法似乎不起作用,但是如果我离开channels first块来执行该形状,它似乎是正确的。
im = cv2.resize(im, (img_rows, img_cols))
im.reshape((img_rows,img_cols))
print(im.shape) # (28,28)
batch = np.expand_dims(im,axis=0)
print(batch.shape) # (1, 28, 28)
batch = np.expand_dimes(batch,axis=3)
print(batch.shape) # (1, 28, 28,1)
... # build the model
model.predict(batch)
print(model.input_shape) # (None,28,28,1)
K.set_image_dim_ordering('th')