tensorflow從人們到昇仙(1)

tensorflow的hello world


來一段性感的代碼:

import tensorflow as tf
import numpy as np

#創建數據
x = np.random.rand(200).astype(np.float32)
y_data = x * 0.1 + 0.3 # y = weights * x + biases

#搭建模型
weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))

y = weights * x + biases  #神經網絡經典傳遞


#計算誤差,均方差公式
loss = tf.reduce_mean(tf.square(y - y_data))

#誤差傳遞
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

#訓練
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for step in range(401):
    sess.run(train)
    if step % 20 == 0:
        print(step,sess.run(weights),sess.run(biases))

預測結果:

0 [-0.50229931] [ 0.81214285]
20 [-0.05962949] [ 0.38132203]
40 [ 0.06281903] [ 0.31894156]
60 [ 0.09133982] [ 0.30441189]
80 [ 0.09798285] [ 0.30102763]
100 [ 0.09953018] [ 0.30023935]
120 [ 0.09989057] [ 0.30005577]
140 [ 0.09997453] [ 0.30001298]
160 [ 0.09999406] [ 0.30000302]
180 [ 0.09999864] [ 0.3000007]
200 [ 0.09999968] [ 0.30000016]
220 [ 0.0999999] [ 0.30000007]
240 [ 0.0999999] [ 0.30000007]
260 [ 0.0999999] [ 0.30000007]
280 [ 0.0999999] [ 0.30000007]
300 [ 0.0999999] [ 0.30000007]
320 [ 0.0999999] [ 0.30000007]
340 [ 0.0999999] [ 0.30000007]
360 [ 0.0999999] [ 0.30000007]
380 [ 0.0999999] [ 0.30000007]
400 [ 0.0999999] [ 0.30000007]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章