博客
关于我
机器学习有关线性相关的实例:有关于广告的预测模型
阅读量: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/

你可能感兴趣的文章
NOIP2011T1 数字反转
查看>>
NOIP2014 提高组 Day2——寻找道路
查看>>
noip借教室 题解
查看>>
NOIP模拟测试19
查看>>
NOIp模拟赛二十九
查看>>
Vue3+element plus+sortablejs实现table列表拖拽
查看>>
Nokia5233手机和我装的几个symbian V5手机软件
查看>>
non linear processor
查看>>
Non-final field ‘code‘ in enum StateEnum‘
查看>>
none 和 host 网络的适用场景 - 每天5分钟玩转 Docker 容器技术(31)
查看>>
None还可以是函数定义可选参数的一个默认值,设置成默认值时实参在调用该函数时可以不输入与None绑定的元素...
查看>>
NoNodeAvailableException None of the configured nodes are available异常
查看>>
Vue.js 学习总结(16)—— 为什么 :deep、/deep/、>>> 样式能穿透到子组件
查看>>
nopcommerce商城系统--文档整理
查看>>
NOPI读取Excel
查看>>
NoSQL&MongoDB
查看>>
NoSQL介绍
查看>>
NoSQL数据库概述
查看>>
Notadd —— 基于 nest.js 的微服务开发框架
查看>>
NOTE:rfc5766-turn-server
查看>>