python - 预测测试图像时出错 - 无法重塑大小数组
问题描述
我正在尝试使用 TensorFlow 和 Keras 在 Python 中进行图像识别,并且我已经按照下面的博客进行了相同的操作。 https://stackabuse.com/image-recognition-in-python-with-tensorflow-and-keras/
我需要找到每一层的输出,同时我也试图预测一个图像。
请在下面查看我的代码。我无法预测和想象我正在提供的任何帮助和输入来解决这个问题非常感谢。
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())
我正在尝试使用下图预测模型
尝试使用上述经过训练的模型来预测此图像
我写了下面的代码
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())
使用上面的model.predict,我得到了以下错误
---------------------------------------------------------------------------
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)**
我已经尝试了所有选项,但没有得到正确的结果。任何人都可以帮助我得到正确的结果吗?
解决方案
您的输入大小为 (28,28,3) 但您将其转换为 (28,28,28) 这是错误的。尝试:
pred = model.predict(img_tensor.reshape(-1, 28, 28, 3))
推荐阅读
- c# - 为什么即使在添加程序集“Microsoft.SqlServer.ConnectionInfo”之后 C# 也无法识别 Server()
- docker - docker nginx 访问日志权限被拒绝
- python - 按范围扩展 DataFrame
- mongodb - 无法通过脚本运行 mongo
- c++ - 为什么 const_cast 和 static_cast 到 const 引用没有效果?
- ios - 以编程方式获取 iOS 中的 GPU 使用情况
- angular - 构建应用程序时未找到/注册错误的 Angular Service Worker
- powershell - 导出 Pfxcertificate 命令在 Powershell 中不可用
- html - 选择字段中的选项仅在切换选项卡后出现
- c# - 如果添加到 where 子句的参数为空,则从 db 获取所有行