Tensorflow2 图像分类-Flowers数据深度学习图像预测的两种方法

上一篇文章中说明了数据深度学习模型保存、读取、参数查看和图像预测等方法,但是图像预测部分没有详细说明,只是简单预测了单张图片,实际应用过程中,我们需要预测大量的图片数据。本文中将详细介绍两种预测方法即详细代码,将输出预测结果和精度报告,具体如下:

1.预测测试集和所有数据

使用model.predict(ds,verbose=1)预测

在模型训练中,采用tf.keras.preprocessing.image_dataset_from_directory()函数读取文件中的图片数据,文件夹中的子文件夹名称即为图片类别。

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.9,
    subset='training',
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)
test_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.9,
    subset='validation',
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)

 1.1预测测试集

model = tf.keras.models.load_model(model_path)

#预测测试集精度
predictions = model.predict(test_ds,verbose=1)
predicted_classes = tf.argmax(predictions, axis=1)
pred_list = predicted_classes.numpy().tolist()

#获取标签数据
labels = []
for images, labels_batch in test_ds:
    labels.append(labels_batch.numpy())
labels = tf.concat(labels, axis=0)
# 输出预测结果
print(predicted_classes)
df=pd.DataFrame()
list_predict=list(predicted_classes)
df['true']=labels
df['pre']=pred_list
df.to_csv(model_path.replace('.h5','_Val.csv'))
# 计算分类指标
report = classification_report(labels, pred_list)

1.2预测所有数据

如果预测所有数据,可以将训练集和测试集合并,然后进行预测。不过顺序打乱了。

#预测所有数据精度
# 合并训练集和验证集
data_all = train_ds.concatenate(test_ds)  顺序可能变化,重新读取文件夹中的左右数据集
predictions = model.predict(data_all)
predicted_classes = tf.argmax(predictions, axis=1)
pred_list = predicted_classes.numpy().tolist()

#获取标签数据
labels = []
for images, labels_batch in data_all:
    labels.append(labels_batch.numpy())
labels = tf.concat(labels, axis=0)
# 输出预测结果
print(predicted_classes)
df=pd.DataFrame()
list_predict=list(predicted_classes)
df['true']=labels
df['pre']=pred_list
df.to_csv('IP224_predictions_all_20230410.csv')
# report = classification_report(labels, pred_list)
with open('IP224_predictions_report.txt', 'w') as f:
    f.write(classification_report(labels, pred_list))

 还可以重新一次性读取包含所有图片的文件夹数据,然后进行预测,并输出预测结果保存为csv和精度报告txt文件。

代码如下:

data_dir1='RadarData/ALLData'
data_all=tf.keras.preprocessing.image_dataset_from_directory(
    data_dir1,
    validation_split=None,
    #validation_split设置值为None 不区分训练集和测试集
    #如果你不设置 validation_split 参数,tf.keras.preprocessing.image_dataset_from_directory
    # 函数将会从给定目录中读取所有的数据,并将其划分为训练集和验证集两部分,默认比例是80%训练集和20%验证集。
    # subset='training',
    # seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)

predictions = model.predict(data_all)
predicted_classes = tf.argmax(predictions, axis=1)
pred_list = predicted_classes.numpy().tolist()

#获取标签数据
labels = []
for images, labels_batch in data_all:
    labels.append(labels_batch.numpy())
labels = tf.concat(labels, axis=0)
# 输出预测结果
print(predicted_classes)
df=pd.DataFrame()
list_predict=list(predicted_classes)
df['true']=labels
df['pre']=pred_list
df.to_csv('IP224_predictions_all_20230410.csv')
# report = classification_report(labels, pred_list)
with open('IP224_predictions_report.txt', 'w') as f:
    f.write(classification_report(labels, pred_list))

 2.遍历预测所有图片数据

代码如下:

# 遍历预测所有图片 效率较低
# pri_data_dir = tf.keras.utils.get_file('pavia_9red_all',origin="")
data_dir1='RadarData/ALLData'
pri_data_dir = pathlib.Path(data_dir1)

sunflower_path=list(pri_data_dir.glob('*/*.png'))
f=open(Outputfilename+"_Pre_all.csv","w")
for i in range(len(sunflower_path)):
    img = keras.preprocessing.image.load_img(
        sunflower_path[i], target_size=(img_height, img_width)
    )
    img_array = keras.preprocessing.image.img_to_array(img)
    img_array = tf.expand_dims(img_array, 0)  # Create a batch

    predictions = model.predict(img_array)
    # print('predictions:',predictions)
    # predictions_classes = model.predict_classes(img_array)
    predictions_classes=np.argmax(model.predict(img_array), axis=-1)
    print('predictions_classes:',predictions_classes)
    score = tf.nn.softmax(predictions[0])
    filepath=str(sunflower_path[i])
    filepath_list = filepath.split("\\")
    filename = filepath_list[-1]
    filename = filename[:-4]
    print(filename)
    # print("{}{:.2f}".format(class_names[np.argmax(score)], 100 * np.max(score)))
    # print(predictions_classes)
    true_class=filename.split('_')[0]  #真实类别
    ID = filename.split('_')[1]  # 真实类别
    print('真实类别是:',true_class)
    line = filename+","+true_class+","+ID+","+"{},{:.2f}".format(class_names[np.argmax(score)], 100 * np.max(score))+"," + str(predictions_classes[0]) + '\n'
    f.write(line)
    #print(filename,".png write completed!")
print("compute completed!")
f.close()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空中旋转篮球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值