文章目录

  • 1.广告预测-线性回归
  • 2.广告预测-岭回归

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 LinearRegressionif __name__ == "__main__":path = 'Advertising.csv'# # 手写读取数据# f = file(path)# x = []# y = []# for i, d in enumerate(f):#     if i == 0:#         continue#     d = d.strip()#     if not d:#         continue#     d = map(float, d.split(','))#     x.append(d[1:-1])#     y.append(d[-1])# pprint(x)# pprint(y)# x = np.array(x)# y = np.array(y)# Python自带库# f = file(path, 'r')# print f# d = csv.reader(f)# for line in d:#     print line# f.close()# # numpy读入# p = np.loadtxt(path, delimiter=',', skiprows=1)# print p# print '\n\n===============\n\n'# pandas读入data = pd.read_csv(path)    # TV、Radio、Newspaper、Sales# x = data[['TV', 'Radio', 'Newspaper']]x = data[['TV', 'Radio']]y = data['Sales']print(x)print(y)# 解决字体问题mpl.rcParams['font.sans-serif'] = [u'simHei']mpl.rcParams['axes.unicode_minus'] = False# 绘制1plt.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='Newspaer')# loc位置-右下角plt.legend(loc='lower right')plt.xlabel(u'广告花费', fontsize=16)plt.ylabel(u'销售额', fontsize=16)plt.title(u'广告花费与销售额对比数据', fontsize=20)plt.grid()plt.show()# 绘制2plt.figure(facecolor='w', figsize=(9, 10))# (311)表示3行1列第一个位置plt.subplot(311)plt.plot(data['TV'], y, 'ro')plt.title('TV')plt.grid()plt.subplot(312)plt.plot(data['Radio'], y, 'g^')plt.title('Radio')plt.grid()plt.subplot(313)plt.plot(data['Newspaper'], y, 'b*')plt.title('Newspaper')plt.grid()# tight_layout会自动调整子图参数,使之填充整个图像区域plt.tight_layout()plt.show()# 数据集的分割x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state=1)print(type(x_test))print(x_train.shape, y_train.shape)linreg = LinearRegression()model = linreg.fit(x_train, y_train)print(model)# coef_为: w = (w_1, ..., w_p) intercept_:w_0print(linreg.coef_, linreg.intercept_)# argsort函数返回的是数组值从小到大的索引值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)  # Mean Squared Errorrmse = np.sqrt(mse)  # Root Mean Squared Errorprint('MSE = ', mse)print('RMSE = ', rmse)print('R2 = ', linreg.score(x_train, y_train))print('R2 = ', linreg.score(x_test, y_test))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()

运行结果:

<class 'pandas.core.frame.DataFrame'>
(160, 2) (160,)
LinearRegression()
[0.04686997 0.1800065 ] 2.9475150360289994
MSE =  1.9552218850113174
RMSE =  1.3982924890777741
R2 =  0.8958528468776601
R2 =  0.8947344950027067



2.广告预测-岭回归

# 岭回归加参数调优
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 Lasso, Ridge
from sklearn.model_selection import GridSearchCVif __name__ == "__main__":# pandas读入data = pd.read_csv('Advertising.csv')    # TV、Radio、Newspaper、Salesx = data[['TV', 'Radio', 'Newspaper']]# x = data[['TV', 'Radio']]y = data['Sales']print(x)print(y)x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)# model = Lasso()model = Ridge()alpha_can = np.logspace(-3, 2, 10)np.set_printoptions(suppress=True)print('alpha_can = ', alpha_can)# 网格搜索-超参数调优lasso_model = GridSearchCV(model, param_grid={'alpha': alpha_can}, cv=5)lasso_model.fit(x_train, y_train)print('超参数:\n', lasso_model.best_params_)order = y_test.argsort(axis=0)y_test = y_test.values[order]x_test = x_test.values[order, :]y_hat = lasso_model.predict(x_test)print(lasso_model.score(x_test, y_test))mse = np.average((y_hat - np.array(y_test)) ** 2)  # Mean Squared Errorrmse = np.sqrt(mse)  # Root Mean Squared Errorprint(mse, rmse)t = np.arange(len(x_test))mpl.rcParams['font.sans-serif'] = [u'simHei']mpl.rcParams['axes.unicode_minus'] = Falseplt.figure(facecolor='w')plt.plot(t, y_test, 'r-', linewidth=2, label=u'真实数据')plt.plot(t, y_hat, 'g-', linewidth=2, label=u'预测数据')plt.title(u'线性回归预测销量', fontsize=18)plt.legend(loc='upper right')plt.grid()plt.show()

运行结果:

alpha_can =  [  0.001        0.00359381   0.0129155    0.04641589   0.166810050.59948425   2.15443469   7.74263683  27.82559402 100.        ]
超参数:{'alpha': 0.001}
0.915621357511648
1.9730457106647623 1.4046514552246625

