时序预测 | Python实现GA-TCN-LSTM遗传算法-时间卷积神经网络-长短期记忆网络时间序列预测

时序预测 | Python实现GA-TCN-LSTM遗传算法-时间卷积神经网络-长短期记忆网络时间序列预测

目录

    • 时序预测 | Python实现GA-TCN-LSTM遗传算法-时间卷积神经网络-长短期记忆网络时间序列预测
      • 预测效果
      • 基本介绍
      • 程序设计
      • 参考资料

预测效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

基本介绍

使用先进的机器学习技术和优化算法开发石油产量预测模型,包括开发遗传算法-时间卷积神经网络-长短期记忆(GA-TCN-LSTM)集成模型,以及对循环神经网络(RNN)、门控循环单元( GRU)、长短期记忆LSTM)和时间卷积网络(TCN)。 此外,该程序还包括使用探索性数据分析和数据清理,旨在检测、可视化和处理数据集中的异常值。

在这里插入图片描述
利用先进的机器学习技术和优化算法可以通过考虑这些复杂性来提高预测的准确性 并确定每个模型的最佳超参数组合。

程序设计

  • 私信博主回复Python实现GA-TCN-LSTM遗传算法-时间卷积神经网络-长短期记忆网络时间序列预测
  • Python 3.10.7

在这里插入图片描述

