Tensorflow教程(一)

calong發表於2020-09-22
pip3 install tensorflow
import tensorflow as tf
with tf.compat.v1.Session() as session:
    session.run([...])
    # 執行初始化變數
    session.run(init)
    # Feed賦值
    print(session.run(iMul, feed_dict={input2: [7.0], input3: [3.0]}))
# 宣告常量
m1 = tf.compat.v1.constant([[3, 3]])
# 宣告變數
var = tf.Variable([1, 2])
# 初始化變數
init = tf.compat.v1.global_variables_initializer()
# 變數賦值
update = tf.compat.v1.assign(counter, new_value)
# 佔位符宣告變數
input = tf.compat.v1.placeholder(tf.float32)
# 構建線性模型
tf.compat.v1.disable_eager_execution()
x_data = np.random.rand(100)
y_data = x_data * 0.1 + 0.2
k = tf.compat.v1.Variable(0.)
b = tf.compat.v1.Variable(0.)
y = k * x_data + b
# 二次代價函式
loss = tf.compat.v1.reduce_mean(tf.square(y_data - y))
# 定義梯度下降法訓練優化器
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.2)
# 最小化代價函式
train = optimizer.minimize(loss)
# 初始化變數
init = tf.compat.v1.global_variables_initializer()
# 定義會話
with tf.compat.v1.Session() as session:
    # 執行初始化變數
    session.run(init)
    # 擬合訓練
    for step in range(201):
        session.run(train)
        if step % 20 == 0:
            print(step, session.run([k, b]))

執行結果

0 [0.052299168, 0.09965591]
20 [0.10233624, 0.1987706]
40 [0.10136684, 0.19928078]
60 [0.10079966, 0.19957922]
80 [0.10046784, 0.19975384]
100 [0.100273706, 0.19985598]
120 [0.10016012, 0.19991575]
140 [0.10009368, 0.19995071]
160 [0.1000548, 0.19997117]
180 [0.10003207, 0.19998313]
200 [0.10001877, 0.19999012]
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章