高级回归处理销售与广告

import  numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import  matplotlib as mpl
%matplotlib inline
from sklearn.linear_model import Lasso , Ridge  #拉萨回归,铃回归
from sklearn.model_selection  import train_test_split #自动切割
from sklearn.model_selection  import   GridSearchCV #表格搜索
path=r"C:\Users\Tsinghua-yincheng\Desktop\SZday94\data\Advertising.csv"
data=pd.read_csv(path)
x=data[["TV","Radio","Newspaper"]]
y=data["Sales"]
x_train,x_test,y_train,y_test= train_test_split(
    x,y,train_size=0.8, random_state=1) #数据自动切割
#ridge=Ridge()#创建岭回归模型
model=Lasso()#拉格朗日回归
alpha_scan=np.logspace(-3,2,10) #指数类型数组
lasso_model= GridSearchCV(model,
                          param_grid={"alpha":alpha_scan},
                          cv=10) #自动匹配最佳alpha
lasso_model.fit(x_train,y_train) #训练数据
lasso_model.best_params_  #寻找最佳alpha
lasso_model.score(x_test,y_test) #评分
lasso_model.score(x_train,y_train) #评分比
mpl.rcParams['font.sans-serif'] = ['simHei']
mpl.rcParams['axes.unicode_minus'] = False#中文乱码

print(lasso_model.score(x_train,y_train))
print(lasso_model.score(x_test,y_test))

order=y_test.argsort(axis=0)  #按照参数排序
print(type(y_test))
y_hat=lasso_model.predict(x_test) #预测的数据

plt.figure(facecolor="w")
t=np.arange(len(x_test)) #生成数组
plt.plot(t,y_test,"r-",linewidth=2,label="真实数据")
plt.plot(t,y_hat,"g-",linewidth=2,label="预测数据")
plt.legend()
plt.title("拉格朗日回归预测")
plt.grid()
plt.show()

在这里插入图片描述

#ridge=Ridge()#创建岭回归模型
model=Ridge()#岭回归模型
alpha_scan=np.logspace(-3,2,10) #指数类型数组
lasso_model= GridSearchCV(model,
                          param_grid={"alpha":alpha_scan},
                          cv=10) #自动匹配最佳alpha
lasso_model.fit(x_train,y_train) #训练数据
lasso_model.best_params_  #寻找最佳alpha
print(lasso_model.score(x_train,y_train))
print(lasso_model.score(x_test,y_test))

order=y_test.argsort(axis=0)  #按照参数排序
print(type(y_test))
y_hat=lasso_model.predict(x_test) #预测的数据

plt.figure(facecolor="w")
t=np.arange(len(x_test)) #生成数组
plt.plot(t,y_test,"r-",linewidth=2,label="真实数据")
plt.plot(t,y_hat,"g-",linewidth=2,label="预测数据")
plt.legend()
plt.title("岭回归预测")
plt.grid()
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青灯有味是儿时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值