1
行變量優化之後是多個哈希(#)符號如何在tensorflow訪問一個單獨的函數創建的代碼興趣
爲了理解的目的我運行在tensorflow簡單線性迴歸。使用的代碼IM是:
def generate_dataset():
#y = 2x+e where is the normally distributed error
x_batch = np.linspace(-1,1,101)
y_batch = 2*x_batch +np.random.random(*x_batch.shape)*0.3
return x_batch, y_batch
def linear_regression(): ##################
x = tf.placeholder(tf.float32, shape = (None,), name = 'x')
y = tf.placeholder(tf.float32, shape = (None,), name = 'y')
with tf.variable_scope('lreg') as scope: ################
w = tf.Variable(np.random.normal()) ##################
y_pred = tf.multiply(w,x)
loss = tf.reduce_mean(tf.square(y_pred - y))
return x,y, y_pred, loss
def run():
x_batch, y_batch = generate_dataset()
x, y, y_pred, loss = linear_regression()
optimizer = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init)
feed_dict = {x: x_batch, y: y_batch}
for _ in range(30):
loss_val, _ = session.run([loss, optimizer], feed_dict)
print('loss:', loss_val.mean())
y_pred_batch = session.run(y_pred, {x:x_batch})
print(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)) ############
print(session.run(fetches = [w])) #############
run()
我不能似乎能夠獲取變量(它實際上是一個運算?)的值「W」與取回調用任一「W」或「LREG/w',如果我理解正確的是由於'w'在linear_regression()中定義的事實,並且它不借助其名稱空間來運行()。但是,我可以通過對其變量名'lreg/vairable:0'的訪問來訪問'w'。優化器工作得很好並且更新被完美應用
優化器如何訪問'w'並應用更新,如果您能夠讓我深入瞭解'w'如何在linear_regression( )並運行()
非常感謝你的反應。我有一個後續問題:爲什麼從run()運行時拋出一個錯誤print(session.run(fetches = [w]))? NameError:名稱'w'未定義。想要提醒你print(session.run(fetches = ['lreg/variable:0'])取得'w'的值 – Nitin
你必須保持python變量和tensorflow變量分離在你的腦海中。 Tensorflow圖有一個名爲w的變量,並不意味着python在當前範圍內有一個名爲w的變量。 – Aaron