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

数据挖掘 机器学习 深度学习 喀拉斯 张量流 预言
2022-03-12 06:19:35

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

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

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

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

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% 的图块来训练模型,然后我将其保存并在以下脚本中重复使用:

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))
0个回答
没有发现任何回复~