You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow运行线性回归代码报Placeholder_1占位符需传float值错误

错误根因

计算测试损失的代码存在依赖错误:

原代码中测试损失计算行:test_loss = tf.square(test_y - train_label)

这里错误使用了训练标签占位符train_label参与测试损失计算,而非预期的测试标签占位符test_label。调用sess.run(test_loss)时,feed_dict仅传入了test_x、test_label两个占位符的取值,计算图依赖的train_label没有被传值,因此触发了未喂值的InvalidArgumentError,报错信息中的Placeholder_1即对应按定义顺序排列的第二个占位符train_label。

修复方案
  1. 修正测试损失的计算逻辑,将计算式中的train_label替换为test_label即可解决报错:
test_loss = tf.square(test_y - test_label)
  1. (可选优化)当前损失为单样本平方差,训练过程波动较大,可改为取均值让训练过程更平稳:
train_loss = tf.reduce_mean(tf.square(train_y - train_label))
test_loss = tf.reduce_mean(tf.square(test_y - test_label))
修复后完整代码
import tensorflow as tf
import numpy as np
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
tf.compat.v1.disable_eager_execution()

def get_data(number):
    list_x = []
    list_label = []
    for i in range(number):
        # y=2x+10
        x = np.random.randn(1)
        label = 2 * x + np.random.randn(1) * 0.01 + 10
        list_x.append(x)
        list_label.append(label)
    return list_x, list_label

def inference(x):
    weight = tf.compat.v1.get_variable("weight", [1])
    bias = tf.compat.v1.get_variable("bias", [1])
    y = x * weight + bias
    return y

train_x = tf.compat.v1.placeholder("float32")
train_label = tf.compat.v1.placeholder("float32")
test_x = tf.compat.v1.placeholder("float32")
test_label = tf.compat.v1.placeholder("float32")

with tf.compat.v1.variable_scope("inference"):
    train_y = inference(train_x)
    tf.compat.v1.get_variable_scope().reuse_variables()
    test_y = inference(test_x)

train_loss = tf.reduce_mean(tf.square(train_y - train_label))
test_loss = tf.reduce_mean(tf.square(test_y - test_label))
opt = tf.compat.v1.train.GradientDescentOptimizer(0.002)
train_op = opt.minimize(train_loss)

init = tf.compat.v1.global_variables_initializer()
train_data_x, train_data_label = get_data(1000)
test_data_x, test_data_label = get_data(1)

with tf.compat.v1.Session() as sess:
    sess.run(init)
    for i in range(1000):
        sess.run(train_op, feed_dict={train_x: train_data_x[i], train_label: train_data_label[i]})
        if i % 10 == 0:
            test_loss_value = sess.run(test_loss, feed_dict={test_x: test_data_x[0], test_label: test_data_label[0]})
            print("step %d eval loss is %.3f" %(i, test_loss_value))

内容的提问来源于stack exchange,提问作者Liang kaixin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:39:03