【问题标题】:How can I test a tensorflow model which I have trained on a real-life picture?如何测试我在真实图片上训练过的张量流模型?
【发布时间】:2021-03-20 18:26:34
【问题描述】:

我用KerasTensorflow 训练了一个模型,并生成了一个保存模型的.h5 文件。这是我的代码(我只包含了模型而不是数据处理 sn-p 以便它更具可读性):

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 文件吗?抱歉,如果我的问题是超级基本/显而易见的,我只是很困惑,不知道该怎么做。提前致谢

【问题讨论】:

    标签: python tensorflow keras hdf5


    【解决方案1】:

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

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

    predict 函数接受一个 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)
    

    【讨论】:

    • 我是否必须将图像 "thumbs_up.jpg" 转换为 numpy 数组?
    • 是的,predict 函数接受一个 numpy 数组。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      相关资源
      最近更新 更多