In [2]:
import numpy as np
import tensorflow as tf
from sklearn.datasets import fetch_california_housing
/usr/local/lib/python3.5/dist-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
In [3]:
# 载入数据
housing = fetch_california_housing()
m, n = housing.data.shape
Downloading Cal. housing from https://ndownloader.figshare.com/files/5976036 to /home/yahei/scikit_learn_data
INFO:sklearn.datasets.california_housing:Downloading Cal. housing from https://ndownloader.figshare.com/files/5976036 to /home/yahei/scikit_learn_data
In [5]:
print(m, n)
20640 8
In [6]:
# 在开头增加一列偏置,该列值均为1
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
In [9]:
print(housing_data_plus_bias.shape)
(20640, 9)

构造计算图

$$ \widehat{y} = X \cdot \theta $$ $$\widehat{\theta} = (X^T \cdot X)^{-1} \cdot X^T \cdot y$$

In [10]:
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)
In [11]:
with tf.Session() as sess:
    theta_value = theta.eval()
In [12]:
print(theta_value)
[[-3.7465141e+01]
 [ 4.3573415e-01]
 [ 9.3382923e-03]
 [-1.0662201e-01]
 [ 6.4410698e-01]
 [-4.2513184e-06]
 [-3.7732250e-03]
 [-4.2664889e-01]
 [-4.4051403e-01]]