Python 代码示例:随机展示测试样本并预测其标签
Python 代码示例:随机展示测试样本并预测其标签
该代码示例使用 Python 的 random 库随机选择测试样本,并使用机器学习模型预测其标签。同时,代码会展示样本图像,并显示预测结果和实际标签,方便直观地评估模型性能。
for i in range(20):
rand_num = random.randint(1,1000)
label = np.where(y_test[rand_num])[0][0]
#计算one-hot
pixels = x_test[rand_num]
pixels = pixels.reshape((128,128,3))
plt.title('Label is ' + str(label))
plt.imshow(pixels,cmap='gray')
plt.show()
print('测试样本第{}个,预测结果是{}'.format(rand_num,classes_x[rand_num]))
if classes_x[rand_num] != label:
print('预测错误')
标签修改说明:
你可以修改以下代码中的 str(label) 为你想要的标签,例如 '类别' + str(label),或者直接替换成具体的标签名称。
plt.title('Label is ' + str(label))
代码说明:
random.randint(1,1000):随机选择一个测试样本,索引范围为 1 到 1000。np.where(y_test[rand_num])[0][0]:获取测试样本的实际标签。plt.title('Label is ' + str(label)):设置图像标题,显示实际标签。plt.imshow(pixels,cmap='gray'):展示样本图像,使用灰色色系。print('测试样本第{}个,预测结果是{}'.format(rand_num,classes_x[rand_num])):打印样本序号和预测结果。if classes_x[rand_num] != label::判断预测结果是否与实际标签一致,若不一致则打印“预测错误”。
原文地址: https://www.cveoy.top/t/topic/oubc 著作权归作者所有。请勿转载和采集!