时序预测 | 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.mzph.cn/news/195960.shtml

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

相关文章

【C++ regex】C++正则表达式

文章目录 前言一、正则表达式是什么&#xff1f;二、<regex>库的基础使用2.1 第一个示例2.1 <regex>库的函数详解std::regex_matchstd::regex_searchregex_search 和 regex_match 的区别std::regex_replacestd::regex_iterator 和 std::sregex_iterator&#xff1a…

❀My学习Linux命令小记录(13)❀

目录 ❀My学习Linux命令小记录&#xff08;13&#xff09;❀ 51.su指令 52.sudo指令 53.shutdown指令 54.reboot指令 55.poweroff指令 ❀My学习Linux命令小记录&#xff08;13&#xff09;❀ 51.su指令 功能说明&#xff1a;用于切换当前用户身份到其他用户身份。 &am…

MacBook Pro 安装Nacos【超详细图解】

目录 一、安装Nacos 二、启动nacos 三、进入可视化界面 因项目用到nacos&#xff0c;所以需要装一个&#xff0c;顺便写篇文章记录 一、安装Nacos 前往官网下载&#xff1a;Nacos官网homehttps://nacos.io/zh-cn/ # 解压 unzip nacos-server-2.3.0.zip 二、启动nacos …

怎么测试服务器的访问速度

一个网站的好坏&#xff0c;很大一部分原因是由于网站空间的稳定决定的。现在互联网发展十分迅速&#xff0c;网络宽带速度也非常快&#xff0c;流畅的 网站让用户对网站的打开时间要求也越来越高。如果一个网站它打开时间超过了5秒以上&#xff0c;那么极有可能会让访问用户关…

Collection集合的遍历方式-迭代器,增强for循环,Lambda

集合体系概述 Collection是单列集合的祖宗&#xff0c;它规定的方法&#xff08;功能&#xff09;是全部单列集合都会继承的 public class Work1 {public static void main(String[] args) {//简单认识一下Collection集合的特点ArrayList<String> list new ArrayList&…

【Vue2】Vue的介绍与Vue的第一个实例

文章目录 前言一、为什么要学习Vue二、什么是Vue1.什么是构建用户界面2.什么是渐进式Vue的两种开发方式&#xff1a; 3.什么是框架 三、创建Vue实例四、插值表达式 {{}}1.作用&#xff1a;利用表达式进行插值&#xff0c;渲染到页面中2.语法3.错误用法 五、响应式特性1.什么是响…

mysql中删除数据后,新增数据时id会跳跃,主键自增id不连续

引言&#xff1a; 在使用MySQL数据库时&#xff0c;有时候我们需要删除某些记录&#xff0c;但是删除记录后可能会导致表中的id不再连续排序。 如何实现删除记录后让id重新排序的功能。 如图&#xff1a; 删除数据后&#xff0c;中间的id不会自动连续。 下面有两种方法进行重…

医院绩效系统源码:基础数据管理、核算方法和分配规则、KPI评分公式等功能

医院绩效管理系统源码&#xff0c;医院绩效管理数据采集的自动化和绩效评估数字化 医院绩效管理系统以国家医院绩效管理考核政策法规为依据&#xff0c;结合医院管理实践&#xff0c;以经济管理指标为核心&#xff0c;医疗质量、安全、效率、效益管理为重点&#xff0c;特别强调…

阿里云虚拟机安装nginx容器步骤

1、申请虚拟机&#xff0c;操作系统选择centos 7.6&#xff0c;自带阿里云yum源。 2、安装yum工具 yum install -y yum-utils 3、添加docker 源 yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo 4、安装docker yum -y insta…

头哥实践平台----HBase 开发:使用Java操作HBase

一.第1关&#xff1a;创建表 1.先写命令行 start-dfs.shstart-hbase.shhadoop fs -ls /hbase(可有可无)2.再写代码文件 package step1;import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; impor…

unity3d模型中缺失animation

