如何使用TensorFlow Gradient Tape对新数据集进行预测?
TensorFlow Gradient Tape 预测与准确率计算问题解决
问题核心
熟悉model.fit()的训练流程,但不理解Gradient Tape场景下的预测逻辑,误将模型前向传播输出的张量当作模型实例调用.predict()方法,触发错误:
'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'predict'
目标是完成测试集预测后,对比预测值与真实值计算准确率。
错误原因
network_output = trained_network(input_images,input_number)得到的是模型前向传播后的输出张量,而非模型本身。只有Keras模型实例才有.predict()方法,不能用张量调用该方法。
正确实现步骤
1. 测试集预测
Gradient Tape仅用于训练阶段记录梯度,预测时直接用训练好的trained_network(模型实例)对测试数据做前向传播即可:
# 对测试数据执行前向传播,得到输出张量 test_network_output = trained_network(test_images, test_number) # 将张量转为numpy数组后,用argmax获取预测类别索引 predicted_number = np.argmax(test_network_output.numpy(), axis=1)
2. 准确率计算优化
避免低效循环,用numpy向量化操作更简洁高效:
# 注意:如果test_number是one-hot编码,先转成类别索引;若本身就是索引则跳过此步 true_labels = np.argmax(test_number, axis=1) # 统计匹配数量并计算准确率 correct_count = np.sum(predicted_number == true_labels) accuracy = (correct_count / len(test_images)) * 100 print(f"Accuracy: {accuracy:.2f}%")
完整示例代码
# 训练完成后执行预测 test_output = trained_network(test_images, test_number) preds = np.argmax(test_output.numpy(), axis=1) # 处理真实标签(根据数据格式调整) true_labels = np.argmax(test_number, axis=1) if test_number.ndim > 1 else test_number # 计算并打印准确率 correct = np.sum(preds == true_labels) acc = (correct / len(test_images)) * 100 print(f"测试集准确率: {acc:.2f}%")
内容的提问来源于stack exchange,提问作者Relative0
相关产品推荐
相关产品推荐

