tensorflow训练线性参数

import tensorflow as tf
import numpy as np

# create data
x_data = np.random.rand(100).astype(np.float32) # 生成100个随机数
y_data = x_data * 0.1 + 0.3 # 根据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) # 添加优化器
train = optimizer.minimize(loss) # 训练让误差变小

init = tf.initialize_all_variables() # 初始化所有的变量
### create tensorflow struncture 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(Weights),sess.run(biases)) # 每训练20步把训练后的变量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会训练成正确的值.

你可能感兴趣的