如何测试我在真实图片上训练过的张量流模型?

How can I test a tensorflow model which I have trained on a real-life picture?

我已经用 KerasTensorflow 训练了一个模型,并生成了一个 .h5 文件来保存模型。这是我的代码(我只包含了模型而不是数据处理片段,这样它会更具可读性):

ts = 0.3 # Percentage of images that we want to use for testing. The rest is used for training.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=ts, random_state=42)

# Import of keras model and hidden layers for our convolutional network
from keras.models import Sequential
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.layers import Dense, Flatten

from tensorflow.python.client import device_lib
from keras import backend as K

# Construction of model
model = Sequential()
model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(120, 320, 1))) 
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu')) 
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))

# Configures the model for training
model.compile(optimizer='adam', # Optimization routine, which tells the computer how to adjust the parameter values to minimize the loss function.
              loss='sparse_categorical_crossentropy', # Loss function, which tells us how bad our predictions are.
              metrics=['accuracy']) # List of metrics to be evaluated by the model during training and testing.

# Trains the model for a given number of epochs (iterations on a dataset) and validates it.
model.fit(X_train, y_train, epochs=5, batch_size=64, verbose=2, validation_data=(X_test, y_test))

# Save entire model to a HDF5 file
model.save('handrecognition_model.h5')

我已经在 this 包含手势照片的数据集上训练了我的模型。现在我有一张用笔记本电脑相机拍摄的照片,可以说它叫做 "thumbs_up.jpg",它包含一张我竖起大拇指的照片。我想把这张照片放在我训练的模型上,看看它是否能正确预测。我知道我可能在这里遗漏了一些非常基本的东西,但我该怎么做呢?我应该以某种方式使用 .h5 文件吗?抱歉,如果我的问题超级 basic/obvious 我只是很困惑,不知道该怎么做。提前致谢

您只需添加 model.predict(yourList) 即可预测您需要输入的任何值

我想你要找的是tensorflow内置的predict()函数。您还可以使用 evaluate() 函数在多个测试图像上评估您的模型。这是解释如何完成的指南:https://www.tensorflow.org/guide/keras/train_and_evaluate?hl=en

# Evaluate the model on the test data using `evaluate`
print("Evaluate on test data")
results = model.evaluate(x_test, y_test, batch_size=128)
print("test loss, test acc:", results)

# Generate predictions (probabilities -- the output of the last layer)
# on new data using `predict`
print("Generate predictions for 3 samples")
predictions = model.predict(x_test[:3])
print("predictions shape:", predictions.shape)

您甚至不必保存模型。只需从保存路径加载图像即可。

预测函数接受一个 numpy 数组。您可以使用 cv2 库将图像读取为 numpy 数组。这是我使用的过程:

# read image
image = cv2.imread(image_path)
# resize image
dimensions = (img_height, img_width)
image = cv2.resize(image, dimensions)
# change color channels form bgr to rgb
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# normalise data
image = (image/255).astype(np.float16)
# add image to array
image_data = np.concatenate(image)