python - 从保存的模型进行预测时,测试数据预测会产生随机结果

标签 python tensorflow machine-learning deep-learning keras

我正在使用 Keras 和 TensorFlow 对平铺成 256x256 block 的航拍图像进行分类。该模型将训练数据(即构成研究区域的 256x256 图像 block )分成 70% 的训练数据和 30% 的验证数据。使用顺序模型,然后使用图像数据生成器。最后,拟合生成器用于将模型拟合到数据。然后将模型保存为 h5 格式,用于预测不同研究区域中其他图像的类别。

当我使用 70%/30% 训练/验证分割运行模型时,验证图像的预测效果很好,准确度越来越高,每个时期的损失稳步下降。此外,当我通过将概率数组连接到表示图 block 边界的矢量多边形来可视化预测(即概率数组)时,分类结果看起来非常好。

我的问题是当我使用保存的 h5 模型对新图像进行预测时——结果是荒谬的,并且每个图 block 都是随机的。就好像概率数组被随机打乱,以至于当我将结果加入矢量图像边界图 block 时,结果看起来完全随机。我该如何解决这个问题?

以下是用于训练模型的代码的相关部分:

base_model = applications.VGG16(weights='imagenet', include_top=False, input_shape=(img_rows, img_cols, img_channel))

add_model = Sequential()
add_model.add(Flatten(input_shape=base_model.output_shape[1:]))
add_model.add(Dense(256, activation='relu'))
add_model.add(Dense(n_classes, activation='sigmoid')) # n classes

model = Model(inputs=base_model.input, outputs=add_model(base_model.output))
model.compile(loss='binary_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
              metrics=['accuracy'])

######################

batch_size = 32
epochs = 50

print('Running the image data generator...')
train_datagen = ImageDataGenerator(
        rotation_range=30, 
        width_shift_range=0.1,
        height_shift_range=0.1, 
        horizontal_flip=True)
train_datagen.fit(x_train)

print('Fitting the model...')
history = model.fit_generator(
    train_datagen.flow(x_train, y_train, batch_size=batch_size),
    steps_per_epoch=x_train.shape[0] // batch_size,
    epochs=epochs,
    #validation_data=(x_valid, y_valid),
    #callbacks=[ModelCheckpoint(model_checkpoint, monitor='val_acc', save_best_only=True)]
)

######################

## Predict
#print('Predicting...')
#p_valid = model.predict(x_valid, batch_size=128)

## Write predictions to csv
#print('Saving predictions to CSV...')
#df = pd.DataFrame(p_valid)
#df['image'] = split + 1 + df.index 
#df.to_csv(out_csv, index=False, header=False)

""" 
Save model, including these details:
-the architecture of the model, allowing to re-create the model
-the weights of the model
-the training configuration (loss, optimizer)
-the state of the optimizer, allowing to resume training exactly where you left off.
"""
print("Saving model")
model.save("/vgg16-model-50epochs.h5")

print('Processing complete.')

以下脚本使用上面保存的模型对来自不同研究区域的测试图像进​​行预测。请注意,在上面的最终训练运行中没有 70/30 的训练/验证拆分——我只是使用 100% 的图 block 来训练模型,然后我将其保存并在以下脚本中重复使用:

import glob, os, time
import cv2
import numpy as np
import pandas as pd

from keras.models import load_model
#from keras.models import model_from_json

# Path to the input tiles which will be used to predict classes
inws = '/image-directory-for-another-study-area'
tiles = glob.glob(os.path.join(inws, '*.tif'))

# h5 file from trained model
in_h5 = "/vgg16-model-50epochs.h5"

# Output model predictions in csv format
out_csv = '/new-predictions.csv'

# Read images and convert to numpy array
x_test = np.array([cv2.imread(tile) for tile in tiles], np.float16) / 255.

print('Loading existing model...')
loaded_model = load_model(in_h5)

print("Predicting on image tiles...")
predictions = loaded_model.predict(x_test, batch_size=128)

# Save to csv
df = pd.DataFrame(predictions)
df['image'] = df.index + 1
df.to_csv(out_csv, index=False, header=False)
print("Predictions saved to disk: {0}".format(out_csv))

最佳答案

我高度怀疑这是由于预处理不匹配造成的,即您对 x_trainx_test 应用了不同的预处理。

因为你没有说明x_train是如何得到的,所以我无法为你验证。然而,众所周知,预训练的 VGG16 模型使用类似 caffe 的归一化(参见 preprocess_input ),它通过减去 channel 均值来归一化输入图像。请注意,这与您为测试图像所做的不同,

x_test = np.array([cv2.imread(tile) for tile in tiles], np.float16) / 255.

相反,您需要在 keras VGG16 示例中做一些事情

#Extract features with VGG16
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np

model = VGG16(weights='imagenet', include_top=False)

img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x) <---- use this function to preprocess your image

features = model.predict(x)

关于python - 从保存的模型进行预测时,测试数据预测会产生随机结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082882/

相关文章:

python - 在 SciKit-Learn 中同时使用递归特征消除和网格搜索

python - 如何在 python 中拆分字符串并使用分隔符获得结果?

C# 如何将错误追加到 1 个消息框中?

python - Celery:实例在一两周后变得缓慢

TensorFlow:我的(广义)骰子损失实现有什么问题?

machine-learning - 为什么有些摘要没有绘制在张量板上?

machine-learning - 基于 Keras 的神经网络未训练

python - 一个命令可以杀死使用特定端口的进程

python - 保存使用 BatchNorm 的 Tensorflow 模型

python - 使用 class_weight 来不平衡数据-.fit_generator()