用TensorFlow训练线性和逻辑回归模型
这一节结合前面介绍的所有TensorFlow概念来训练线性和逻辑回归模型,使用玩具数据集。
用TensorFlow训练模型
假如我们指明了数据点和标签的容器,定义了张量操作的损失函数。添加了优化器节点到计算图,它可以用来计算梯度下降。我们如何重复进行梯度下降来学习数据集呢?
答案是用Python for-循环。代码块 Example 3-10说明这个简单的学习过程。注意为了简化教学我们不使用 minibatches 。后面训练大数据集时会用minibatches。
使用TensorFlow的线性回归
这一节我们用Tensor‐Flow 定义线性回归,并学习它的权重。任务很直接,你可以不用TensorFlow完成。但是,使用TensorFlow 是很好的练习因为它可以将我们学习过的概念一起使用。
用TensorFlow定义和训练线性回归
线性回归模型很简单:
y = wx + b
这里 w 和 b 是我们要学习的权重。我们转换这些权重至tf.Variable对象。然后用张量操作来构建损失函数 L2 loss:
ℒ( x, y)=( y − wx − b) 2
List3-24的代码用TensorFlow实现这些数学操作。添加tf.train.AdamOp 优化器来学习以及tf.summary操作来合用TensorBoard。
#List3-24. Defining a linear regression model
#定义模型函数
def model(x,w,b):
return tf.multiply(x,w)+b
def loss_fun(x,y,w,b):
err = model(x,w,b)-y
squared_err = tf.square(err)
return tf.reduce_mean(squared_err)
def grad(x,y,w,b):
with tf.GradientTape() as tape:
loss_ = loss_fun(x,y,w,b)
return tape.gradient(loss_,[w,b])
List3-25 训练模型 (不用 minibatches).
#List3-25. Training the linear regression model
w = tf.Variable(np.random.randn(),tf.float32)
b = tf.Variable(0.0,tf.float32)
#设置迭代次数和学习率
train_epochs = 100
learning_rate = 0.01
loss = []
y_pred=[]
count = 0
display_count = 10 #控制显示粒度的参数,每训练10个样本输出一次损失值
#开始训练,轮数为epoch,采用SGD随机梯度下降优化方法
for epoch in range(train_epochs):
for xs,ys in zip(x_np,y_np):
#计算损失,并保存本次损失计算结果
#rand_index = np.random.choice(100)
#rand_x = tf.cast([x_vals[rand_index]],dtype=tf.float32)
#rand_y = tf.cast([y_vals[rand_index]],dtype=tf.float32)
loss_ =loss_fun(xs,ys,w,b)
loss.append(loss_)
#计算当前[w,b]的梯度
delta_w,delta_b = grad(xs,ys,w,b)
change_w = delta_w * learning_rate
change_b = delta_b * learning_rate
w.assign_sub(change_w)
b.assign_sub(change_b)
#训练步数加1
count = count +1
if count % display_count == 0:
print('train epoch : ','%02d'%(epoch+1),'step:%03d' % (count),'loss= ','{:.9f}'.format(loss_))
为线性回归取梯度
线性回归模型的方程为 y = wx + b
其中 w, b是可学习权重。我们前面提过,这个系统的损失是 ℒ =( y − wx − b)2。可以用上些矩阵微积分来计算可学习参数的梯度:
以及
这些方程仅给有好奇心读者参考。我们不会系统的教如何求损失函数的微分。