![](/img/trans.png)
[英]How do I convert this code from Tensorflow version 1 to version 2?
[英]How do I convert the following in tensorflow version 2
%tensorflow_version 1.x
import tensorflow as tf
print(tensorflow.__version__)
w = tf.Variable(0, dtype = tf.float32)
cost = w**2 - 8*w + 16
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
init = tf.global_variables_initializer()
session = tf.Session()
session.run(init)
for i in range(1000):
session.run(train)
print(session.run(w))
#3.994
我用谷歌搜索了這些東西,但沒有得到任何結論,當我使用 tf-vr-2 時,該程序會計算多項式的因子
import tensorflow as tf
w = tf.Variable(0, dtype = tf.float32)
@tf.function
def cost():
return w**2 - 8*w + 16
train = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01)
for i in range(1000):
train.minimize(loss=cost, var_list=[w])
tf.print(w)
從 TF1 到 TF2 的幾個變化:
keras
模塊中,但是有一個別名tf.optimizers
可以使用。 GradientDescentOptimizer
可以用沒有動量的SGD
代替@tf.function
裝飾器可用於將 function 跟蹤到圖表中,從而提高性能。 這不是強制性的。init
操作。遷移指南可能會有所幫助。
import tensorflow as tf
w = tf.Variable(0, dtype = tf.float32)
@tf.function
def cost():
return w**2 - 8*w + 16
train = tf.optimizers.SGD(learning_rate=0.01)
for i in range(1000):
train.minimize(loss=cost, var_list=[w])
print(w)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.