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

news2024/9/23 7:22:36

时序预测 | 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_bits
    for i in range(len(bounds)):
        # extract the substring
        start, end = i * n_bits, (i * n_bits)+n_bits
    
        substring = bitstring[start:end]
        # convert bitstring to a string of chars
        chars = ''.join([str(s) for s in substring])
        # convert string to integer
        integer = int(chars, 2)
        # scale integer to desired range
        value = bounds[i][0] + (integer/largest) * (bounds[i][1] - bounds[i][0])
        value = np.round(value)
        value = int(value)
        # store
        decoded.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 selection
    selection_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 loss
            selection_ix = ix

    return 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 default
    c1, c2 = p1.copy(), p2.copy()
	# check for recombination
    if rand() < r_cross:
		# select crossover point that is not on the end of the string
        pt = randint(1, len(p1)-2)
		# perform crossover
        c1 = 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 mutation
        if rand() < r_mut:
			# flip the bit
            bitstring[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 bitstring
    pop = [randint(0, 2, n_bits*len(bounds)).tolist() for _ in range(n_pop)]
    # keep track of best solution
    best, best_eval = 0, inf
    # enumerate generations
    for gen in range(1, n_iter+1):
        print(f"Generation:{gen}")
        # decode population
        decoded = [decode(bounds, n_bits, p) for p in pop]
        # evaluate all candidates in the population
        scores = [evaluate(series, steps_ahead, individual) for individual in decoded]
        # check for new best solution
        for i in range(n_pop):
            if scores[i] < best_eval: # find the lowest validation loss
                best, 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 generation
        children = list()
        for i in range(0, n_pop, 2):
			# get selected parents in pairs
            p1, p2 = selected[i], selected[i+1]
			# crossover and mutation
            for c in crossover(p1, p2, r_cross):
				# mutation
                mutation(c, r_mut)
				# store for next generation
                children.append(c)
		# replace population
        pop = children
    return [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 combination
        predictions = ((w1 * yhat_tcn_test) + (w2 * yhat_lstm_test)) / (w1+w2+1e-10)
        
        # Evaluate the performance using some metric, e.g. accuracy
        performance = sqrt(mean_squared_error(y_tcn_test, predictions))

        # Update the best weights and best performance if the current performance is better
        if performance < best_performance:
            best_weights = (w1, w2)
            best_performance = performance

print("Best weights:", best_weights)
print("Best performance:", best_performance)    

参考资料

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

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

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

相关文章

window10家庭版中文转专业版流程

1.确认当前为家庭中文版 2.用管理员权限打开cmd窗口 3.输入 dism /online /get-targeteditions &#xff0c;查询当前支持的升级的版本 4.专业版密钥&#xff1a;VK7JG-NPHTM-C97JM-9MPGT-3V66T 5.changepk.exe /productkey VK7JG-NPHTM-C97JM-9MPGT-3V66T

微服务--07--Seata 分布式事务

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 分布式事务1.认识Seata2.部署TC服务2.1.准备数据库表2.2.准备配置文件2.3.Docker部署 3.微服务集成Seata3.1.引入依赖3.2.改造配置3.3.添加数据库表3.4.测试 分布式…

事务级 REST API 在网络管理中的应用

什么是REST API&#xff1f; REST&#xff08;Representational State Transfer&#xff0c;也称RESTful&#xff09;API是一种架构风格&#xff0c;用于构建网络应用程序和服务之间的通信&#xff0c;是基于HTTP协议的一种应用程序接口。它提供了一组规范和约定&#xff0c;使…

【每日一坑】KiCAD导Gerber 文件

第一&#xff0c;软件版本 第二、操作选择注意点 第三步&#xff0c;那个坑。。。 不知道什么原因&#xff0c;这第二个框里会选其他不必要得一些东西&#xff0c;导致最终光绘是废的&#xff1b; 一定切记只选edge.cut就好了。 最后&#xff0c;上Gerber图&#xff0c;还有一…

Java数据结构之《顺序查找》问题

一、前言&#xff1a; 这是怀化学院的&#xff1a;Java数据结构中的一道难度中等偏下的一道编程题(此方法为博主自己研究&#xff0c;问题基本解决&#xff0c;若有bug欢迎下方评论提出意见&#xff0c;我会第一时间改进代码&#xff0c;谢谢&#xff01;) 后面其他编程题只要我…

位图和布隆过滤器(C++)

位图和布隆过滤器 一、位图1. 引入2. 概念3. 代码实现setreset完整代码 4. 位图的应用 二、布隆过滤器1. 引入2. 概念3. 逻辑结构4. 特点5. 代码实现6. 布隆过滤器的应用 三、哈希切割 一、位图 1. 引入 当面对海量数据需要处理时&#xff0c;内存不足以加载这些数据&#xf…

网络基础_1

目录 网络基础 协议 协议分层 OSI七层模型 网络传输的基本流程 数据包的封装和分用 IP地址和MAC地址 网络基础 网络就是不同的计算机之间可以进行通信&#xff0c;前面我们学了同一台计算机之间通信&#xff0c;其中有进程间通信&#xff0c;前面学过的有管道&#xff…

C++ 学习之函数成员指针的一个小细节

看看下面的代码&#xff0c;你能看出错误吗 class A { public:void fun(){}}; int main() {A a;void (A:: * p)() &A::fun;(*p)(); } 这段代码在调用成员函数时存在问题。正确的方式是使用对象来调用成员函数&#xff0c;而不是通过指针。以下是修正后的代码&#xff1a…

java学校高校运动会报名信息管理系统springboot+jsp

课题研究方案&#xff1a; 结合用户的使用需求&#xff0c;本系统采用运用较为广泛的Java语言&#xff0c;springboot框架&#xff0c;HTML语言等关键技术&#xff0c;并在idea开发平台上设计与研发创业学院运动会管理系统。同时&#xff0c;使用MySQL数据库&#xff0c;设计实…

【数据清洗 | 数据规约】数据类别型数据 编码最佳实践,确定不来看看?

&#x1f935;‍♂️ 个人主页: AI_magician &#x1f4e1;主页地址&#xff1a; 作者简介&#xff1a;CSDN内容合伙人&#xff0c;全栈领域优质创作者。 &#x1f468;‍&#x1f4bb;景愿&#xff1a;旨在于能和更多的热爱计算机的伙伴一起成长&#xff01;&#xff01;&…

1-3、DOSBox环境搭建

语雀原文链接 文章目录 1、安装DOSBox2、Debug进入Debugrdeautq 1、安装DOSBox 官网下载下载地址&#xff1a;https://www.dosbox.com/download.php?main1此处直接下载这个附件&#xff08;内部有8086的DEBUG.EXE环境&#xff09;8086汇编工作环境.rar执行安装DOSBox0.74-wi…

2021年8月18日 Go生态洞察:整合Go的网络体验

&#x1f337;&#x1f341; 博主猫头虎&#xff08;&#x1f405;&#x1f43e;&#xff09;带您 Go to New World✨&#x1f341; &#x1f984; 博客首页——&#x1f405;&#x1f43e;猫头虎的博客&#x1f390; &#x1f433; 《面试题大全专栏》 &#x1f995; 文章图文…

带大家做一个,易上手的家常炒鸡蛋

想做这道菜 先准备五个鸡蛋 然后将鸡蛋打到碗里面 然后 加小半勺盐 这个看个人喜好 放多少都没问题 不要太咸就好 将鸡蛋搅拌均匀 起锅烧油 油温热了之后 放三个干辣椒进去炒 干辣椒烧黑后 捞出来 味道就留在油里了 然后 倒入鸡蛋液 翻炒 注意翻炒 不要粘锅底 或者 一面糊…

Oracle SQL优化

1、书写顺序和执行顺序 在Oracle SQL中&#xff0c;查询的书写顺序和执行顺序是不同的。 1.1SQL书写顺序如下&#xff1a; SELECTFROMWHEREGROUP BYHAVINGORDER BY 1.2 SQL执行顺序 FROM&#xff1a;数据源被确定&#xff0c;表连接操作也在此步骤完成。 WHERE&#xff1a;对…

防爆执法记录仪、防爆智能安全帽助力海上钻井平台远程可视化监管平台建设

推动远程安全管理&#xff0c;海上钻井"视"界拓新—防爆执法记录仪与防爆智能安全帽的创新应用 在海上钻井作业领域&#xff0c;安全生产一直是萦绕在每一个业者心头的重大课题。由于环境的恶劣及作业的特殊性&#xff0c;一旦发生安全事故&#xff0c;其后果往往极…

【MySQL】视图:简化查询

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

Scrapy框架中间件(一篇文章齐全)

1、Scrapy框架初识&#xff08;点击前往查阅&#xff09; 2、Scrapy框架持久化存储&#xff08;点击前往查阅&#xff09; 3、Scrapy框架内置管道&#xff08;点击前往查阅&#xff09; 4、Scrapy框架中间件 Scrapy 是一个开源的、基于Python的爬虫框架&#xff0c;它提供了…

分支和循环

通常来说&#xff0c;C语言是结构化的程序设计语言&#xff0c;这里的结构包括顺序结构、选择结构、循环结构&#xff0c;C语言能够实现这三种结构&#xff0c;如果我们仔细分析&#xff0c;我们日常生活中所见的事情都可以拆分为这三种结构或者它们的组合。 下面我会仔细讲解我…

4.7-容器网络之host和none

这一节我们来看一下docker中的另外两种网络&#xff0c;host和none。 docker network inspect none 于是就看到Containers, 里面包含了一个test1 表示这个容器连接到了none。

【【FPGA的 MicroBlaze 的 介绍与使用 】】

FPGA的 MicroBlaze 的 介绍与使用 可编程片上系统&#xff08;SOPC&#xff09;的设计 在进行系统设计时&#xff0c;倘若系统非常复杂&#xff0c;采用传统 FPGA 单独用 Verilog/VHDL 语言进行开发的方式&#xff0c;工作量无疑是巨大的&#xff0c;这时调用 MicroBlaze 软核…