我是机器学习的新手,我在网上找到了这个迁移学习模型,可能这个问题看起来很简单,但我该如何用单张图片在这个模型上进行预测呢?目前我对代码还不太熟悉,但我训练的模型似乎运行得很好(我在使用Google Colab)。
import pandas as pdimport numpy as npimport osimport kerasimport matplotlib.pyplot as pltfrom keras.layers import Dense,GlobalAveragePooling2Dfrom keras.applications import MobileNetfrom keras.preprocessing import imagefrom keras.applications.mobilenet import preprocess_inputfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.models import Modelfrom keras.optimizers import Adambase_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.x=base_model.outputx=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 2x=Dense(512,activation='relu')(x) #dense layer 3preds=Dense(4,activation='softmax')(x) #final layer with softmax activationmodel=Model(inputs=base_model.input,outputs=preds)#specify the inputs#specify the outputs#now a model has been created based on our architecturefor layer in model.layers[:20]: layer.trainable=Falsefor layer in model.layers[20:]: layer.trainable=Truefrom zipfile import ZipFilefile_name = 'thecar.zip'with ZipFile(file_name, 'r') as zip: zip.extractall() print('Done')train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependenciestrain_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 accuracystep_size_train=train_generator.n//train_generator.batch_sizemodel.fit_generator(generator=train_generator, steps_per_epoch=step_size_train, epochs=5)
回答:
这可能是对你问题的进一步扩展。如果你仍然有你的模型可用,当然你不需要重新加载它。此外,如果你只有一个图像,你可以只定义单个图像的路径。在下面的代码中,我涵盖了你保存了模型并且现在使用它来对一个或多个图像进行预测的情况。将你想要预测的一个或多个图像放置在一个目录中。然后执行下面的代码
import tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras.models import load_modelimport numpy as npimport cv2import osmodel_location =r'c:\temp\people\Mobilenet-99.00.h5' # location of the saved modelmodel=load_model(model_location) # load the saved modelimage_location=r'c:\temp\people\storage' # directory storing the images that you want to predictfile_list=os.listdir(image_location) # list of filesfor 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] )