저는 기계 학습을 처음 접했고이 전이 학습 모델을 온라인에서 찾았습니다. 사소한 질문처럼 보일 수 있지만 단일 이미지로 어떻게 예측을 할 수 있습니까? 지금은 코드에 익숙하지 않지만 훈련 된 모델이 잘 작동하는 것 같습니다 (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)
이것은 귀하의 질문에 대한 약간의 확장 일 수 있습니다. 여전히 모델을 사용할 수있는 경우에는 물론로드 할 필요가 없습니다. 또한 하나의 이미지 만있는 경우 단일 이미지에 대한 경로를 정의 할 수 있습니다. 아래 코드에서는 모델을 저장하고 이제 하나 이상의 이미지를 예측하는 데 사용하는 경우를 다루었습니다. 예측하려는 하나 이상의 이미지를 디렉토리에 배치하십시오. 그런 다음 아래 코드를 실행하십시오.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import os
model_location =r'c:\temp\people\Mobilenet-99.00.h5' # location of the saved model
model=load_model(model_location) # load the saved model
image_location=r'c:\temp\people\storage' # directory storing the images that you want to predict
file_list=os.listdir(image_location) # list of files
for f in file_list: # iterate through the files in the directory list
f_path=os.path.join(image_location, f) # create the path to the image file
img=cv2.imread(f_path) # read in the image - note cv2 reads in images in BGR format
img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # model was trained on RGB images so convert to RGB
img=cv2.resize(img, (128,128)) # model was trained on images of size 128 X 128 X 3 so resize the images
img=img/127.5-1 # model was trained with pixel value scalled between -1 to +1 so convert the pixel range
img=np.expand_dims(img, axis=0) # model predict expects the input to have dimension (batch_size, width, height, bands)
#print (img.shape) # uncomment to see effect of expanding dimension
prediction =model.predict (img, batch_size=1, verbose=0) # make predictions
pred=np.argmax(prediction)# find the index of the column with the highest probability
print ('for file ', f_path, ' the index of the predicted class is ', pred, ' with a probability of ', prediction[0][pred] )
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다