# (找到将用于 TCN-LSTM 预测的加权平均指标的最佳权重)。
# decode bitstring to numbers
def decode(bounds: list, n_bits: int, bitstring: list
)-> list:"""Decodes a bitstring into a list of values that correspond to the variables in an optimization problem.Args:bounds (list): A list of lists, where each list represents the lower and upper bounds of a variable in the optimization problem.n_bits (int): An integer that specifies the number of bits used to represent each variable in the bitstring.bitstring (list): A list of bits that represents a candidate solution in the optimization problem.Returns:list: A list of values that correspond to the variables in the optimization problem."""decoded = list()largest = 2**n_bitsfor i in range(len(bounds)):# extract the substringstart, end = i * n_bits, (i * n_bits)+n_bitssubstring = bitstring[start:end]# convert bitstring to a string of charschars = ''.join([str(s) for s in substring])# convert string to integerinteger = int(chars, 2)# scale integer to desired rangevalue = bounds[i][0] + (integer/largest) * (bounds[i][1] - bounds[i][0])value = np.round(value)value = int(value)# storedecoded.append(value)return decoded# tournament selection
def selection(pop: list, scores: list, k: int = 3
)-> list:"""Selects a candidate solution from a population using tournament selection.Args:pop (list): A list of candidate solutions.scores (list): A list of fitness scores for the candidate solutions.k (int): The number of individuals to compete in each tournament.Returns:list: The selected candidate solution."""# first random selectionselection_ix = randint(len(pop))for ix in randint(0, len(pop), k-1):# check if better (e.g. perform a tournament)if scores[ix] < scores[selection_ix]: # which individual has the lowest lossselection_ix = ixreturn pop[selection_ix]# crossover two parents to create two children
def crossover(p1: list, p2: list, r_cross: float
)-> list:"""Performs crossover between two parent candidate solutions to create two child candidate solutions.Args:p1 (list): The first parent candidate solution.p2 (list): The second parent candidate solution.r_cross (float): The crossover rate.Returns:list: A list containing the two child candidate solutions."""# children are copies of parents by defaultc1, c2 = p1.copy(), p2.copy()# check for recombinationif rand() < r_cross:# select crossover point that is not on the end of the stringpt = randint(1, len(p1)-2)# perform crossoverc1 = np.append(p1[:pt] , p2[pt:])c2 = np.append(p2[:pt] , p1[pt:])return [c1, c2]# mutation operator
def mutation(bitstring: list, r_mut: float
)-> list:"""Mutates a candidate solution by flipping bits in its bitstring.Args:bitstring (list): The bitstring of the candidate solution.r_mut (float): The mutation rate.Returns:None"""for i in range(len(bitstring)):# check for a mutationif rand() < r_mut:# flip the bitbitstring[i] = 1 - bitstring[i]# genetic algorithm
def genetic_algorithm(series: pd.Series, netowrk_type: str, steps_ahead: int,evaluate: callable, bounds: list, n_bits: int, n_iter: int, n_pop: int, r_cross: float, r_mut: float
)-> list:"""Implements a genetic algorithm to optimize the hyperparameters of a neural network.Args:series (pd.Series): The time series data to be used for training and validation.network_type (str): The type of neural network to be optimized ('lstm' or 'tcn').steps_ahead (int): The number of steps ahead to forecast.evaluate (callable): A function that evaluates the fitness of a candidate solution based on the validation loss.bounds (list): A list of lists, where each list represents the lower and upper bounds of a variable in the optimization problem.n_bits (int): An integer that specifies the number of bits used to represent each variable in the bitstring.n_iter (int): The number of generations to run the genetic algorithm.n_pop (int): The number of candidate solutions in each generation.r_cross (float): The crossover rate.r_mut (float): The mutation rate.Returns:list: A list containing the best candidate solution and its fitness score."""if network_type not in ['lstm', 'tcn']:raise ValueError("network_type must be either 'lstm' or 'tcn'")# initial population of random bitstringpop = [randint(0, 2, n_bits*len(bounds)).tolist() for _ in range(n_pop)]# keep track of best solutionbest, best_eval = 0, inf# enumerate generationsfor gen in range(1, n_iter+1):print(f"Generation:{gen}")# decode populationdecoded = [decode(bounds, n_bits, p) for p in pop]# evaluate all candidates in the populationscores = [evaluate(series, steps_ahead, individual) for individual in decoded]# check for new best solutionfor i in range(n_pop):if scores[i] < best_eval: # find the lowest validation lossbest, best_eval = pop[i], scores[i]if network_type == 'lstm':print(">%d, new best combination, Epoch: %d, num_hidden_layers: %d, num_neurons:%d, batch_size: %d, window_size: %d, Loss = %.8f" % \(gen,  decoded[i][0],decoded[i][1], decoded[i][2], decoded[i][3], decoded[i][4],scores[i]))elif network_type == 'tcn':print(">%d, new best combination, Epoch: %d, n_filters_1: %d, n_filters_2: %d, n_filters_3: %d, batch_size: %d, window_size: %d, Loss = %.8f" % \(gen,  decoded[i][0],decoded[i][1], decoded[i][2], decoded[i][3], decoded[i][4], decoded[i][5],scores[i]))# select parents (Tournament selection)selected = [selection(pop, scores) for _ in range(n_pop)]# create the next generationchildren = list()for i in range(0, n_pop, 2):# get selected parents in pairsp1, p2 = selected[i], selected[i+1]# crossover and mutationfor c in crossover(p1, p2, r_cross):# mutationmutation(c, r_mut)# store for next generationchildren.append(c)# replace populationpop = childrenreturn [best, best_eval]
#find the optimal weights for the weighted average metric that will be used for the prediction of TCN-LSTM
# Define a range for the weights to be searched
weights = np.linspace(0.0, 1, 100)
weights = np.round(weights,5)# Initialize the best weights and best performance
# best_weights = (1,1)
best_performance = float('inf')# Iterate over all possible weight combinations
for w1 in weights:for w2 in weights:        # Make predictions using the current weight combinationpredictions = ((w1 * yhat_tcn_test) + (w2 * yhat_lstm_test)) / (w1+w2+1e-10)# Evaluate the performance using some metric, e.g. accuracyperformance = sqrt(mean_squared_error(y_tcn_test, predictions))# Update the best weights and best performance if the current performance is betterif performance < best_performance:best_weights = (w1, w2)best_performance = performanceprint("Best weights:", best_weights)
print("Best performance:", best_performance)    

参考资料

[1] https://blog.csdn.net/kjm13182345320/article/details/128247182

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

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

相关文章

【C++】了解模板

这里是目录 前言函数模板函数模板的实例化类模板 前言 如果我们要交换两个数字&#xff0c;那么我们就需要写一个Swap函数来进行交换&#xff0c;那如果我们要交换char类型的数据呢&#xff1f;那又要写一份Swap的函数重载&#xff0c;参数的两个类型是char&#xff0c;那我们…

免费WordPress站群插件-批量管理站群的免费软件

