0

我已经创建了 CNN,并且正在尝试弄清楚如何针对它测试随机图像。我正在使用 Keras 和 Tensorflow。假设我想测试在这里找到的图像: https ://i.ytimg.com/vi/7I8OeQs7cQA/maxresdefault.jpg 。

我将如何保存模型,加载它然后针对它测试这个图像?这是我在网上找到的一些示例代码,说明了我的意思: https ://meta.stackexchange.com/questions/144665/hide-email-address-from-my-profile

非常感谢任何帮助,谢谢!

在此处输入图像描述

import os
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, Image

from keras.models import Sequential, load_model
from keras.layers import Conv2D, Flatten, MaxPooling2D, Input
from keras.preprocessing.image import ImageDataGenerator

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import models, layers

X = []
y = []

from sklearn.model_selection import train_test_split

labels = os.listdir(r'C:/Users/zF1bo/Desktop/natural_images')
labels



for label in labels:
    path = r'C:/Users/zF1bo/Desktop/natural_images/{}/'.format(label)
    img_data = os.listdir(path)
    
    for image in img_data:
        a = cv2.imread( path + image)
        a = cv2.resize(a, (64, 64))
        X.append(np.array(a.astype('float32')) / 255)
        y.append(label)


buckets = []
for i in y:
    if i == 'airplane':
        buckets.append(0)
    elif i == 'car':
        buckets.append(1)
    elif i == 'cat':
        buckets.append(2)
    elif i == 'dog':
        buckets.append(3)
    elif i == 'flower':
        buckets.append(4)
    elif i == 'fruit':
        buckets.append(5)
    elif i == 'motorbike':
        buckets.append(6)
    elif i == 'person':
        buckets.append(7)


y = buckets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, \
        random_state = 0)


model = models.Sequential()
model.add(layers.Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=(64,64,3)))
model.add(layers.MaxPool2D(pool_size=(2, 2)))
model.add(layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
model.add(layers.MaxPool2D(pool_size=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(8, activation='softmax'))

model.compile(optimizer='adam', loss = 'sparse_categorical_crossentropy',metrics=['accuracy'])

y_train = np.array(y_train)

model.fit(X_train, y_train, batch_size=(256), epochs=25)

pred = model.predict(X_test)

diff = []
for i in pred:
    diff.append(np.argmax(i))

from sklearn.metrics import accuracy_score

accuracy_score(diff,y_test)
4

2 回答 2

0

第 1 步:保存模型

model.save('model.h5')

第 2 步:加载模型

loaded_model = tensorflow.keras.models.load_model('model.h5')

第 3 步:通过 requests 库下载图片(答案来自:通过 urllib 和 python 下载图片):

import urllib.request 
urllib.request.urlretrieve(url, filename)

否则,您可以应用与您发布的第一张图片相同的步骤。不要忘记expand_dims()

于 2020-10-12T05:26:49.867 回答
0

您可以使用 mode.save('path to save location') 保存您的模型。要输入您应该阅读的图像,请执行您对训练图像所做的任何预处理,然后使用 model.predict,如下面的代码所示。

import tensorflow as tf
from tensorflow import keras
model = keras.models.load_model('path/to/location') # loads the saved model
pred_img =r'path to the img'
img=cv2.imread (pred_img)
img=img/255 # rescale the image
print(img.shape)
img=cv2.resize(img, (64,64)) # resize to same size used in training
print (img.shape)
img=np.expand_dims(img, axis=0)
print (img.shape)
pred=model.predict(img)
print (pred)  # will be a list of 8 elements select the element in the list with the highest probability
index=np.argmax(pred)) # this will be the index of the class predicted
class_name=buckets[index] # this will be the name of the class predicted
print (class_name)

请注意,如果您使用 cv2 读取训练图像,请记住顺序是 bgr 而不是 rgb。该模型是在 bgr 图像上训练的。当您在图像中读取以进行预测时,它也必须是 bgr。

于 2020-10-12T05:37:46.783 回答