tensorflow实现线性回归
# coding=utf-8
# By author MZ
import tensorflow as tf
from sklearn.datasets import load_boston
import numpy as np
###警告:Your CPU supports instructions that this TensorFlow binary was not compiled to use
###不影响程序的运行,若想彻底解决重新编译(CPU版本)
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
##使用波士顿房价数据
boston = load_boston()
# print(data.data.shape) # 共506行,13列
#m行n列数据
m,n = boston.data.shape
print(boston.data)
# 这里添加一个额外的bias输入特征(x0=1)到所有的训练数据上面,因为使用的numpy所有会立即执行
housing_data_plus_bias = np.c_[np.ones((m, 1)), boston.data]
# 创建两个TensorFlow常量节点X和y,去持有数据和标签
#tf.constant是创建一个常量
X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name='X')
y = tf.constant(boston.target.reshape(-1, 1), dtype=tf.float32, name='y')
# 使用一些TensorFlow框架提供的矩阵操作去求theta
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() # sess.run(theta)
print(theta_value)