本文共 5587 字,大约阅读时间需要 18 分钟。
作为有监督学习,分类问题是预测类别结果,而回归问题是预测一个连续的结果。
Pandas是一个用于数据探索、数据处理、数据分析的库
import pandas as pd
# read csv file directly from a URL and save the resultsdata = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)# display the first 5 rowsdata.head()
上面显示的结果类似一个电子表格,这个结构称为Pandas的数据帧(data frame)。
pandas的两个主要:Series和DataFrame:
# display the last 5 rowsdata.tail()
# check the shape of the DataFrame(rows, colums)data.shape
特征:
响应:
在这个案例中,我们通过不同的广告投入,预测产品销量。因为响应变量是一个连续的值,所以这个问题是一个回归问题。数据集一共有200个观测值,每一组观测对应一个市场的情况。
import seaborn as sns%matplotlib inline
# visualize the relationship between the features and the response using scatterplotssns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.8)
seaborn的pairplot函数绘制X的每一维度和对应Y的散点图。通过设置size和aspect参数来调节显示的大小和比例。可以从图中看出,TV特征和销量是有比较强的线性关系的,而Radio和Sales线性关系弱一些,Newspaper和Sales线性关系更弱。通过加入一个参数kind='reg',seaborn可以添加一条最佳拟合直线和95%的置信带。
sns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.8, kind='reg')
优点:快速;没有调节参数;可轻易解释;可理解
缺点:相比其他复杂一些的模型,其预测准确率不是太高,因为它假设特征和响应之间存在确定的线性关系,这种假设对于非线性的关系,线性回归模型显然不能很好的对这种数据建模。
线性模型表达式: y=β0+β1x1+β2x2+...+βnxn 其中
在这个案例中: y=β0+β1∗TV+β2∗Radio+...+βn∗Newspaper
# create a python list of feature namesfeature_cols = ['TV', 'Radio', 'Newspaper']# use the list to select a subset of the original DataFrameX = data[feature_cols]# equivalent command to do this in one lineX = data[['TV', 'Radio', 'Newspaper']]# print the first 5 rowsX.head()
# check the type and shape of Xprint type(X)print X.shape
# select a Series from the DataFramey = data['Sales']# equivalent command that works if there are no spaces in the column namey = data.Sales# print the first 5 valuesy.head()
print type(y)print y.shape
from sklearn.cross_validation import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
# default split is 75% for training and 25% for testingprint X_train.shapeprint y_train.shapeprint X_test.shapeprint y_test.shape
from sklearn.linear_model import LinearRegressionlinreg = LinearRegression()linreg.fit(X_train, y_train)
print linreg.intercept_print linreg.coef_
# pair the feature names with the coefficientszip(feature_cols, linreg.coef_)
y=2.88+0.0466∗TV+0.179∗Radio+0.00345∗Newspaper
如何解释各个特征对应的系数的意义?
y_pred = linreg.predict(X_test)
对于分类问题,评价测度是准确率,但这种方法不适用于回归问题。我们使用针对连续数值的评价测度(evaluation metrics)。
下面介绍三种常用的针对回归问题的评价测度
# define true and predicted response valuestrue = [100, 50, 30, 20]pred = [90, 50, 50, 30]
(1)平均绝对误差(Mean Absolute Error, MAE)
1n∑ni=1|yi−yi^|
(2)均方误差(Mean Squared Error, MSE)
1n∑ni=1(yi−yi^)2
(3)均方根误差(Root Mean Squared Error, RMSE)
1n∑ni=1(yi−yi^)2−−−−−−−−−−−−−√
from sklearn import metricsimport numpy as np# calculate MAE by handprint "MAE by hand:",(10 + 0 + 20 + 10)/4.# calculate MAE using scikit-learnprint "MAE:",metrics.mean_absolute_error(true, pred)# calculate MSE by handprint "MSE by hand:",(10**2 + 0**2 + 20**2 + 10**2)/4.# calculate MSE using scikit-learnprint "MSE:",metrics.mean_squared_error(true, pred)# calculate RMSE by handprint "RMSE by hand:",np.sqrt((10**2 + 0**2 + 20**2 + 10**2)/4.)# calculate RMSE using scikit-learnprint "RMSE:",np.sqrt(metrics.mean_squared_error(true, pred))
print np.sqrt(metrics.mean_squared_error(y_test, y_pred))
在之前展示的数据中,我们看到Newspaper和销量之间的线性关系比较弱,现在我们移除这个特征,看看线性回归预测的结果的RMSE如何?
feature_cols = ['TV', 'Radio']X = data[feature_cols]y = data.SalesX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)linreg.fit(X_train, y_train)y_pred = linreg.predict(X_test)print np.sqrt(metrics.mean_squared_error(y_test, y_pred))
我们将Newspaper这个特征移除之后,得到RMSE变小了,说明Newspaper特征不适合作为预测销量的特征,于是,我们得到了新的模型。我们还可以通过不同的特征组合得到新的模型,看看最终的误差是如何的。