深度学习:基于Keras,使用长短期记忆神经网络模型LSTM和RMSProp优化算法进行销售预测分析

sales

前言

系列专栏:【机器学习:项目实战100+】【2024】✨︎
在本专栏中不仅包含一些适合初学者的最新机器学习项目,每个项目都处理一组不同的问题,包括监督和无监督学习、分类、回归和聚类,而且涉及创建深度学习模型、处理非结构化数据以及指导复杂的模型,如卷积神经网络、门控循环单元、大型语言模型和强化学习模型

预测是使用过去的值和许多其他因素来预测未来的值。在本文中,我们将使用 Keras 功能 API 创建一个销售预测模型。

目录

  • 1. 相关库和数据集
    • 1.1 相关库介绍
    • 1.2 数据集介绍
  • 2.数据处理
      • 2.2.1 数据预处理
      • 2.2.2 数据预处理
  • 3. 数据建模(LSTM)
    • 3.1 数据准备
    • 3.2 使用 RMSprop 编译模型
    • 3.3 拟合模型
    • 3.4 模型评估

1. 相关库和数据集

1.1 相关库介绍

Python 库使我们能够非常轻松地处理数据并使用一行代码执行典型和复杂的任务。

  • Pandas – 该库有助于以 2D 数组格式加载数据框,并具有多种功能,可一次性执行分析任务。
  • Numpy – Numpy 数组速度非常快,可以在很短的时间内执行大型计算。
  • Matplotlib/Seaborn – 此库用于绘制可视化效果,用于展现数据之间的相互关系。
  • Keras – 是一个由Python编写的开源人工神经网络库,可以作为Tensorflow、Microsoft-CNTK和Theano的高阶应用程序接口。
import pandas as pd                     # to extract data from dataset(.csv file)
import csv                              #used to read and write to csv files
import numpy as np                      #used to convert input into numpy arrays to be fed to the model
import matplotlib.pyplot as plt         #to plot/visualize sales data and sales forecasting
import tensorflow as tf                 # acts as the framework upon which this model is built
from tensorflow import keras            #defines layers and functions in the model
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense,LSTM,Flatten
from tensorflow.keras.layers import concatenate
#here the csv file has been copied into three lists to allow better availability
list_row,date,traffic = get_data('/home/abh/Documents/Python/Untitled Folder/Sales_dataset')

外部库的使用已经保持在最低限度,以提供一个更简单的界面,您可以用已经存在于已建立的库中的函数替换本教程中使用的函数。

1.2 数据集介绍

它使用过去的销售额、季节性、节日、经济状况等数据来确定当前或未来的销售额。所以,这个模型在提供了一定的输入后,会预测某一天的销售额。
5 年销售数据原始数据集:
在这里插入图片描述
2015 年 1 月至 2019 年 12 月的销售数据

如您所见,销售数据似乎每年都遵循类似的模式,峰值销售值似乎在 5 年的时间框架内随着时间的推移而增加。在这 5 年的时间框架内,前 4 年将用于训练模型,最后一年将用作测试集。现在,一些辅助函数用于处理数据集和创建所需形状和大小的输入。它们如下:

  1. get _ data–用于使用指向数据集位置的路径加载数据集。
  2. date _ to _ day–提供每天的日期。例如,2/2/16 是星期六,9/5/15 是星期一。
  3. date _ to _ enc–将数据编码成一个热点向量,这为模型提供了更好的学习机会。

这里无法解释这些函数和一些其他函数的所有属性,因为这会花费太多时间。

2.数据处理

首先,所有输入都经过预处理,以便机器能够理解。这是一个基于监督学习的线性回归模型,因此输出将与输入一起提供。然后,输入连同期望的输出一起被馈送到模型。该模型将绘制(学习)输入和输出之间的关系(函数)。然后,该函数或关系用于预测特定输入集的输出。在这种情况下,像日期和以前的销售额这样的输入参数被标记为输入,销售额被标记为输出。该模型将预测 0 到 1 之间的一个数字,因为 sigmoid 函数用于最后一层。这个输出可以乘以一个特定的数字(在这种情况下是最大销售额),这将是我们某一天对应的销售额。然后,该输出作为输入提供,以计算第二天的销售数据。这一系列步骤将持续到某一天到来。

