首页 > 解决方案 > 如何对这个训练有素的模型进行预测?

问题描述

我是机器学习的新手,我在网上找到了这个迁移学习模型,这似乎是一个微不足道的问题,但我如何用一张图像进行预测?到目前为止,我对代码还不是很熟悉,但我训练有素的模型似乎运行良好(我正在使用 google colab)。

import pandas as pd
import numpy as np
import os
import keras
import matplotlib.pyplot as plt
from keras.layers import Dense,GlobalAveragePooling2D
from keras.applications import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam

base_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(4,activation='softmax')(x) #final layer with softmax activation

model=Model(inputs=base_model.input,outputs=preds)
#specify the inputs
#specify the outputs
#now a model has been created based on our architecture

for layer in model.layers[:20]:
    layer.trainable=False
for layer in model.layers[20:]:
    layer.trainable=True

from zipfile import ZipFile
file_name = 'thecar.zip'

with ZipFile(file_name, 'r') as zip:
  zip.extractall()
  print('Done')

train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependencies

train_generator=train_datagen.flow_from_directory('thecar', # this is where you specify the path to the main data folder
                                                 target_size=(224,224),
                                                 color_mode='rgb',
                                                 batch_size=5,
                                                 class_mode='categorical',
                                                 shuffle=True)


model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# Adam optimizer
# loss function will be categorical cross entropy
# evaluation metric will be accuracy

step_size_train=train_generator.n//train_generator.batch_size
model.fit_generator(generator=train_generator,
                   steps_per_epoch=step_size_train,
                   epochs=5)

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


当您在 5 个小批量上训练模型时,您必须在对单个图像进行预测时考虑到这一点。您只需将图像更改为以下形状:[1, image_width, image_height, number_of_channels]这是通过使用np.expand_dims().

import numpy as np
from keras.preprocessing import image


img = image.load_img(PATH_TO_IMAGE, target_size = (224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis = 0)

model.predict(img)

推荐阅读