'Tensor'对象没有属性'assign'

时间:2019-07-08 21:21:23

标签: tensorflow

我将使用google clab运行以下代码

import numpy as np
from sklearn.datasets import fetch_california_housing
import tensorflow as tf
from sklearn.preprocessing import StandardScaler

housing = fetch_california_housing()
m,n = housing.data.shape
scaler = StandardScaler()
scaled_data = scaler.fit_transform(housing.data)
scaled_data_biased = np.c_[np.ones(shape=  (m,1),dtype=np.float32),scaled_data]

lr = 0.1
n_epoches = 1000
X = tf.Variable(scaled_data_biased,dtype = tf.float32, name = "X")
y = tf.Variable(housing.target,dtype = tf.float32,name="y")
theta = tf.random_uniform(shape=(n+1,1),minval=-1,
                      maxval=1,dtype = tf.float32, name = "theta")

y_pred = tf.matmul(X,theta)
mse = tf.reduce_mean(tf.square(y-y_pred))
grad = tf.gradients(mse,theta)[0]
learn_theta = tf.assign(theta,theta-lr*grad)

init = tf.global_variables_initializer()

sess = tf.Session()
with tf.Session() as sess: 
     init.run()
     for i in range(n_epoches):
         learn_theta.eval()
         if(i%100 is 0): 
             print(mse)

但是我遇到了以下错误

AttributeError                            Traceback (most recent call last)

<ipython-input-54-750024cac1f5> in <module>()
     20 mse = tf.reduce_mean(tf.square(y-y_pred))
     21 grad = tf.gradients(mse,theta)[0]
---> 22 learn_theta = tf.assign(theta,theta-lr*grad)
     23 
     24 init = tf.global_variables_initializer()

/usr/local/lib/python3.6/dist-packages/tensorflow/python    /ops/state_ops.py in assign(ref, value, validate_shape, use_locking, name)
    226         ref, value, use_locking=use_locking, name=name,
    227         validate_shape=validate_shape)
--> 228   return ref.assign(value, name=name)
    229 
    230 

AttributeError: 'Tensor' object has no attribute 'assign'

我的代码中的tf.assign操作是否有问题?似乎tf.assign是对tf.Variable对象的常规操作。我代码中的theta是一个tf.Variable,对其进行的操作均合法。

0 个答案:

没有答案