[英]expected conv2d_input to have 4 dimensions with shape(1, 1)
After I fit my machine learning I am trying to predict a new one. 在适应了机器学习之后,我正在尝试预测一个新的机器学习。 Image named demo1.jpg
名为demo1.jpg的图片
What I expected get new feature into my library: 我期望将新功能添加到库中:
My details: 我的细节:
RTX 2080
Tensorflow 1.13.1
Cuda 10.0
I'm using tf.keras and I'm getting following error: 我正在使用tf.keras,但出现以下错误:
ValueError: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (1, 1)
ValueError:检查输入时出错:预期conv2d_input具有4维,但数组的形状为(1,1)
My full code: 我的完整代码:
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
import tensorflow as tf
import numpy as np
import pickle
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from tensorflow import keras
IMG_SIZE = 50
def prepare(file):
img_array = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
predictdata = tf.reshape(new_array, (1, 50, 50))
predictdata = np.expand_dims(predictdata, -1)
return predictdata
pickle_ind = open("x.pickle", "rb")
x = pickle.load(pickle_ind)
x = np.array(x, dtype=float)
x = np.expand_dims(x, -1)
pickle_ind = open("y.pickle", "rb")
y = pickle.load(pickle_ind)
n_batch = len(x)
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(50, 50, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(1, activation='softmax'))
model.summary()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(x, y, epochs=1, batch_size=n_batch)
prediction = model.predict([prepare('demo1.jpg')], batch_size=n_batch, steps=1, verbose=1)
print(prediction)
Do below changes: 执行以下更改:
def prepare(file):
img_array = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
return np.expand_dims(cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)), -1)
model.fit(x, y, epochs=1, batch_size=n_batch)
model.predict(np.array([prepare("demo1.jpg")]), batch_size=n_batch, steps=1, verbose=1)
Issue: tf.reshape
returns a tensor not a numpy array. 问题:
tf.reshape
返回张量而不是numpy数组。 Then the expand_dims
adds a dimension and returns a single element np array (the element being the tensor). 然后
expand_dims
添加一个维度并返回单个元素np数组(该元素为张量)。
Rather return a image as 3D np array then create a batch of images for prediction. 而是将图像返回为3D np数组,然后创建一批图像进行预测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.