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

你可能感兴趣的文章
nio 中channel和buffer的基本使用
查看>>
NIO基于UDP协议的网络编程
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
Nitrux 3.8 发布!性能全面提升,带来非凡体验
查看>>
NI笔试——大数加法
查看>>
NLog 自定义字段 写入 oracle
查看>>
NLog类库使用探索——详解配置
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
查看>>
NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
查看>>
NLP学习笔记:使用 Python 进行NLTK
查看>>
NLP的神经网络训练的新模式
查看>>
NLP采用Bert进行简单文本情感分类
查看>>
NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>