编程思路:
- 导入相关包
- 导入数据集
- 处理数据格式
- 构建算法(最小二乘)
- 创建Session执行图
最小二乘公式:
"""
tensorflow 实现线性回归案例
"""
import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing
# 装载数据
housing = fetch_california_housing(data_home='C:/Users/Mcdonald/Documents/workplace/Pycharm/scikit_learn_data',
download_if_missing=True)
# 查看数据信息
m, n = housing.data.shape
print(m, n)
print(housing.data, housing.target)
print(housing.feature_names)
# 准备数据,构建图
"""
m行 n列 -> 添加一列偏置列(x0)
直接二乘法处理
"""
housing_data_with_bias = np.c_[np.ones((m, 1)), housing.data]
X = tf.constant(housing_data_with_bias, name='X')
''''
y = tf.constant(housing.target, name='y')
print(y.shape) # (20640,) 显然这个格式不行 -- 需要变成二维数组格式
'''
y = tf.constant(housing.target.reshape(-1, 1), 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)