在 模型的Rig-Animationtype 设置成Legacy https://tieba.baidu.com/p/2293580178

时间戳,标准时间之间的转化

一. 获取时间戳 方法一&#xff1a;Date.now() console.log(Date.now()) // 1701676212978方法二&#xff1a;Date.parse() Date.parse()将字符串或者时间对象直接转化成时间戳&#xff1a; Date.parse(new Date()) // 1701676571000 Date.parse("2023/12/04 15:53"…

回文串+动态规划

最长回文子串 遍历字符串&#xff0c;逐个判断每个字符&#xff0c;向两边扩散&#xff0c;判断以当前字符为中心&#xff0c;最长回文大小。 /*** ①中心扩散法* 向左 向右 向左右* ②动态规划优化* 空间换时间*/ class Solution {public static void main(String[] args) …

OWASP SAMM 软件保障成熟度模型

软件保障成熟度模型 我们的使命是为您提供一种有效且可衡量的方式来分析和改进您的安全开发生命周期。 SAMM 支持完整的软件生命周期&#xff0c;并且与技术和流程无关。我们构建的 SAMM 本质上是不断发展和风险驱动的&#xff0c;因为没有一种单一的配方适用于所有组织。奥瓦…

【图像拼接】论文精读:Pixel-wise Deep Image Stitching(PWM+SIGMo)

第一次来请先看这篇文章:【图像拼接(Image Stitching)】关于【图像拼接论文精读】专栏的相关说明,包含专栏使用说明、创新思路分享等(不定期更新) 图像拼接系列相关论文精读 Seam Carving for Content-Aware Image ResizingAs-Rigid-As-Possible Shape ManipulationAdap…

【前端】甘特图或日历图

前言 之前不是说了吗?公司文化就是让人来偷懒就偷懒的操作,于是乎就开始开发甘特图,可以让客户的员工以及领导能清晰地看见工作安排和生产排产情况。 技术选型 说实话使用什么技术可以兼容到现有系统里面,毕竟自己手写太浪费时间啦,于是乎就去GitHub上面找,真是尝试了…

JVM——垃圾回收器(G1,JDK9默认为G1垃圾回收器)

1.G1垃圾回收器 JDK9之后默认的垃圾回收器是G1&#xff08;Garbage First&#xff09;垃圾回收器。 Parallel Scavenge关注吞吐量&#xff0c;允许用户设置最大暂停时间 &#xff0c;但是会减少年轻代可用空间的大小。 CMS关注暂停时间&#xff0c;但是吞吐量方面会下降。 而G1…

【C语言】扫雷小游戏初学者版

成功的秘诀就是每天都比别人多努力一点。 今天给大家带来一款非常经典的小游戏——扫雷的实现和讲解 这里是目录 前言整体框架1.打印菜单2.创建二维数组3.初始化棋盘4.打印棋盘5.布置棋盘中的雷6.排查雷和统计雷总体代码test.cgame.cgame.h 进阶&#xff08;递归展开&#xff0…

CityEngine2023 shp数据城市与路网三维模型并导入UE5

目录 0 引言1 城市和道路数据获取1.1 常用方法1.2 OSM数据获取1.3 OSM数据格式1.3.1 所有格式1.3.2 Shapefile格式 2 实践2.1 导入数据&#xff08;.shp&#xff09;2.2 构建三维模型2.3 将模型导入UE5 &#x1f64b;‍♂️ 作者&#xff1a;海码007&#x1f4dc; 专栏&#xf…

手机传输数据到电脑该怎么操作?安卓、苹果都可以这样操作

安卓手机 你知道安卓手机传输数据到电脑的方法有哪些吗&#xff1f;下面我们就一起来看一看可以使用的一些方法。 采用 USB 数据线 这个方法应该是我们生活中较为常见的方法了&#xff0c;我们只需要使用手机的充电线&#xff0c;将其连接到电脑上&#xff0c;然后手机可能会…