线性回归的代码运行异常

运行异常的结果是 (python3.6,TensorFlow1.11)

File “/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/eager/backprop.py”, line 869, in gradient
output_gradients=output_gradients)
File “/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/eager/imperative_grad.py”, line 63, in imperative_grad
tape._tape, vspace, target, sources, output_gradients) # pylint: disable=protected-access
AttributeError: ‘RefVariable’ object has no attribute ‘_id’
源码如下,复制的文档中的代码运行也是这个错误,多谢大佬指导问题所在!谢谢!
import numpy as np
import tensorflow as tf
tf.enable_eager_execution
X_raw = np.array ([2013, 2014, 2015, 2016, 2017], dtype=np.float32)
y_raw = np.array ([12000, 14000, 15000, 16500, 17500], dtype=np.float32)

X = (X_raw - X_raw.min ()) / (X_raw.max () - X_raw.min ())
y = (y_raw - y_raw.min ()) / (y_raw.max () - y_raw.min ())

X = tf.constant (X)
y = tf.constant (y)

a = tf.get_variable (‘a’, dtype=tf.float32, shape=[], initializer=tf.zeros_initializer)
b = tf.get_variable (‘b’, dtype=tf.float32, shape=[], initializer=tf.zeros_initializer)
variables = [a, b]

num_epoch = 10000
optimizer = tf.train.GradientDescentOptimizer (learning_rate=1e-3)
for e in range (num_epoch):
# 使用 tf.GradientTape () 记录损失函数的梯度信息
with tf.GradientTape () as tape:
y_pred = a * X + b
loss = 0.5 * tf.reduce_sum (tf.square (y_pred - y))
# TensorFlow 自动计算损失函数关于自变量(模型参数)的梯度
grads = tape.gradient (loss, variables)
# TensorFlow 自动根据梯度更新参数
optimizer.apply_gradients (grads_and_vars=zip (grads, variables))


抖蕊咪发嗖啦嘻 2018-10-11 23:16:46

tf.enable_eager_execution

改成

tf.enable_eager_execution ()

试试?

在 python 3.6, tensorflow 1.11 (cpu, gpu) 环境下都测试通过。


xiaoming 发表于 2018-10-16 17:36:25