用到的数据:
汽车销售数据:https://pan.baidu.com/s/1VlTy4nfvgXdDzgimVguZMg
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error,r2_score
data = pd.read_csv('data.csv')
data.head()
data.shape #(65, 10)
data.isnull().sum() #查看是否有缺失值
公路里程数有一个缺失值,用均值填充
data['公路里程数']=data['公路里程数'].fillna(data['公路里程数'].mean())
cormatrix = data.corr()
cormatrix *= np.tri(*cormatrix.values.shape,k=-1).T
cormatrix
X = data[['国内生产总值当季值(亿元)x1', '汽油价格(元/吨)x2', '人民币贷款基准利率%x3','公路里程数', '汽车整车股票指数', '消费者信心指数']]
Y = data['传统汽车销量']
X.head()
x_train,x_test,y_train,y_test = train_test_split(X,Y,test_size = 0.2,random_state = 66)
ss = StandardScaler()
ss.fit(x_train)
x_train_ss = ss.transform(x_train)
x_test_ss = ss.transform(x_test)
#构建模型
lr = LinearRegression()
lr.fit(x_train_ss,y_train)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
y_pred = lr.predict(x_test_ss)
#输出mse值
mean_squared_error(y_test,y_pred)
5017.725895684722
#输出R平方值
r2_score(y_test,y_pred)
0.8875379565909532