昨天写了Tensorflow的初体验,感觉不错,再接再励,就把官方教程上的机器学习demo码出来自己看看,总结总结。
这是官方教程上的第一个机器学习的教程,做一个简单求线性函数,的斜率W和Bias的demo,用的方法是梯度下降法,就是从变化速度最快的方向优化系数,具体的方法讲解我还需要回忆和复习,在tensorflow里这类算法已经成熟的打包了,直接调用就好。
在demo程序里我增加了部分我的理解注释,这样看起来会更容易明白。
import tensorflow as tf
# Model parameters(原始参数)
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output(占位符,声明变量)
x = tf.placeholder(tf.float32)
linear_model = W*x + b
y = tf.placeholder(tf.float32)
# loss (损失函数,相减的平方再求和)
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer (最小下降法的步长为0.01)
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data (数据)
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop (训练过程)
init = tf.global_variable