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

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

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

1. 数据导入与准备

导入必要的数据分析库:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from 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'] = False
plt.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/

你可能感兴趣的文章
Node.js 切近实战(七) 之Excel在线(文件&文件组)
查看>>
node.js 初体验
查看>>
Node.js 历史
查看>>
Node.js 在个推的微服务实践:基于容器的一站式命令行工具链
查看>>
Node.js 实现类似于.php,.jsp的服务器页面技术,自动路由
查看>>
Node.js 异步模式浅析
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
Node.js 模块系统的原理、使用方式和一些常见的应用场景
查看>>
Node.js 的事件循环(Event Loop)详解
查看>>
node.js 简易聊天室
查看>>
Node.js 线程你理解的可能是错的
查看>>
Node.js 调用微信公众号 API 添加自定义菜单报错的解决方法
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>
Node.js中环境变量process.env详解
查看>>
Node.js之async_hooks
查看>>
Node.js初体验
查看>>
Node.js升级工具n
查看>>
Node.js卸载超详细步骤(附图文讲解)
查看>>