# 用scikit-learn和pandas学习线性回归

from http://www.cnblogs.com/pinard/p/6016029.html
by 刘建平Pinard

# 1. 获取数据，定义问题

PE=θ0+θ1AT+θ2V+θ3AP+θ4RH

$PE={\theta }_{0}+{\theta }_{1}\ast AT+{\theta }_{2}\ast V+{\theta }_{3}\ast AP+{\theta }_{4}\ast RH$

${\theta }_{0},{\theta }_{1},{\theta }_{2},{\theta }_{3},{\theta }_{4}$

# 3. 用pandas来读取数据

import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import pandas as pd
from sklearn import datasets, linear_model

# read_csv里面的参数是csv在你电脑上的路径，此处csv文件放在notebook运行目录下面的CCPP目录里
data = pd.read_csv('.\CCPP\ccpp.csv')

#读取前五行数据，如果是最后五行，用data.tail()
data.head()

AT V AP RH PE
0 8.34 40.77 1010.84 90.01 480.48
1 23.64 58.49 1011.40 74.20 445.75
2 29.74 56.90 1007.15 41.91 438.76
3 19.07 49.69 1007.22 76.79 453.09
4 11.80 40.66 1017.13 97.20 464.43

# 4. 准备运行算法的数据

data.shape

X = data[['AT', 'V', 'AP', 'RH']]
X.head()

AT V AP RH
0 8.34 40.77 1010.84 90.01
1 23.64 58.49 1011.40 74.20
2 29.74 56.90 1007.15 41.91
3 19.07 49.69 1007.22 76.79
4 11.80 40.66 1017.13 97.20

y = data[['PE']]
y.head()

PE
0 480.48
1 445.75
2 438.76
3 453.09
4 464.43

# 5. 划分训练集和测试集

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)

print X_train.shape
print y_train.shape
print X_test.shape
print y_test.shape

(7176, 4)
(7176, 1)
(2392, 4)
(2392, 1)

可以看到75%的样本数据被作为训练集，25%的样本被作为测试集。


# 6. 运行scikit-learn的线性模型

from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
linreg.fit(X_train, y_train)

print linreg.intercept_
print linreg.coef_

[ 447.06297099]
[[-1.97376045 -0.23229086  0.0693515  -0.15806957]]

PE=447.062970991.97376045AT0.23229086V+0.0693515AP0.15806957RH

$PE=447.06297099-1.97376045\ast AT-0.23229086\ast V+0.0693515\ast AP-0.15806957\ast RH$

# 7. 模型评价

#模型拟合测试集
y_pred = linreg.predict(X_test)
from sklearn import metrics
# 用scikit-learn计算MSE
print "MSE:",metrics.mean_squared_error(y_test, y_pred)
# 用scikit-learn计算RMSE
print "RMSE:",np.sqrt(metrics.mean_squared_error(y_test, y_pred))

MSE: 20.0804012021
RMSE: 4.48111606657

X = data[['AT', 'V', 'AP']]
y = data[['PE']]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
linreg.fit(X_train, y_train)
#模型拟合测试集
y_pred = linreg.predict(X_test)
from sklearn import metrics
# 用scikit-learn计算MSE
print "MSE:",metrics.mean_squared_error(y_test, y_pred)
# 用scikit-learn计算RMSE
print "RMSE:",np.sqrt(metrics.mean_squared_error(y_test, y_pred))

MSE: 23.2089074701
RMSE: 4.81756239919
　　　　可以看出，去掉RH后，模型拟合的没有加上RH的好，MSE变大了。

# 8. 交叉验证

　　　　我们可以通过交叉验证来持续优化模型，代码如下，我们采用10折交叉验证，即cross_val_predict中的cv参数为10：
X = data[['AT', 'V', 'AP', 'RH']]
y = data[['PE']]
from sklearn.model_selection import cross_val_predict
predicted = cross_val_predict(linreg, X, y, cv=10)
# 用scikit-learn计算MSE
print "MSE:",metrics.mean_squared_error(y, predicted)
# 用scikit-learn计算RMSE
print "RMSE:",np.sqrt(metrics.mean_squared_error(y, predicted))

MSE: 20.7955974619
RMSE: 4.56021901469

# 9. 画图观察结果

fig, ax = plt.subplots()
ax.scatter(y, predicted)
ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4)
ax.set_xlabel('Measured')
ax.set_ylabel('Predicted')
plt.show()

（欢迎转载，转载请注明出处。欢迎沟通交流： pinard.liu@ericsson.com）