解决AttributeError: ‘RefVariable’ object has no attribute 'numpy’报错信息
在做线性回归的时候出现了变量没有numpy属性的错误,百度也未找到相关解决方法,下面将代码奉上,附加解决方案!
import tensorflow as tf
import matplotlib.pyplot as plt
class Model(object):
def __init__(self):
self.W = tf.Variable(5.0)
self.b = tf.Variable(0.0)
def __call__(self, x):
return self.W * x + self.b
def loss(predicted_y, desired_y):
return tf.reduce_mean(tf.square(predicted_y - desired_y))
TRUE_W = 3.0
TRUE_b = 2.0
NUM_EXAMPLES = 1000
inputs = tf.random_normal(shape=[NUM_EXAMPLES])
noise = tf.random_normal(shape=[NUM_EXAMPLES])
outputs = inputs * TRUE_W + TRUE_b + noise
def train(model, inputs, outputs, learning_rate):
with tf.GradientTape() as t:
current_loss = loss(model(inputs), outputs)
dW, db = t.gradient(current_loss, [model.W, model.b])
model.W.assign_sub(learning_rate * dW)
model.b.assign_sub(learning_rate * db)
model = Model()
Ws, bs = [], []
epochs = range(10)
for epoch in epochs:
Ws.append(model.W.numpy())
bs.append(model.b.numpy())
current_loss = loss(model(inputs), outputs)
train(model, inputs, outputs, learning_rate=0.1)
print('Epoch %2d: W=%1.2f b=%1.2f, loss=%2.5f' %
(epoch, Ws[-1], bs[-1], current_loss))
plt.plot(epochs, Ws, 'r',
epochs, bs, 'b')
plt.plot([TRUE_W] * len(epochs), 'r--',
[TRUE_b] * len(epochs), 'b--')
plt.legend(['W', 'b', 'true W', 'true_b'])
plt.show()
运行之后发现报错信息如下:
WARNING:tensorflow:From E:\Workspace\pycharm\tensorflow\venv\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
Traceback (most recent call last):
File "E:/Workspace/pycharm/tensorflow/example/tensorflow_example/tensorflow_02.py", line 48, in <module>
Ws.append(model.W.numpy())
AttributeError: 'RefVariable' object has no attribute 'numpy'
Process finished with exit code 1
解决方式,在程序之前加入如下代码,报错信息即可消除,程序正常运行:
tf.enable_eager_execution(
config=None,
device_policy=None,
execution_mode=None
)