数据: 第一列为序列号,2-4列为每种媒体的投入,最后一列为销量。共200条数据。
代码:利用了sklearn里面自带的线性模型。
import numpy as np import pandas as pd import matplotlib as mpl from sklearn.model_selection import train_test_split from sklearn.linear_model import Lasso from sklearn.model_selection import GridSearchCV import matplotlib.pyplot as plt ''' 数据: TV Radio Newspaper Sales 预测在各种媒体上的投资与销量的关系 (线性回归问题) ''' data = pd.read_csv("./Advertising.csv") # 用pandas读取文件 x_data = data[["TV","Radio","Newspaper"]] y_data = data["Sales"] # print(x_data) print(y_data) x_train,x_test,y_train,y_test = train_test_split(x_data,y_data,train_size=0.8,test_size=0.2) print(x_train,y_train) model = Lasso() alpha_can = np.logspace(-3,2,20) #在10的-3次方到10的2次方之间随机选20个数 print(alpha_can) np.set_printoptions(suppress=True) # 显示小数形式 print(alpha_can) # 随机初始化参数 #设置网格搜索的参数:使用model模型,参数取值为alpha_can,cv为交叉验证折数,默认3折,这里设为5 lasso_model = GridSearchCV(model,param_grid={'alpha': alpha_can},cv=5) # print(lasso_model) lasso_model.fit(x_train,y_train)# 运行网格搜索,用来优化参数 # print(lasso_model) print('超参数:',lasso_model.best_params_)#获取最终结果 # 把测试数据扔进已经训练好的模型,并计算均方差 y_out = lasso_model.predict(x_test) mse = np.average((y_out - np.array(y_test)) ** 2) print(mse) # mean square error # 画图 t = np.arange(len(x_test)) print(t) mpl.rcParams['font.sans-serif']=[u'simHei'] #设置中文字体 mpl.rcParams['axes.unicode_minus'] = False #字符显示 plt.figure(facecolor='w') plt.plot(t, y_test, 'r-', linewidth=2,label=u'真实数据') plt.plot(t, y_out, 'g-', linewidth=2, label=u'预测数据') plt.title("Regression predict Sales",fontsize=18) plt.legend(loc='upper right') plt.grid() plt.show()
可视化图: