TensorFlow学习笔记-实现Linear Regression

TensorFlow的输入输出是被称为张量的多维数组(因此被称为“tensor flow”),就像NumPy数组一样,张量具有类型和形状,NumPy中用ndarray表示。以下代码操作二维数组对加利福尼亚的房屋数据进行线性回归,数据集可以自行百度搜索即可。获取数据集后,向所有的训练实例中添加一个额外的偏置输入特征(X0=1),之后创建两个TensorFlow常量节点x和y保存该数据和目标,并且使用TensorFlow提供的一些矩阵运算来定义theta,这些矩阵函数transpose(),matmul()和matrix_inverse()分别表示矩阵的转置,矩阵的相乘和矩阵的取逆运算,它们不会立即计算,而是在图形中创建运行图形时执行它们的节点。我们的目标是计算\boldsymbol{\theta =(X^{T}.X)^{-1}.X^{T}.y},最后创建一个session会话来求出theta的值。代码如下:

import numpy as np
from sklearn.datesets import fetch_california_housing
housing = fetch_california_housing()
m,n = housing.data.shape()
#np.c_按column来组合array
housing_data_plus_bias = np.c_[np.ones((m,1)),housing.data]

X = tf.constant(housing_data_plus_bias,dtype=tf.float32,name="X")
y = tf.constant(housing.target.reshape(-1,1),dtype = tf.float32,name="y")
XT = tf.transpose(X)
theta = tf.matmul(tf.matual(tf.matrix(tf.matmul(XT,X)),XT),y)
with tf.Session() as sess:
    theta_value=theta.eval()
print(theta_value)

这里其实就是用了最小二乘法计算\theta

下面介绍通过使用批量梯度下降,而不是普通方程来训练模型,首先我们通过手动计算梯度来实现,然后使用TensorFlow的自动扩展功能来使TensorFlow自动计算梯度,最后使用几个TensorFlow的优化器。当使用梯度下降时,首先要对输入的特征向量进行归一化,否则训练可能会慢得多。

手动计算梯度

 以下代码大部分很简单,除了几个新元素:

  • random_uniform() 函数在图形中创建一个节点,它将生成包含随机值的张量,给定其形状和值作用域,就像NumPy中的rand()函数一样。
  • aaign()函数创建一个为变量分配新值的节点。在这种情况下,它实现了批次梯度下降步骤\theta (nextstep)=\theta-\eta \bigtriangledown _{\theta }MSE(\theta).

主循环一次又一次(共n_epocchs次)执行训练步骤,每100迭代都打印出当前的均方差误差(MSE),正确的结果MSE应该每次都会减小。代码如下:

houing = fetch_california_housing()
m,n = housing.data.shape
housing_data_plus_bias = np.c_[np.ones((m,1)),housing.data]
scaled_housing_data_plus_bias=scale(housing_data_plus_bias)
n_epochs=1000
learning_rate=0.01
X=tf.constant(scaled_housing_plus_bias,dtype=tf.float32,name="X")
y=tf.constant(housing.target.reshape(-1,1),dtype=tf.float32,name="y")
theta=-tf.Variable(tf.random_unofprm([n+1,1],-1.0,1.0),name="theta")
y_pred=tf.matmul(X,theta,name="predictions")
error=y_pred-y
mse=tf.reduce_mean(tf.square(error),name="mse")
gradients=2/m*tf.matmul(tf.transdpose(X),error)
training_op=tf.assign(theta,theta-leaing_rate*gradients)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    sess.ruin(init)
    for epoch in range(n_epochs):
        if epoch%100==0:
            print("Epoch",epoch,"MSE =",mse.eval())
        sess.run(training_op)
     best_theta=theta.eval()

这里计算梯度时使用了函数的微积分,但是当要求导的函数很复杂的时候这种方法就变得很容易出错,尤其是要使用深度神经网络来进行计算的时候,幸运的是TensorFlow的自动计算梯度功能可以计算这个公式,只需要将上面代码中的gradients=.....换为:gradients=tf.gradients(mse,[theta])[0]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值