自己的理解:线性回归是一个特征值对应的一个目标值,即目标依赖于一个特征;而多元回归就是多个特征值对应一个目标值,即目标依赖于多个特征或者多个变量。以Boston为例,研究一下回归模型。
载入相关的库:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets as skds
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
加载sklearn库中的数据集并查看描述:提取x,这是一个特征矩阵,y是代码中的目标向量,重塑y使其转化成二维的,并将x中的特征缩放为均值为零和标准方差为1的特征。
#加载keras库的数据集并查看描述,
boston=skds.load_boston()
print(boston.DESCR)
x_data=boston.data.astype(np.float32)
y_data=boston.target.astype(np.float32)
if(y_data.ndim==1):
y_data=y_data.reshape(len(y_data),1)
x_data=StandardScaler().fit_transform(x_data) #将x中的特征缩放为均值为0和标准方差为1的特征。
接下来使用多个特征进行建模,定义损失函数,优化器,并进行训练模型。
x_train,x_test,y_train,y_test=train_test_split(x_data,y_data,
test_size=.4,random_state=123)
num_inputs=x_train.shape[1]
num_outputs=y_train.shape[1]
x=tf.placeholder(tf.float32,[None,num_inputs],name='x')
y=tf.placeholder(tf.float32,[None,num_outputs],name='y')
weights=tf.Variable(tf.zeros([num_inputs,num_outputs]),tf.float32,name='w')
biases=tf.Variable(tf.zeros([num_outputs]),tf.float32,name='b')
model=tf.matmul(x,weights)+biases
loss=tf.reduce_mean(tf.square(model-y))
#mse和R2函数
mse=tf.reduce_mean(tf.square(model-y))
y_mean=tf.reduce_mean(y)
total_error=tf.reduce_sum(tf.square(y-y_mean))
unexplained_error=tf.reduce_sum(tf.square(y-model))
rs=1-tf.div(unexplained_error,total_error)
learning_rate=0.001
train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
num_epochs=1500
loss_epochs=np.empty([num_epochs],np.float32)
mse_epochs=np.empty([num_epochs],np.float32)
rs_epochs=np.empty([num_epochs],np.float32)
mse_score=0
rs_score=0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(num_epochs):
feed_dict={x:x_train,y:y_train}
loss_val,_=sess.run([loss,train_step],feed_dict)
loss_epochs[epoch]=loss_val
feed_dict={x:x_test,y:y_test}
mse_score,rs_score=sess.run([mse,rs],feed_dict)
mse_epochs[epoch]=mse_score
rs_epochs[epoch]=rs_score
print('For test data : MSE = {0:.8f}, R2 = {1:.8f}'.format(mse_score,rs_score))
模型获得输出:
绘制均方误差图:
plt.figure(figsize=(14,8))
plt.axis([0,num_epochs,0,np.max(loss_epochs)])
plt.plot(loss_epochs,label='Loss on X_train')
plt.title('Loss in Iteration')
plt.xlabel('# Epoch')
plt.ylabel('MSE')
plt.axis([0,num_epochs,0,np.max(mse_epochs)])
plt.plot(mse_epochs,label='MSE on X_train')
plt.title('MSE in Iteration')
plt.xlabel('# Epoch')
plt.ylabel('MSE')
plt.legend()
plt.show()
绘制r平方值图:
plt.figure(figsize=(14,8))
plt.axis([0,num_epochs,0,np.max(rs_epochs)])
plt.title('R-squared in Iterayion')
plt.plot(rs_epochs,label='R2 on X_test')
plt.xlabel('# Epoch')
plt.ylabel('R2')
plt.legend()
plt.show()