Reputation: 1
After I fit my machine learning I am trying to predict a new one. Image named 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:
ValueError: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (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)
Upvotes: 0
Views: 726
Reputation: 16916
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. Then the expand_dims
adds a dimension and returns a single element np array (the element being the tensor).
Rather return a image as 3D np array then create a batch of images for prediction.
Upvotes: 1