文章出处:https://blog.csdn.net/qq_43299522/article/details/108704221,将其中的代码部分全部整理出来用于学习
# In[2]:
# pip install seaborn
# In[3]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Window系统下设置字体为SimHei
plt.rcParams['font.sans-serif'] = ['SimHei']
# Mac系统下设置字体为Arial Unicode MS
# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# In[6]:
from sklearn import datasets
# 加载波士顿房价的数据集
boston = datasets.load_boston()
boston
# In[7]:
# 先要查看数据的类型,是否有空值,数据的描述信息等等。
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
boston_df['PRICE'] = boston.target
# In[8]:
# 查看数据是否存在空值,从结果来看数据不存在空值。
boston_df.isnull().sum()
# 查看数据大小
boston_df.shape
# 显示数据前5行
boston_df.head()
# In[10]:
# 查看数据的描述信息,在描述信息里可以看到每个特征的均值,最大值,最小值等信息。
boston_df.describe()
# In[11]:
# 清洗'PRICE' = 50.0 的数据
boston_df = boston_df.loc[boston_df['PRICE'] != 50.0]
# In[12]:
# 计算每一个特征和房价的相关系数
boston_df.corr()['PRICE']
# In[13]:
# 可以看出LSTAT、PTRATIO、RM三个特征的相关系数大于0.5,这三个特征和价格都有明显的线性关系。
plt.figure(facecolor='gray')
corr = boston_df.corr()
corr = corr['PRICE']
corr[abs(corr) > 0.5].sort_values().plot.bar()
# In[14]:
# LSTAT 和房价的散点图
plt.figure(facecolor='gray')
plt.scatter(boston_df['LSTAT'], boston_df['PRICE'], s=30, edgecolor='white')
plt.title('LSTAT')
plt.show()
# In[15]:
# PTRATIO 和房价的散点图
plt.figure(facecolor='gray')
plt.scatter(boston_df['PTRATIO'], boston_df['PRICE'], s=30, edgecolor='white')
plt.title('PTRATIO')
plt.show()
# In[16]:
# RM 和房价的散点图
plt.figure(facecolor='gray')
plt.scatter(boston_df['RM'], boston_df['PRICE'], s=30, edgecolor='white')
plt.title('RM')
plt.show()
# In[17]:
boston_df = boston_df[['LSTAT', 'PTRATIO', 'RM', 'PRICE']]
# 目标值
y = np.array(boston_df['PRICE'])
boston_df = boston_df.drop(['PRICE'], axis=1)
# 特征值
X = np.array(boston_df)
# In[18]:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.2,
random_state=0)
# In[19]:
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
# In[20]:
from sklearn import preprocessing
# 初始化标准化器
min_max_scaler = preprocessing.MinMaxScaler()
# 分别对训练和测试数据的特征以及目标值进行标准化处理
X_train = min_max_scaler.fit_transform(X_train)
y_train = min_max_scaler.fit_transform(y_train.reshape(-1,1)) # reshape(-1,1)指将它转化为1列,行自动确定
X_test = min_max_scaler.fit_transform(X_test)
y_test = min_max_scaler.fit_transform(y_test.reshape(-1,1))
# In[21]:
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
# 使用训练数据进行参数估计
lr.fit(X_train, y_train)
# 使用测试数据进行回归预测
y_test_pred = lr.predict(X_test)
# In[22]:
# 使用r2_score对模型评估
from sklearn.metrics import mean_squared_error, r2_score
# In[23]:
# 绘图函数
def figure(title, *datalist):
plt.figure(facecolor='gray', figsize=[16, 8])
for v in datalist:
plt.plot(v[0], '-', label=v[1], linewidth=2)
plt.plot(v[0], 'o')
plt.grid()
plt.title(title, fontsize=20)
plt.legend(fontsize=16)
plt.show()
# In[24]:
# 训练数据的预测值
y_train_pred = lr.predict(X_train)
# 计算均方差
train_error = [mean_squared_error(y_train, [np.mean(y_train)] * len(y_train)),
mean_squared_error(y_train, y_train_pred)]
# In[25]:
# 绘制误差图
figure('误差图 最终的MSE = %.4f' % (train_error[-1]), [train_error, 'Error'])
# In[26]:
# 绘制预测值与真实值图
figure('预测值与真实值图 模型的' + r'$R^2=%.4f$' % (r2_score(y_train_pred, y_train)), [y_test_pred, '预测值'],
[y_test, '真实值'])
# In[27]:
# 线性回归的系数
print('线性回归的系数为:\n w = %s \n b = %s' % (lr.coef_, lr.intercept_))