对于一次线性回归,就是求w 和 b 的值,针对预测值 y(x) = w*x + b, 真实值 y ,使其满足min(k) = (y^i - y(x^i))^2 ,其中 i 为第i个数,即 x^1为 x1,y^1为y1;若序列集合为 x:[x1,x2,…], y:[y1,y2,….]
如图所示,如果直接将 b 设置为 0,那么相当于 求 y(x) = w*x 中的 w,那么可以直接手动得到关于 w的方程式
k = 30* (w^2 - 2*w + 1)
这个是抛物线方程,对其求导可以得到 k’ = 2*w - 2,我的理解,当我们使用梯度下降时,就是类似
w(j+1) = w(j) - a*k';
其中 k’ 就是图中的 三角形y,我们w值越逼近 1,三角形y的值越小,这个当w初始值幅值为4后,通过上面的公式,下一个w值 w(j+1)就是 w(j) 减去一个增量,这个增量在不断的减小,进而w值将慢慢的向1 靠近
注(该方法可能存在的问题-自己的理解):
1.如果手动自己演算下该过程也会发现,如果 a的值过大,就会出现震荡的现象(就是两个值不停的循环)
2.如果a的值很小,而训练中的次数较小,可能 w还没有到达 值 1 就已经训练结束了,这个时候得到的最小值不是全局最小值,仅仅是局部最小值
下面是tensflow线性回归代码(也可以称为线性拟合)
#!/user/bin/env python
import tensorflow as tf
#W 和 b 赋予初值
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
#1.创建线程方程
linear_model = W*x + b
y = tf.placeholder(tf.float32)
# 2.平方损失-最小二乘法 loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer 创建梯度下降法,a的值为 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_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
#训练了 1000 次
for i in range(1000):
sess.run(train, {x: x_train, y: y_train})
# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))