SoFunction
Updated on 2024-11-12

Predict a single input image and return the prediction result operation in keras

After the model has been trained and tested, we often use one or two graphs to analyze and discuss the model prediction results, then the following describes the method of using the trained model in keras after testing.

Below is a demonstration of prediction using a pre-trained ResNet, with a selected image of a dog, from a kaggle competition.

The first prediction turned out to be a Scottish breed of dog, and I don't know if it's accurate == .

import numpy as np
from .imagenet_utils import decode_predictions
from  import image
from  import *
 
import os
 
# Ignore hardware acceleration warning messages
['TF_CPP_MIN_LOG_LEVEL'] = '2'
 
file_path = 'images/'
 
img = image.load_img(file_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
 
model = ResNet50(weights='imagenet')
y = (x)
# print((y))
print('Predicted:', decode_predictions(y, top=3)[0])

A few points:

1. Input img is converted to numpy array and shape is processed as (224,224,3) Generally speaking, for pre-training model is to have a minimum size value, larger than the minimum size is enough. In ResNet, the minimum size is 197.

2. To expand the dimension of the input shape into (None, 224,224,3), the first None is the batches, the model does not know how many batches you input, but the dimension must be the same as the input of ResNet.

3. Although the use of ResNet, their own design of the model is also a reason, to retain the training of the weights, the model module and the prediction module is written separately, this time load the weights, and then prediction can be.

Additional knowledge:keras: how to use fit_generator to train multiple outputs of different types

This example is very simple and straightforward; the model consists of 1 input, 2 outputs, and two output branches each using MSE as a loss.

x = Convolution2D(8, 5, 5, subsample=(1, 1))(image_input)
x = Activation('relu')(x)
x = Flatten()(x)
x = Dense(50, W_regularizer=l2(0.0001))(x)
x = Activation('relu')(x)

output1 = Dense(1, activation='linear', name='output1')(x)
output2 = Dense(1, activation='linear', name='output2')(x)

model = Model(input=image_input, output=[output1, output2])
(optimizer='adam', loss={'output1': 'mean_squared_error', 'output2': 'mean_squared_error'})

Generator that produces training data, here y=[y1,y2].

batch_generator(x, y, batch_size):
  ....transform images
  ....generate batch batch of size: batch_size 
  yield(X_batch, {'output1': y1, 'output2': y2} ))

After that, call the fit_generator

model.fit_generator(batch_generator(X_train, y_train, batch_size))

original questionlink (on a website)

Above this in keras to a single input image prediction and return the prediction results operation is all I have shared with you, I hope to give you a reference, and I hope you support me more.