博客
关于我
机器学习有关线性相关的实例:有关于广告的预测模型
阅读量:327 次
发布时间:2019-03-04

本文共 2086 字,大约阅读时间需要 6 分钟。

线性回归分析广告投放与销量关系

1. 数据导入与准备

导入必要的数据分析库:

import numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression

读取广告投放与销量的数据集:

path = 'Advertising.csv'data = pd.read_csv(path)x = data[['TV', 'Radio', 'Newspaper']]y = data['Sales']

2. 数据可视化

绘制广告投放与销量的对比图:

mpl.rcParams['font.sans-serif'] = [u'simHei']mpl.rcParams['axes.unicode_minus'] = Falseplt.figure(facecolor='w')plt.plot(data['TV'], y, 'ro', label='TV')plt.plot(data['Radio'], y, 'g^', label='Radio')plt.plot(data['Newspaper'], y, 'mv', label='Newspaper')plt.legend(loc='lower right')plt.xlabel(u'广告花费', fontsize=16)plt.ylabel(u'销售额', fontsize=16)plt.title(u'广告花费与销售额对比数据', fontsize=20)plt.grid()plt.show()

3. 数据预处理

划分训练集与测试集:

x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state=1)print("x_train.shape=", x_train.shape, "y_train.shape=", y_train.shape)

4. 模型训练

使用线性回归模型拟合数据:

linreg = LinearRegression()model = linreg.fit(x_train, y_train)print("模型系数:", linreg.coef_, "模型截距:", linreg.intercept_)

5. 模型评估

计算预测误差:

order = y_test.argsort(axis=0)y_test = y_test.values[order]x_test = x_test.values[order, :]y_hat = linreg.predict(x_test)mse = np.average((y_hat - np.array(y_test)) ** 2)rmse = np.sqrt(mse)print('MSE = ', mse)print('RMSE = ', rmse)print('R² = ', linreg.score(x_train, y_train))print('R² = ', linreg.score(x_test, y_test))

6. 可视化预测结果

绘制真实数据与预测数据对比图:

plt.figure(facecolor='w')t = np.arange(len(x_test))plt.plot(t, y_test, 'r-', linewidth=2, label=u'真实数据')plt.plot(t, y_hat, 'g-', linewidth=2, label=u'预测数据')plt.legend(loc='upper right')plt.title(u'线性回归预测销量', fontsize=18)plt.grid(b=True)plt.show()

7. 常用 sklearn 线性回归函数

  • fit(X, y, [sample_weight]):拟合线性模型

    • X:训练数据,形状为 [n_samples, n_features]
    • y:函数值,形状为 [n_samples, n_targets]
    • sample_weight:样本权重,形状为 [n_samples]
  • predict(X):利用训练好的模型进行预测

    • X:预测数据集,形状为 (n_samples, n_features)
  • score(X, y, [sample_weight]):返回预测的决定系数 R²

    • X:训练数据,形状为 [n_samples, n_features]
    • y:关于 X 的真实函数值,形状为 (n_samples)(n_samples, n_outputs)
    • sample_weight:样本权重

转载地址:http://bujh.baihongyu.com/

你可能感兴趣的文章
NodeJS yarn 或 npm如何切换淘宝或国外镜像源
查看>>
nodejs 中间件理解
查看>>
nodejs 创建HTTP服务器详解
查看>>
nodejs 发起 GET 请求示例和 POST 请求示例
查看>>
NodeJS 导入导出模块的方法( 代码演示 )
查看>>
nodejs 开发websocket 笔记
查看>>
nodejs 的 Buffer 详解
查看>>
NodeJS 的环境变量: 开发环境vs生产环境
查看>>
nodejs 读取xlsx文件内容
查看>>
nodejs 运行CMD命令
查看>>
Nodejs+Express+Mysql实现简单用户管理增删改查
查看>>
nodejs+nginx获取真实ip
查看>>
nodejs-mime类型
查看>>
NodeJs——(11)控制权转移next
查看>>
NodeJS、NPM安装配置步骤(windows版本)
查看>>
NodeJS、NPM安装配置步骤(windows版本)
查看>>
nodejs下的express安装
查看>>
nodejs与javascript中的aes加密
查看>>
nodejs中Express 路由统一设置缓存的小技巧
查看>>
nodejs中express的使用
查看>>