Python机器学习（四）-线性回归

# 1。导入数据，数据清洗，详见Python机器学习-数据预处理

import numpy as np

import pandas as pd

data = data.replace(to_replace='?', value=np.nan)

data = data.dropna(how='any')

print(data.shape)

column_names = data.columns # column_names=list(data.columns)

print(column_names)

from pandas.plotting import scatter_matrix

features = ['Length (mm)', 'Width (mm)', 'Peak Long', 'Peak Lat']

scatter_matrix(data[features], alpha=0.2, figsize=(12,8))

corr_matrix = data.corr()

print(corr_matrix['Peak Lat'].sort_values(ascending=False))

#3。数据训练集、测试集划分

from sklearn.cross_validation import train_test_split

x_train, x_test, y_train, y_test = train_test_split(data[column_names[0:43]],

data[column_names[43]], test_size=0.25, random_state=33)

#4。从sklearn调入线性回归，数据拟合，测试集数据预测

from sklearn.linear_model import LinearRegression

lr = LinearRegression()

lr.fit(x_train, y_train)

lr_y_predict = lr.predict(x_test)

lr_y_predict_train=lr.predict(x_train)

#5。模型评估，并输出线性回归的各特征的系数

from sklearn.metrics import r2_score,mean_squared_error,mean_absolute_error

print('The value of R-squared of LinearRegression is %.4f:'%(r2_score(y_test,lr_y_predict)))

print('The value of Mean_squared_error of Linear Regression is %.4f:'%(mean_squared_error(y_test,lr_y_predict)))

print('The value of Mean_absolute_error of Linear Regression is %.4f:'%(mean_absolute_error(y_test,lr_y_predict)))

print('The maximum LinearRegressor prediction error is: %.2f%%'%(100*max((lr_y_predict-y_test)/y_test)))

print('Linear regression coefficients:', lr.coef_)

#5。预测结果写入excel表

writer1 = pd.ExcelWriter('LinearPrediction_RRC.xlsx')

df1 = pd.DataFrame(lr_y_predict)

df1.to_excel(writer1,'Sheet1')

writer1.save()

#6。图形输出训练集、测试集预测值与真值得散点图（红色为训练集，蓝色为测试集）

import matplotlib.pyplot as plt

plt.figure()

plt.scatter(lr_y_predict,y_test,marker='X',s=5,c='blue')

plt.scatter(lr_y_predict_train,y_train,marker='X',s=5,c='red')

plt.title('LinearRegressor prediction vs true value')

plt.xlabel('lr_y_predict')

plt.ylabel('y_true value')

plt.show()

#7。新数据预测

x_new=data_new[column_names[0:43]]

y_new=data_new[column_names[43]]

lr_y_new_predict=lr.predict(x_new)

print('prediction with all features:',lr_y_new_predict)

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20180607G063H700?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2022-01-18

2022-01-18

2022-01-18

2022-01-18

2018-06-25

2022-01-18

2022-01-18

2022-01-18

2022-01-18

2022-01-18