预测测试图像时出现错误-无法重整尺寸数组 [英] getting error while predicting a test image - cannot reshape array of size
问题描述
我正在尝试使用TensorFlow和Keras在Python中进行图像识别,我在下面的博客中也做了同样的事情.
尝试使用上述训练有素的模型预测这张图片
我写了下面的代码
来自keras.preprocessing导入图像的 从keras.preprocessing.image导入ImageDataGeneratorimg_path ='数据/img.jpg'img = image.load_img(img_path,target_size =(28,28))img_tensor = image.img_to_array(img)img_tensor = numpy.expand_dims(img_tensor,轴= 0)img_tensor/= 255.pyplot.imshow(img_tensor [0])pyplot.show()打印(img_tensor.shape)pred = model.predict(img_tensor.reshape(-1,28,28,28))打印(pred.argmax())
使用上面的model.predict,我得到以下错误
---------------------------------------------------------------------------ValueError Traceback(最近一次通话)< ipython-input-125-965f3e01bc73>在< module>中---->1个pred = model.predict(img_tensor.reshape(-1,28,28,28))2打印(pred.argmax())** ValueError:无法将大小为2352的数组重塑为形状(28,28,28)**
我尝试了所有选项,但没有得到正确的结果.有人可以帮助我获得正确的结果吗?
您的输入大小为(28,28,3),但是您正在将其转换为(28,28,28),这是错误的.试试:
pred = model.predict(img_tensor.reshape(-1,28,28,3))
I am trying to do Image Recognition in Python with TensorFlow and Keras and I have followed below blog for the same. https://stackabuse.com/image-recognition-in-python-with-tensorflow-and-keras/
I need to find the output of each layer and at the same time I am also trying to predict an image.
Please see my code below. I am not able to predict and image that I am providing Any help and inputs here to get this fixed is much appreciated.
import numpy
from keras import models
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, BatchNormalization, Activation
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.constraints import maxnorm
from keras.utils import np_utils
from matplotlib import pyplot
# Create dictionary of target classes
label_dict = {
0: 'T-shirt/top',
1: 'Trouser',
2: 'Pullover',
3: 'Dress',
4: 'Coat',
5: 'Sandal',
6: 'Shirt',
7: 'Sneaker',
8: 'Bag',
9: 'Ankle boot',
}
# example of loading the mnist dataset
from keras.datasets import fashion_mnist
from matplotlib import pyplot
# load dataset
#trainX, trainy), (testX, testy) = fashion_mnist.load_data()
(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
# summarize loaded dataset
print('Train: X=%s, y=%s' % (X_train.shape, y_train.shape))
print('Test: X=%s, y=%s' % (X_test.shape, y_test.shape))
# plot first few images
for i in range(9):
# define subplot
pyplot.subplot(330 + 1 + i)
# plot raw pixel data
pyplot.imshow(X_train[i], cmap=pyplot.get_cmap('gray'))
# show the figure
pyplot.show()
# normalize the inputs from 0-255 to between 0 and 1 by dividing by 255
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train = X_train / 255.0
X_test = X_test / 255.0
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
class_num =10
numpy.max(X_train[0])
numpy.min(X_train[0])
X_train[0][500:]
y_train[:500][0]
y_train[:500][0]
X_train.shape, X_test.shape
y_train.shape, y_test.shape
# Reshape training and testing image
X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1,28,28,1)
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=X_train.shape[1:], padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3), input_shape=(3, 32, 32), activation='relu', padding='same'))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(Conv2D(64, (3, 3), padding='same', name='test1'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(Conv2D(64, (3, 3), padding='same', name='test2'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(Conv2D(128, (3, 3), padding='same', name='test3'))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(256, kernel_constraint=maxnorm(3)))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(Dense(128, kernel_constraint=maxnorm(3)))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(Dense(class_num))
model.add(Activation('softmax'))
epochs = 2
optimizer = 'adam'
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
print(model.summary())
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=64)
# Model evaluation
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
# This I am predicting from test images
image_index = 430
pyplot.imshow(X_test[image_index].reshape(28, 28,1),cmap='Greys')
pred = model.predict(X_test[image_index].reshape(-1, 28, 28, 1))
print(pred.argmax())
I am trying to predict model using image below
Trying to predict this image using the above trained model
I have written below code
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
img_path = 'data/img.jpg'
img = image.load_img(img_path, target_size=(28, 28))
img_tensor = image.img_to_array(img)
img_tensor = numpy.expand_dims(img_tensor, axis=0)
img_tensor /= 255.
pyplot.imshow(img_tensor[0])
pyplot.show()
print(img_tensor.shape)
pred = model.predict(img_tensor.reshape(-1, 28, 28, 28))
print(pred.argmax())
With the above model.predict, I am getting below error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-125-965f3e01bc73> in <module>
----> 1 pred = model.predict(img_tensor.reshape(-1, 28, 28, 28))
2 print(pred.argmax())
**ValueError: cannot reshape array of size 2352 into shape (28,28,28)**
I have tried all options but not getting the right results. Can any one help me to get the right results please?
Your input is of size (28,28,3) but you are transforming it into (28,28,28) which is wrong. Try:
pred = model.predict(img_tensor.reshape(-1, 28, 28, 3))
这篇关于预测测试图像时出现错误-无法重整尺寸数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!