2.2.1 数据预处理

最初,数据集只有两列:日期和流量(销售额)。

在添加不同的列并对值进行处理/标准化之后,数据包含了所有这些值。

  1. 日期
  2. 交通
  3. 假期与否
  4. 一天

所有这些参数都必须转换成机器可以理解的形式,这将使用下面的这个函数来完成。

它不是将日期、月份和年份作为一个单独的实体,而是被分成三个不同的输入。原因是这些输入中的年份参数在大多数情况下是相同的,这将导致模型变得自满,即它将开始过度拟合当前数据集。为了增加不同输入之间的可变性,日期和月份被分别标记。下面的函数转换()将创建六个列表,并向它们追加适当的输入。这就是 2015 年到 2019 年的编码
{2015:数组([1。, 0., 0., 0., 0.],dtype=float32),2016: array([0。, 1., 0., 0., 0.],dtype=float32),2017: array([0。, 0., 1., 0., 0.],dtype=float32),2018: array([0。, 0., 0., 1., 0.],dtype=float32),2019: array([0。, 0., 0., 0., 1.],dtype=float32)

每一个都是长度为 5 的 NumPy 数组,1 和 0 表示它的值

def conversion(week,days,months,years,list_row):#lists have been defined to hold different inputsinp_day = []inp_mon = []inp_year = []inp_week=[]inp_hol=[]out = []#converts the days of a week(monday,sunday,etc.) into one hot vectors and stores them as a dictionaryweek1 = number_to_one_hot(week)#list_row contains primary inputsfor row in list_row:#Filter out date from list_rowd = row[0]#the date was split into three values date, month and year.d_split=d.split('/')if d_split[2]==str(year_all[0]):#prevents use of the first year data to ensure each input contains previous year data as well.continue#encode the three parameters of date into one hot vectors using date_to_enc function.d1,m1,y1 = date_to_enc(d,days,months,years) #days, months and years and dictionaries containing the one hot encoding of each date,month and year.inp_day.append(d1) #append date into date inputinp_mon.append(m1) #append month into month inputinp_year.append(y1) #append year into year inputweek2 = week1[row[3]] #the day column from list_is converted into its one-hot representation and saved into week2 variableinp_week.append(week2)# it is now appended into week input.inp_hol.append([row[2]])#specifies whether the day is a holiday or nott1 = row[1] #row[1] contains the traffic/sales value for a specific dateout.append(t1) #append t1(traffic value) into a list outreturn inp_day,inp_mon,inp_year,inp_week,inp_hol,out #all the processed inputs are returnedinp_day,inp_mon,inp_year,inp_week,inp_hol,out = conversion(week,days,months,years,list_train)
#all of the inputs must be converted into numpy arrays to be fed into the model
inp_day = np.array(inp_day)
inp_mon = np.array(inp_mon)
inp_year = np.array(inp_year)
inp_week = np.array(inp_week)
inp_hol = np.array(inp_hol)

我们现在将处理一些剩余的其他输入,使用所有这些参数背后的原因是为了提高模型的效率,您可以尝试移除或添加一些输入。

过去七天的销售数据被作为输入传递,以创建销售数据的趋势,这将使预测值不会完全随机。同样,前一年当天的销售数据也被提供。

以下函数(other_inputs)处理三个输入:

  • 过去七天的销售数据
  • 上一年同一天的销售数据
  • 季节性——季节性被添加到夏季销售等趋势中。

2.2.2 数据预处理

def other_inputs(season,list_row):#lists to hold all the inputsinp7=[]inp_prev=[]inp_sess=[]count=0 #count variable will be used to keep track of the index of current row in order to access the traffic values of past seven days.for row in list_row:ind = countcount=count+1d = row[0] #date was copied to variable dd_split=d.split('/')if d_split[2]==str(year_all[0]):#preventing use of the first year in the datacontinuesess = cur_season(season,d) #assigning a season to to the current dateinp_sess.append(sess) #appending sess variable to an input listt7=[] #temporary list to hold seven sales valuet_prev=[] #temporary list to hold the previous year sales valuet_prev.append(list_row[ind-365][1]) #accessing the sales value from one year back and appending themfor j in range(0,7):t7.append(list_row[ind-j-1][1]) #appending the last seven days sales valueinp7.append(t7)inp_prev.append(t_prev)return inp7,inp_prev,inp_sessinp7,inp_prev,inp_sess = other_inputs(season,list_train)
inp7 = np.array(inp7)
inp7= inp7.reshape(inp7.shape[0],inp7.shape[1],1)
inp_prev = np.array(inp_prev)
inp_sess = np.array(inp_sess)

这么多输入背后的原因是,如果将所有这些组合成一个数组,它将具有不同长度的不同行或列。这样的数组不能作为输入。

将所有值线性排列在单个数组中会导致模型具有高损耗。

线性排列将导致模型一般化,因为连续输入之间的差异不会太大,这将导致有限的学习,降低模型的准确性。

3. 数据建模(LSTM)

3.1 数据准备

八个独立的输入被处理并连接成一个单独的层,并传递给模型。

最终输入如下:

  1. 日期
  2. 一天
  3. 前七天销售额
  4. 上一年的销售额
  5. 季节
  6. 假期与否

在这里的大部分图层中,我已经使用了 5 个单位作为输出形状,你可以进一步用它来实验,以提高模型的效率。

#an Input variable is made from every input array
input_day = Input(shape=(inp_day.shape[1],),name = 'input_day')
input_mon = Input(shape=(inp_mon.shape[1],),name = 'input_mon')
input_year = Input(shape=(inp_year.shape[1],),name = 'input_year')
input_week = Input(shape=(inp_week.shape[1],),name = 'input_week')
input_hol = Input(shape=(inp_hol.shape[1],),name = 'input_hol')
input_day7 = Input(shape=(inp7.shape[1],inp7.shape[2]),name = 'input_day7')
input_day_prev = Input(shape=(inp_prev.shape[1],),name = 'input_day_prev')
input_day_sess = Input(shape=(inp_sess.shape[1],),name = 'input_day_sess')
# The model is quite straight-forward, all inputs were inserted into a dense layer with 5 units and 'relu' as activation function
x1 = Dense(5, activation='relu')(input_day)
x2 = Dense(5, activation='relu')(input_mon)
x3 = Dense(5, activation='relu')(input_year)
x4 = Dense(5, activation='relu')(input_week)
x5 = Dense(5, activation='relu')(input_hol)
x_6 = Dense(5, activation='relu')(input_day7)
x__6 = LSTM(5,return_sequences=True)(x_6) # LSTM is used to remember the importance of each day from the seven days data
x6 = Flatten()(x__10) # done to make the shape compatible to other inputs as LSTM outputs a three dimensional tensor
x7 = Dense(5, activation='relu')(input_day_prev)
x8 = Dense(5, activation='relu')(input_day_sess)
c = concatenate([x1,x2,x3,x4,x5,x6,x7,x8]) # all inputs are concatenated into one
layer1 = Dense(64,activation='relu')(c)
outputs = Dense(1, activation='sigmoid')(layer1) # a single output is produced with value ranging between 0-1.
# now the model is initialized and created as well
model = Model(inputs=[input_day,input_mon,input_year,input_week,input_hol,input_day7,input_day_prev,input_day_sess], outputs=outputs)
model.summary() # used to draw a summary(diagram) of the model

模型

3.2 使用 RMSprop 编译模型

RMSprop 非常擅长处理随机分布,因此在这里使用它。

from tensorflow.keras.optimizers import RMSpropmodel.compile(loss=['mean_squared_error'],optimizer = 'adam',metrics = ['acc'] #while accuracy is used as a metrics here it will remain zero as this is no classification model)                  # linear regression models are best gauged by their loss value

3.3 拟合模型

该模型现在将被输入和输出数据,这是最后一步,现在我们的模型将能够预测销售数据。

history = model.fit(x = [inp_day,inp_mon,inp_year,inp_week,inp_hol,inp7,inp_prev,inp_sess],y = out,batch_size=16,steps_per_epoch=50,epochs = 15,verbose=1,shuffle =False)
#all the inputs were fed into the model and the training was completed

拟合模型
现在,为了测试模型,input()接受输入并将其转换为适当的形式:

def input(date):d1,d2,d3 = date_to_enc(date,days,months,years)   #separate date into three parametersprint('date=',date)d1 = np.array([d1])                        d2 = np.array([d2])d3 = np.array([d3])week1 = number_to_one_hot(week)        #defining one hot vector to encode days of a weekweek2 = week1[day[date]]week2=np.array([week2])//appeding a column for holiday(0-not holiday, 1- holiday)if date in holiday:h=1#print('holiday')else:h=0#print("no holiday")h = np.array([h])sess = cur_season(season,date)        #getting seasonality data from cur_season functionsess = np.array([sess])                            return d1,d2,d3,week2,h,sess

预测销售数据不是我们来这里的目的,所以我们还是继续预测工作吧。

销售预测

定义预测 _ 测试功能,预测提供日期后一年的销售数据:

该功能的工作原理如下:

  • 需要输入一个日期来预测从一年前到上述日期的销售数据
  • 然后,我们访问前一年当天的销售数据和前 7 天的销售数据。
  • 然后,使用这些作为输入,预测新的值,然后在七天值中,第一天被移除,并且预测的输出被添加作为下一次预测的输入

我们要求预测到 2019 年 12 月 31 日为止的一年

  • 首先,记录了 2018 年 12 月 31 日(一年前)的日期,以及从(2018 年 12 月 25 日–2018 年 12 月 31 日)开始的七天销售
  • 然后收集一年前,即 2017 年 12 月 31 日的销售数据
  • 将这些数据作为其他数据的输入,预测第一个销售数据(即 1/1/2019)
  • 然后删除 2018 年 12 月 24 日的销售数据,添加 2019 年 1 月 1 日的预测销售额。如此循环,直到预测出 2019 年 12 月 31 日的销售数据。

所以,以前的输出作为输入。

def forecast_testing(date):maxj = max(traffic) # determines the maximum sales value in order to normalize or return the data to its original formout=[]count=-1ind=0for i in list_row:count =count+1if i[0]==date: #identify the index of the data in listind = countt7=[]t_prev=[]t_prev.append(list_row[ind-365][1]) #previous year data# for the first input, sales data of last seven days will be taken from training datafor j in range(0,7):t7.append(list_row[ind-j-365][1])result=[] # list to store the output and valuescount=0for i in list_date[ind-364:ind+2]:d1,d2,d3,week2,h,sess = input(i) # using input function to process input values into numpy arrayst_7 = np.array([t7]) # converting the data into a numpy arrayt_7 = t_7.reshape(1,7,1)# extracting and processing the previous year sales valuet_prev=[]t_prev.append(list_row[ind-730+count][1])t_prev = np.array([t_prev])#predicting value for outputy_out = model.predict([d1,d2,d3,week2,h,t_7,t_prev,sess])#output and multiply the max value to the output value to increase its range from 0-1print(y_out[0][0]*maxj)t7.pop(0) #delete the first value from the last seven days valuet7.append(y_out[0][0]) # append the output as input for the seven days dataresult.append(y_out[0][0]*maxj) # append the output value to the result listcount=count+1return result

运行预测测试功能,将返回包含该年所有销售数据的列表,结果=预测 _ 测试(’ 2019 年 12 月 31 日’,日期)

3.4 模型评估

预测值和实际值的图表,用于测试模型的性能

plt.plot(result,color='red',label='predicted')
plt.plot(test_sales,color='purple',label="actual")
plt.xlabel("Date")
plt.ylabel("Sales")
leg = plt.legend()
plt.show()

在这里插入图片描述
在这里插入图片描述
2019 年 1 月 1 日至 2019 年 12 月 31 日的实际值

在这里插入图片描述
预测值和实际值之间的比较

如你所见,预测值和实际值非常接近,这证明了我们模型的有效性。如果上述文章中有任何错误或改进的可能性,请随时在评论部分提及。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/6811.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[C++核心编程-02]----C++引用详解和使用方法分析

前言 在C中,引用是一个别名,它允许将一个已存在的变量或对象用不同的名称来访问。引用在定义时必须初始化,并且一旦初始化就不能再绑定其他对象,因此引用在声明时被初始化后就不能再改变引用对象。引用使用&符号进行声明。 引…

【C++STL详解(六)】--------list的模拟实现

目录 前言 一、接口总览 一、节点类的模拟实现 二、迭代器类的模拟实现 迭代器的目的 list迭代器为何要写成类? 迭代器类模板参数说明 模拟实现 1.构造函数 2.*运算符重载 3.->运算符重载 4.前置 5.后置 6.前置-- 7.后置-- 8.! 9. 三、list类的…

【Mac】graphpad prism for Mac(专业医学绘图工具) v10.2.3安装教程

软件介绍 GraphPad Prism for Mac是一款专业的科学数据分析和绘图软件,广泛用于生物医学和科学研究领域。它具有强大的统计分析功能,可以进行各种数据分析,包括描述性统计、生存分析、回归分析、方差分析等。同时,它还提供了丰富…

滑动验证码登陆测试编程示例

一、背景及原理 处理登录时的滑动验证码有两个难点,第一个是找到滑块需要移动的距离,第二个是模拟人手工拖动的轨迹。模拟轨迹在要求不是很严的情况下可以用先加速再减速拖动的方法,即路程的前半段加速度为正值,后半段为负值去模…

Go未用代码消除与可执行文件瘦身

在日常编写Go代码时,我们会编写很多包,也会在编写的包中引入了各种依赖包。在大型Go工程中,这些直接依赖和间接依赖的包数目可能会有几十个甚至上百个。依赖包有大有小,但通常我们不会使用到依赖包中的所有导出函数或类型方法。 这…

如何高速下载,百度 阿里 天翼 等网盘内的内容

如何高速下载,百度 阿里 天翼 等网盘内的内容🏅 前言教程下期更新预报🏅 前言 近段时间经常给大家分享各种视频教程,由于分享的资料是用迅雷网盘存的,但是绝大部分用户都是使用的某度,阿某的这些网盘&…

VScode添加c/c++头文件路径

1.设置工作区include path方法: 命令面板 -> 输入c/c 修改配置文件,添加路径: 2.全局路径: 设置 - > 搜索include path

tomcat+maven+java+mysql图书管理系统1-配置项目环境

目录 一、软件版本 二、具体步骤 一、软件版本 idea2022.2.1 maven是idea自带不用另外下载 tomcat8.5.99 Javajdk17 二、具体步骤 1.新建项目 稍等一会,创建成功如下图所示,主要看左方目录相同不。 给maven配置国外镜像 在左上…

【DPU系列之】Bluefield 2 DPU卡的功能图,ConnectX网卡、ARM OS、Host OS的关系?(通过PCIe Switch连接)

核心要点: CX系列网卡与ARM中间有一个PCIe Swtich的硬件单元链接。 简要记录。 可以看到图中两个灰色框,上端是Host主机,下端是BlueField DPU卡。图中是BF2的图,是BF2用的是DDR4。DPU上的Connect系列网卡以及ARM系统之间有一个…

cmd命令跳转至指定目录

1、指定目录与当前目录在同一盘符:直接cd 指定目录。2、指定目录与当前目录不在同一盘符: a、方法一:cd 指定目录,此时不会跳转,接着再输入指定目录的盘符即可。 b、方法二:输入指定目录所在的盘符&#xf…

C++:map和set类

关联式容器 在初阶阶段,我们已经接触过STL中的部分容器,比如:vector、list、deque、 forward_list(C11)等,这些容器统称为序列式容器,因为其底层为线性序列的数据结构,里面 存储的是元素本身。那什么是关…

Docker的私有仓库部署-Harbor

目录 一. Docker原生私有仓库 Registry 1. Registry 的介绍 2. Registry 的部署过程 二. Registry 的升级——Habor 1. Harbor 简介 2. Harbor 特性 3. Harbor 的构成 4. Harbor 部署 4.1 部署 Docker-Compose 服务 4.2 部署 Harbor 服务 4.2.1 下载或上传 Harbor…

结构体介绍(2)

结构体介绍(2) 前言一、结构体的内存对齐之深入理解为什么存在内存对齐?修改默认对齐数 二、结构体传参2.1:该怎么传参呢? 三、结构体实现位段3.1什么是位段位段的内存分配位段的跨平台问题 总结 前言 根据之前讲了结…

【C++程序员的自我修炼】string 库中常见用法(二)

制芰荷以为衣兮 集芙蓉以为裳 不吾知其亦已兮 苟余情其信芳 目录 字符串的头部插入insert <1>头部插入一个字符串&#xff1a; <2>头部插入一个字符&#xff1a; <3>迭代器的插入 总结&#xff1a; 字符串的头部删除 erase <1>头部插入删除一个字符&a…

nodejs实战——搭建websocket服务器

本博客主要介绍websocket服务器库安装&#xff0c;并举了一个简单服务器例子。 服务器端使用websocket需要安装nodejs websocket。 cd 工程目录 # 此刻我们需要执行命令&#xff1a; sudo npm init上述命令创建package.json文件&#xff0c;系统会提示相关配置。 我们也可以使…

数据结构十:哈希表

本次将从概念上理解什么是哈希表&#xff0c;理论知识较多&#xff0c;满满干货&#xff0c;这也是面试笔试的一个重点区域。 目录 一、什么是哈希表 1.0 为什么会有哈希表&#xff1f; 1.1 哈希表的基本概念 1.2 基本思想 1.3 举例理解 1.4 存在的问题 1.5 总结 二、…

基于JSP的人才公寓管理系统

目录 背景 技术简介 系统简介 界面预览 背景 随着互联网的广泛推广和应用&#xff0c;人才公寓管理系统在网络技术的推动下迅速进步。该系统的设计初衷是满足住户的实际需求&#xff0c;通过深入了解住户的期望&#xff0c;开发出高度定制化的人才公寓管理系统。利用互联网…

Django关于ORM的增删改查

Django中使用orm进行数据库的管理&#xff0c;主要包括以下步骤 1、创建model&#xff0c; 2、进行迁移 3、在视图函数中使用 以下的内容可以先从查询开始看&#xff0c;这样更容易理解后面删除部分代码 主要包括几下几种&#xff1a; 1、增 1&#xff09;实例例化model,代…

SpringTask定时任务

SpringBoot项目定时任务 首先在启动类引入注解EnableScheduling然后在方法中加注解Scheduled(cron“”)cron表达式 生成cron https://www.pppet.net/

流畅的Python阅读笔记

五一快乐的时光总是飞快了&#xff0c;不知多久没有拿起键盘写文章了&#xff0c;最近公司有Python的需求&#xff0c;想着复习下Python吧&#xff0c;然后就买了本Python的书籍 书名&#xff1a; 《流畅的Python》 下面是整理的一个阅读笔记&#xff0c;大家自行查阅&#xf…