Table of Contents
第四章 Tensorflow实现简单线性回归
第四章 Tensorflow实现简单线性回归
在了解TensorFlow中图的使用后,利用Tensorflow实现一个简单的线性回归来进一步理解Tensorflow的使用。
4.1 实现代码
将《机器学习实战》中有关tensorflow线性回归的代码进行了一个简单的复现,并添加了一些注释。下面这段代码实现了对加州住房数据的线性回归的计算,整体难度不大。
# 导入相关包
import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing
# 构建计算图
housing = fetch_california_housing()
m,n = housing.data.shape
## 为数据添加偏差项,即添加y=ax+b中的b
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.matmul(tf.matrix_inverse(tf.matmul(XT,X)),XT),y)
# 执行计算图
with tf.Session() as sess:
theta_value = theta.eval()
print(theta_value)
结果如下:
[[-3.7171074e+01]
[ 4.3633682e-01]
[ 9.3871783e-03]
[-1.0717344e-01]
[ 6.4540231e-01]
[-4.1238391e-06]
[-3.7809242e-03]
[-4.2373490e-01]
[-4.3720812e-01]]
代码中的一些函数及包的详细介绍可参考Tensorflow的简单总结
4.2 参考
[1] Geron.机器学习实战