import tensorflow as tf
import numpy as np
# create data
x_data = np.random.rand(100).astype(np.float32) # 生成100個(gè)隨機(jī)數(shù)
y_data = x_data * 0.1 + 0.3 # 根據(jù)x_data定義y_data
### create tensorflow struncture start ###
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)) # 變量Weights
biases = tf.Variable(tf.zeros([1])) # 偏差biases
y = Weights * x_data + biases # 線性公式
loss = tf.reduce_mean(tf.square(y - y_data)) # 減少誤差值
optimizer = tf.train.GradientDescentOptimizer(0.5) # 添加優(yōu)化器
train = optimizer.minimize(loss) # 訓(xùn)練讓誤差變小
init = tf.initialize_all_variables() # 初始化所有的變量
### create tensorflow struncture end ###
sess = tf.Session() # 創(chuàng)建會話
sess.run(init) # Very important # 會話執(zhí)行變量
for step in range(201):
sess.run(train) # 會話執(zhí)行訓(xùn)練
if step % 20 == 0:
print (step,sess.run(Weights),sess.run(biases)) # 每訓(xùn)練20步把訓(xùn)練后的變量Weights和biases打印出來
輸出
0 [ 0.64301312] [ 0.0098274]
20 [ 0.23328485] [ 0.22950047]
40 [ 0.132642] [ 0.28273439]
60 [ 0.10799415] [ 0.2957716]
80 [ 0.10195781] [ 0.29896447]
100 [ 0.10047947] [ 0.29974639]
120 [ 0.10011742] [ 0.2999379]
140 [ 0.10002875] [ 0.29998481]
160 [ 0.10000702] [ 0.29999632]
180 [ 0.10000173] [ 0.29999909]
200 [ 0.10000043] [ 0.29999977]
最后Weights和biases會訓(xùn)練成正確的值.