TensorFlow自学笔记-05 基于官方文档 多元线性回归
在 TensorFlow 实现简单线性回归的基础上,可通过在权重和占位符的声明中稍作修改来对相同的数据进行多元线性回归。
在多元线性回归的情况下,由于每个特征具有不同的值范围,归一化变得至关重要。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 定义归一化函数
def normalize(X):
mean = np.mean(X)
std = np.std(X)
X = (X - mean)/std
return X
def append_bias_reshape(features, labels):
m = features.shape[0]
n = features.shape[1]
x = np.reshape(np.c_[np.ones(m), features], [m, n + 1])
y = np.reshape(labels, [m, 1])
return x, y
boston = tf.contrib.learn.datasets.load_dataset('boston')
X_train, Y_train = boston.data, boston.target
X_train = normalize(X_train)
X_train, Y_train = append_bias_reshape(X_train, Y_train)
m = len(X_train)
n = 13 + 1
X = tf.placeholder(tf.float32, name='X', shape=[m, n])
Y = tf.placeholder(tf.float32, name='Y')
w = tf.Variable(tf.random_normal([n, 1]))
b = tf.Variable(0.0)
Y_hat = tf.matmul(X, w) + b
loss = tf.reduce_mean(tf.square(Y - Y_hat, name='loss'))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
init_op = tf.global_variables_initializer()
total = []
with tf.Session() as sess:
sess.run(init_op)
writer = tf.summary.FileWriter('graphs', sess.graph)
for i in range(100):
_, l = sess.run([optimizer, loss], feed_dict={X: X_train, Y: Y_train})
total.append(l)
print('Epoch {0}: Loss {1}'.format(i, l))
writer.close()
w_value, b_value = sess.run([w, b])
plt.plot(total)
plt.show()
N = 500
X_new = X_train[N, :]
Y_pred = (np.matmul(X_new, w_value) + b_value).round(1)
print('Predicted value: ${0} Actual value: / ${1}'.format(Y_pred[0]*1000, Y_train[N]*1000), '\nDone')
运行结果:
Predicted value: $23800.0 Actual value: / $[16800.]