python - 如何对这个训练有素的模型进行预测?
问题描述
我是机器学习的新手,我在网上找到了这个迁移学习模型,这似乎是一个微不足道的问题,但我如何用一张图像进行预测?到目前为止,我对代码还不是很熟悉,但我训练有素的模型似乎运行良好(我正在使用 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)
解决方案
当您在 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)
推荐阅读
- javascript - TS2739 类型“any[]”缺少类型“JSON”的以下属性:parse、stringify、[Symbol.toStringTag]
- json - 使用 *ngFor 在类中显示 Angular 12 类
- ios - ScrollToItemAt in UICollectionView does not work
- openapi - 告诉 OpenAPI TypeScript Fetch API 客户端包含所有请求的凭据
- python - 如何使用 Python 绘制 ROC 曲线和精度?
- python - 如何将 2 个 LSTM 的输出合并为另一个 LSTM 的输入
- html - 图像填充从其他内容继承高度的整个容器区域(没有设置高度)
- csv - Perl:如何将文件行(CSV 文件)读入哈希键并将它们按升序排序,然后将它们写入新排序的 CSV 文件
- docker - 运行 docker compose 时 pika 异常 amqpconnectionerror 错误
- hyperlink - Doxygen:如何从我的主页引用 README.md 文件