TensorFlow线性回归代码运行报FailedPreconditionError找不到weights变量
问题根因分析
- 变量初始化顺序错误:现有代码先执行
tf.compat.v1.initialize_all_variables().run()初始化变量,之后才通过loss()、train()方法创建W、b等模型变量,等于初始化时变量还未生成,自然会触发未初始化报错。 - 多余的队列操作代码:输入数据直接从Python列表转换为张量,没有用到队列输入逻辑,
start_queue_runners相关代码完全冗余,删除即可消除对应警告。 - 重复创建未初始化变量:
evaluate方法中重复调用inference会生成新的W、b变量,这些新变量也未经过初始化,会进一步触发找不到变量的报错。
修复方案
以下是可直接运行的完整修复代码:
import tensorflow as tf # TF2环境下运行TF1.x静态图语法需要先关闭eager执行 tf.compat.v1.disable_eager_execution() # 提前定义模型变量,避免每次调用inference重复生成新变量 W = tf.Variable(tf.zeros([2, 1]), name="weights") b = tf.Variable(0., name="bias") def inference(X): return tf.linalg.matmul(X, W) + b def inputs(): weight_age = [[84, 46], [73, 20], [65, 52], [70, 30], [76, 57], [69, 25], [63, 28], [72, 36], [79,57], [75,44], [27,24], [89,31], [65,52], [57,23], [59,60], [69,48], [60,34], [79,51], [75,50], [82,34], [59,46], [67,23], [85,37], [55, 40], [63,30]] blood_fat_content = [354, 190, 405, 263, 451, 302, 288, 385, 402, 365, 209, 290, 346, 254, 395, 434, 220, 374, 308, 220, 311, 181, 274, 303, 244] return tf.compat.v1.to_float(weight_age), tf.compat.v1.to_float(blood_fat_content) def train(total_loss): learning_rate = 0.0000001 return tf.compat.v1.train.GradientDescentOptimizer(learning_rate).minimize(total_loss) def evaluate(sess): print(sess.run(inference([[80., 25.]]))) print(sess.run(inference([[65., 25.]]))) def loss(X, Y): Y_predicted = inference(X) return tf.math.reduce_sum(tf.math.squared_difference(Y_predicted, Y)) with tf.compat.v1.Session() as sess: X, Y = inputs() total_loss = loss(X, Y) train_op = train(total_loss) # 变量初始化必须放在所有计算图节点、变量定义完成之后 tf.compat.v1.initialize_all_variables().run() training_steps = 1000 for step in range(training_steps): sess.run([train_op]) if step % 10 == 0: print("loss: ", sess.run([total_loss])) evaluate(sess) sess.close()
关键改动说明
- 开头添加
tf.compat.v1.disable_eager_execution(),兼容TF2环境下运行TF1.x静态图语法 - 将W、b变量提取为全局定义,避免每次调用
inference生成新的未初始化变量 - 调整变量初始化的位置,放到所有变量、计算图节点定义完成之后
- 删除所有队列相关的冗余代码,消除对应警告
内容的提问来源于stack exchange,提问作者Trần Vỹ Khang
相关产品推荐
相关产品推荐