WordPress站群插件&#xff1a;让文章管理如丝般顺滑 在众多网站建设工具中&#xff0c;WordPress一直以其简便易用、丰富的插件生态而备受青睐。对于站群管理者而言&#xff0c;如何高效地更新、发布和推送文章是一项不可忽视的任务。本文将专注分享一款WordPress站群插件&am…

Vue语音播报,不用安装任何包和插件,直接调用。

Vue语音播报功能可以通过使用浏览器提供的Web Speech API来实现。这个API允许你的应用程序通过浏览器朗读文本&#xff0c;不用安装任何包和插件&#xff0c;直接调用。以下是一个简单的介绍&#xff0c;演示如何在Vue中使用语音提示功能&#xff1a; 一、JS版本 <template…

陈年雷司令葡萄酒中的石油笔记

雷司令葡萄酒通常在年轻时食用&#xff0c;当它们酿造出果味和芳香的葡萄酒时&#xff0c;可能带有绿色或其他苹果、葡萄柚、桃子、醋栗、蜂蜜、玫瑰花或切绿草的香气&#xff0c;并且由于酸度高&#xff0c;通常味道清脆。 雷司令天然的高酸度和各种风味使其适合长时间老化&am…

【MySQL】视图:简化查询

文章目录 create view … as创建视图更改或删除视图drop view 删除视图replace关键字&#xff1a;更改视图 可更新视图with check option子句&#xff1a;防止行被删除视图的其他优点简化查询减小数据库设计改动的影响使用视图限制基础表访问 create view … as创建视图 把常用…

代码级接口测试与单元测试的区别

关于接口测试 接口测试是一个比较宽泛的概念, 近几年在国内受到很多企业和测试从业者的追捧, 尤其是上层的UI在取悦用户的过程中迭代更新加快, UI自动化维护成本急剧上升的时代, 大家便转向了绕过前端的接口层面进行测试. 但是很多人, 对接口测试的理解并不完整, 事实上, 我们…

回答关于模糊C均值聚类(FCM)的一些问题!FCM停止迭代的条件是什么,FCM中的隶属度起什么作用?

文章目录 一、模糊C均值聚类&#xff08;FCM&#xff09;中的隶属度是起什么作用二、FCM停止迭代的条件是什么 一、模糊C均值聚类&#xff08;FCM&#xff09;中的隶属度是起什么作用 表示样本点对各个聚类中心的隶属程度。隶属度取值范围是0-1之间,值越大表示样本点越可能属于…

Windows系列:windows server 2003 - 组策略部署软件

通过组策略为域内用户部署&#xff08;deploy&#xff09;软件&#xff0c;可分为指派&#xff08;assign&#xff09;和发布&#xff08;publish&#xff09;。 软件指派给用户&#xff1a;用户在域内登录后&#xff0c;被“通告 advertised”给用户&#xff0c;此时仅安装了部…

nvm 下载node时候下载不到npm包的解决方法

个人博客链接 公众号-nvm 下载node时候下载不到npm包的解决方法 求关注 可以跳过的背景 最近项目比较有空&#xff0c;所以就可以有时间写一些demo&#xff0c;主要测试下react的一些语法&#xff0c;毕竟自己上次写react已经是22年的7月份了,期间对于react-router等的hook…

E云管家微信群聊机器人开发

请求URL&#xff1a; http://域名地址/modifyGroupRemark 请求方式&#xff1a; POST 请求头Headers&#xff1a; Content-Type&#xff1a;application/jsonAuthorization&#xff1a;login接口返回 参数&#xff1a; 参数名必选类型说明wId是String登录实例标识chatRo…

11月30日作业

作业&#xff1a; 设计一个Per类&#xff0c;类中包含私有成员:姓名、年龄、指针成员身高、体重&#xff0c;再设计一个Stu类&#xff0c;类中包含私有成员:成绩、Per类对象p1&#xff0c;设计这两个类的构造函数、析构函数和拷贝构造函数。 #include <iostream>using n…

13-Vue基础之自定义指令与插槽的使用

个人名片&#xff1a; &#x1f60a;作者简介&#xff1a;一名大二在校生 &#x1f921; 个人主页&#xff1a;坠入暮云间x &#x1f43c;座右铭&#xff1a;懒惰受到的惩罚不仅仅是自己的失败&#xff0c;还有别人的成功。 &#x1f385;**学习目标: 坚持每一次的学习打卡 文章…