1. 程式人生 > 其它 >Tensorflow基礎程式碼報錯學習筆記3——Variable變數

Tensorflow基礎程式碼報錯學習筆記3——Variable變數

技術標籤:tensorflow學習筆記pythontensorflow機器學習

原教程地址之Variable變數
先貼原始碼

import tensorflow as tf 

tf.compat.v1.disable_eager_execution()#這一句為了讓run正常執行
state = tf.Variable(0,name='counter')
#print(state.name)
one = tf.constant(1)

new_value = tf.add(state,one)
update = tf.assign(state,new_value)

#定義變數後最重要的一步:初始化#
init = tf.compat.v1.global_variables_initializer()#這一步並沒有啟用# with tf.compat.v1.Session() as sess: sess.run(init) for _ in range(3): sess.run(update) print(sess.run(state))

按照慣例,上一篇教程遇到的問題在這一篇就直接改,之後修改的都是新遇到的問題。

1
今天遇到的版本問題:
AttributeError: module ‘tensorflow’ has no attribute 'assign’


在這裡插入圖片描述
修改為

update = tf.compat.v1.assign(state,new_value)

2
python基礎問題:
for_in range(3)
^
SyntaxError: invalid syntax

在這裡插入圖片描述
因為照著up的螢幕輸入,沒有看清是否有空格
檢視程式碼為:

for_in range(3):

改為

for _ in range(3):

實際上這個報錯還有可能是新手問題裡忘記加冒號導致的
這裡面的下劃線“_”是做一個變數的,相當於“i”,或者第一篇筆記中的“step”。

修改好後的輸出結果為:

第一次print(已被註釋掉)
在這裡插入圖片描述
迴圈裡的print()
在這裡插入圖片描述
最後附上修改好的完整程式碼:

import tensorflow as tf 

tf.compat.v1.disable_eager_execution()
state = tf.Variable(0,name='counter')
#print(state.name)
one = tf.constant(1)

new_value = tf.add(state,one)
update = tf.compat.v1.assign(state,new_value)

#定義變數後最重要的一步:初始化#
init = tf.compat.v1.global_variables_initializer()#這一步並沒有啟用#

with tf.compat.v1.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))