机器学习基础算法12-回归实例-广告预测相关推荐

  1. 机器学习基础算法之随机森林

    英文原文<The Random Forest Algorithm> 专知 编译<机器学习基础算法之随机森林> [导读]在当今深度学习如此火热的背景下,其他基础的机器学习算法显得 ...

  2. 小白机器学习基础算法学习必经之路

    https://www.toutiao.com/a6657427848900379150/ 2019-02-14 15:21:13 未来,人工智能是生产力,是变革社会的主要技术力量之一. 掌握人工智能 ...

  3. kmeans python interation flag_机器学习经典算法-logistic回归代码详解

    一.算法简要 我们希望有这么一种函数:接受输入然后预测出类别,这样用于分类.这里,用到了数学中的sigmoid函数,sigmoid函数的具体表达式和函数图象如下: 可以较为清楚的看到,当输入的x小于0 ...

  4. 【机器学习基础】逻辑回归 + GBDT模型融合实战!

    作者:吴忠强,东北大学,Datawhale成员 一.GBDT+LR简介 协同过滤和矩阵分解存在的劣势就是仅利用了用户与物品相互行为信息进行推荐, 忽视了用户自身特征, 物品自身特征以及上下文信息等,导 ...

  5. 机器学习笔记-基于逻辑回归的分类预测

    天池学习笔记:AI训练营机器学习-阿里云天池 基于逻辑回归的分类预测 1 逻辑回归的介绍和应用 1.1 逻辑回归的介绍 逻辑回归(Logistic regression,简称LR)虽然其中带有&quo ...

  6. 【机器学习】十大机器学习基础算法

    十大机器学习算法入门 近年来,机器学习与人工智能已广泛应用于学术与工程,比如数据挖掘.计算机视觉.自然语言处理.生物特征识别.搜索引擎.医学诊断.检测信用卡欺诈.证券市场分析.DNA序列测序.语音和手 ...

  7. 机器学习基础算法四:逻辑回归算法实验

    逻辑回归算法实验 一.逻辑回归介绍 逻辑回归是一种分类模型 z=WTX=w0+w1x1+w2x2+......+wnxnz =W^{T}X=w^{0}+w^{1}x^{1}+w^{2}x^{2}+.. ...

  8. Pima印第安人数据集上的机器学习-分类算法(根据诊断措施预测糖尿病的发病)

    数据集简介 该数据集最初来自国家糖尿病/消化/肾脏疾病研究所.数据集的目标是基于数据集中包含的某些诊断测量来诊断性的预测 患者是否患有糖尿病. 从较大的数据库中选择这些实例有几个约束条件.尤其是,这里 ...

  9. 机器学习基础算法概述

    机器学习算法大致可以分为三类: 监督学习算法 (Supervised Algorithms):在监督学习训练过程中,可以由训练数据集学到或建立一个模式(函数 / learning model),并依此 ...

  10. 机器学习学习吴恩达逻辑回归_机器学习基础:逻辑回归

    机器学习学习吴恩达逻辑回归 In the previous stories, I had given an explanation of the program for implementation ...

最新文章

  1. 多元价值呼唤教育性父母
  2. 6 个核心理念!诠释了吴恩达新书《Machine Learning Yearning》
  3. 【深度学习】图文并茂!用Keras LSTM构建编码器-解码器模型
  4. eclipse配置本地连接 hadoop
  5. Python pip 国内镜像大全及使用办法
  6. 你知道嵌入式,那你看过这个吗?
  7. 我的Oracle 9i学习日志(18)-- 维护数据完整性.b
  8. iOS Coding项目片段记录(五)
  9. linux进程管理——进程管理相关命令
  10. Linux下命令积累
  11. ASP.net 简单注册界面
  12. android前置录像,Android Camera2video使用前置摄像头(Android Camera2video use front camera)
  13. RxJava串行执行任务
  14. spring aop分析(一)
  15. MySQL 安装失败 Failed to find valid data directory
  16. 第1关:ZooKeeper初体验
  17. Pyecharts组合图表复用渲染模块实现方法
  18. 考研线性代数手写笔记1 行列式
  19. 自动化立体仓库可以为企业带来什么效益?
  20. 张正友标定法几个坐标系的意思

热门文章

  1. PHP Cookbook读书笔记 – 第17章图形
  2. memcached学习笔记(1)——memcached原理
  3. 前端优化,包括css,jss,img,cookie
  4. C++ string用法
  5. Python 模块EasyGui
  6. java.lang.instrument 中的premain 实现类的个性化加载(附源代码)
  7. Codeforces 527C Glass Carving
  8. [转]OAuth 认证步骤
  9. ASP.NET 控件与可访问
  10. SQlite 发布3.2.5版本