Python 机器学习(预测影厅观影人数)Ridge和Lasso

一、岭回归 Ridge
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
df = pd.read_csv(‘d:/3_film.csv’)
X = df.iloc[:,1:4]
y = df.filmnum
X = np.array(X.values)
y = np.array(y.values)
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size = 0.25,random_state = 1)

from sklearn import linear_model
#λ为0.1
ridge = linear_model.Ridge(alpha = 0.1)
ridge.fit(x_train,y_train)
print(‘求解系数为:’+str(ridge.coef_))
print(‘求解截距项为:’+str(ridge.intercept_))

y_pre = ridge.predict(x_test)
print(y_pre)

plt.figure(figsize=(10,6)) #设置图片大小
t = np.arange(0,len(x_test),1) #x轴
plt.plot(t,y_pre,‘b’,linewidth = 2,label = ‘predict’)
plt.plot(t,y_test,‘r’,linewidth = 2,label = ‘test’)
plt.legend()
plt.show()

from sklearn import metrics
from sklearn.metrics import r2_score

print(‘R2拟合度为:’+str(r2_score(y_test,y_pre)))
print(‘MAE误差为:’+str(metrics.mean_absolute_error(y_test,y_pre)))
print(‘MSE误差为:’+str(metrics.mean_squared_error(y_test,y_pre)))
print(‘RMSE误差为’+str(np.sqrt(metrics.mean_squared_error(y_test,y_pre))))

二、Lasso回归
lasso = linear_model.Lasso(alpha = 0.1)
lasso.fit(x_train,y_train)
print(‘参数:’,lasso.coef_)
print(‘截距:’,lasso.intercept_)

y_hat = lasso.predict(x_test)
plt.figure(figsize=(10,6))
t = np.arange(len(y_hat))
plt.plot(t,y_test,‘g’,linewidth=2,label=‘test’)
plt.plot(t,y_hat,‘r’,linewidth=2,label=‘predict’)
plt.legend()
plt.show()

from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(x_train,y_train)

y_pre1 = lr.predict(x_test)

你可能感兴趣的:(python,机器学习)