I need to input a 96 * 96 size picture to the network, but I get this exception:
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) [(None, 96, 96, 3)] 0
sequential_1 (Sequential) (None, 96, 96, 3) 0
rescaling (Rescaling) (None, 96, 96, 3) 0
mobilenetv2_0.35_96 (Functi (None, 3, 3, 1280) 410208
onal)
flatten (Flatten) (None, 11520) 0
dense (Dense) (None, 15) 172815
=================================================================
Total params: 583,023
Trainable params: 172,815
Non-trainable params: 410,208
_________________________________________________________________
(96, 96, 3)
ValueError: Input 0 of layer "model" is incompatible with the layer: expected shape=(None, 96, 96, 3), found shape=(32, 96, 3)
This is strange, when I invoke image.shape()
, I got (96, 96), but this exception shows that this image size is (32, 96).
main.py
import image_load
from pathlib import Path
from tensorflow import keras
base_path = Path()
model = keras.models.load_model(base_path.cwd().joinpath("my_model"))
model.summary()
image = image_load.load_and_preprocess_image(str(base_path.joinpath("cat4.jpg")))
print(image.shape)
predict = model.predict(image)
print(predict)
load_image.py
import tensorflow as tf
import matplotlib.pyplot as plt
def preprocess_image(image):
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, [96, 96])
image /= 255.0 # normalize to [0,1] range
return image
def load_and_preprocess_image(path):
image = tf.io.read_file(path)
return preprocess_image(image)
def show_image(path):
plt.imshow(path)
plt.show()
Here is this image: enter image description here
How can I make the picture enter the model smoothly and get the prediction results?
CodePudding user response:
You need to pass numpy array into model.predict
like this:
predict = model.predict(np.array([image]))[0]
print(predict)
(Note that [0] at the end takes the first value of the output, because we passed array of only one value)