我最近開始使用tensorflow,剛剛嘗試了一些模擬數據的線性迴歸模型。我有以下代碼,我正在使用GradientDescentOptimizer
來訓練兩個變量w
和b
(我使用numpy隨機初始化)。模型完成培訓後,我想看看這些變量,看看它們與實際值有多接近。 (我忽略了代碼的其他部分,因爲它們與問題無關)。因此,當會話退出with tf.Session()...
時,我使用sess = tf.Session()
打開默認會話並嘗試使用sess.run(w)
,但我迎接Attempting to use uninitialized value train_weights
。這是預料之中的。所以我想到了使用sess.run(tf.global_variables_initializer())
,但只是簡單地將w
的值初始化。所以,問題是 - 我怎麼訪問變量的最終值已在tensorflow會話被改變鑑於會議已經關閉Tensorflow:關閉會話後訪問受過訓練的變量
_ = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(_)
for epoch in range(n_epochs):
for batch_pos in range(num_batches):
x_batch = X[batch_ind[batch_pos]:batch_ind[batch_pos+1]]
y_batch = Y[batch_ind[batch_pos]:batch_ind[batch_pos+1]]
sess.run(optimizer, feed_dict = {x_train_batch: x_batch,\
y_train_batch: y_batch})
cost_ = sess.run(cost, feed_dict = {x_train_batch: x_batch,\
y_train_batch: y_batch})
if (epoch)%display_rate == 0:
print('Epoch:', epoch+1, 'Cost: ', cost_)
sess = tf.Session()
# sess.run(tf.global_variables_initializer())
sess.run(w)