import numpy as np
import tensorflow as tf
from sklearn.datasets import fetch_california_housing
# 载入数据
housing = fetch_california_housing()
m, n = housing.data.shape
print(m, n)
# 在开头增加一列偏置,该列值均为1
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
print(housing_data_plus_bias.shape)
$$ \widehat{y} = X \cdot \theta $$ $$\widehat{\theta} = (X^T \cdot X)^{-1} \cdot X^T \cdot y$$
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)