1. 程式人生 > >python TensorFlow 測試程式碼

python TensorFlow 測試程式碼

import tensorflow as tf
import numpy as np

#create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3

###create tensorflow structure start ###
Weight = tf.Variable(tf.random_uniform([1],-1.0,1.0))  #一維向量,從-1.0到1.0
biases = tf.Variable(tf.zeros([1]))                    #一維0向量

y = Weight*x_data + biases
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)    #梯度下降優化器
train = optimizer.minimize(loss)                      #訓練器

init = tf.initialize_all_variables()                   #初始化變數
###create tensorflow structure end ###

sess = tf.Session()                                   #建立會話
sess.run(init)                                        #啟用整個神經網路very important

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

輸出結果:

0 [0.6798785] [-0.03761964]
20 [0.20823106] [0.2404822]
40 [0.11992885] [0.28904086]
60 [0.10366957] [0.29798207]
80 [0.10067568] [0.29962844]
100 [0.10012442] [0.2999316]
120 [0.10002291] [0.2999874]
140 [0.10000422] [0.2999977]
160 [0.10000079] [0.29999956]
180 [0.10000015] [0.29999992]
200 [0.10000005] [0.29999998]

來自:《莫煩python》