gpt4 book ai didi

python - 如何测试我在真实图片上训练过的 tensorflow 模型?

转载 作者:行者123 更新时间:2023-12-05 06:08:01 24 4
gpt4 key购买 nike

我已经使用 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 文件吗?对不起,如果我的问题是 super 基本/显而易见的,我只是很困惑,不知道该怎么做。提前致谢

最佳答案

我认为您正在寻找的是 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)

关于python - 如何测试我在真实图片上训练过的 tensorflow 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65215762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com