码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 基于循环神经网络空中目标意图识别实现(附源码)


    文章目录

    • 前言
    • 基于RNN(循环神经网络)空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释
    • 基于LSTM循环神经网络空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释
    • 基于GRU循环神经网络空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释
    • 基于改进GRU(添加注意力机制)循环神经网络空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释
    • 一、引入库
    • 二、程序主干
      • 1.attention层的定义
      • 2.在GRU层后添加Attention层
      • 3.在双向GRU层后添加Attention层
    • 三、各个函数的意义如下
      • 1、getData()函数负责读取xml文件,并处理成数据序列及对应的标签序列。参数data_length决定了所读取序列的长度。
      • 2、getDocumentList()函数用于辅助getData()函数进行数据读取。
      • 3、modelRNN()、modelLSTM()、modelGRU()都用于实现最基本的循环神经网络模型,只是所用神经元类型不同,分别为最基础的RNN、LSTM和GRU。
      • 4、attention_3d_block()函数定义了Attention层,参数SINGLE_ATTENTION_VECTOR为True时共享注意力权重。注意力权重共享是说,我们的特征在一个时间结点上是多维的,即有可能是多个特征随时间变换一起发生了变换,那对应的注意力算出来也是多维的。此时,是多维特征共享一个注意力权重,还是每一维特征单独有一个注意力权重呢?当SINGLE_ATTENTION_VECTOR=True时,Lambda层将原本多维的注意力权重取平均,RepeatVector层再按特征维度复制粘贴,那么每一维特征的权重都是一样的了,也就是所说的共享一个注意力。
      • 5、modelAttentionAfterGRU()用于实现在GRU层之后添加Attention层的模型。modelAttentionBiLSTM()用于实现在双向GRU层之后添加Attention层的模型。
      • 6、全局变量INPUT_DIM表示输入特征的维度;TIME_STEPS = 500 表示输入到神经网络层序列的长度。
      • 7、主函数中给出了一个示例:读取数据,划分训练集和测试集,多次训练神经网络模型进行交叉验证,计算加权错误率Weighted Error Rate和训练模型所用时间,最后将模型训练过程中的Loss(也可换成其他指标)变化可视化。


    前言

    目标战术意图由一系列动作实现,因此目标状态呈现时序动态变化特征。针对目标意图识别问题的特点,本文是对基于循环神经网络进行意图识别的实现。现有的用于复杂环境下对目标意图识别方法主要有模板匹配、证据推理、贝叶斯网络和神经网络等。


    基于RNN(循环神经网络)空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释

    下载链接:https://download.csdn.net/download/DeepLearning_/87232407

    基于LSTM循环神经网络空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释

    下载链接:https://download.csdn.net/download/DeepLearning_/87232463

    基于GRU循环神经网络空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释

    下载链接:https://download.csdn.net/download/DeepLearning_/87232539

    基于改进GRU(添加注意力机制)循环神经网络空中目标意图识别-kereas完整源码+数据集+评估指标曲线绘制+程序说明及注释

    下载链接:https://download.csdn.net/download/DeepLearning_/87232571

    提示:以下是本篇文章正文内容,下面案例可供参考

    一、引入库

    #!/usr/bin/env python
    # coding: utf-8
    
    import tensorflow as tf
    import keras.backend as K
    from keras.callbacks import ReduceLROnPlateau
    from keras.layers import Multiply
    from keras.layers.core import *
    from keras.layers.recurrent import LSTM
    from keras.layers.recurrent import GRU
    from keras.layers.recurrent import SimpleRNN
    from keras.layers import Bidirectional
    from keras.models import *
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import confusion_matrix
    import xml.etree.ElementTree as ET
    import matplotlib.pyplot as plt
    from collections import Counter
    import pandas as pd
    import numpy as np
    import os
    import time
    import random
    import math
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    二、程序主干

    1.attention层的定义

    代码如下(示例):

    def attention_3d_block(inputs,SINGLE_ATTENTION_VECTOR):
        input_dim = int(inputs.shape[2])
        a = Permute((2, 1))(inputs)#(time_steps, input_dim)维度转置
        a = Reshape((input_dim, TIME_STEPS))(a) 
        a = Dense(TIME_STEPS, activation='softmax')(a)#计算每个特征的权重
        if SINGLE_ATTENTION_VECTOR:#是否共享注意力权重
            a = Lambda(lambda x: K.mean(x, axis=1), name='dim_reduction')(a)
            a = RepeatVector(input_dim)(a)
        a_probs = Permute((2, 1), name='attention_vec')(a)
        output_attention_mul = Multiply()([inputs, a_probs])
        return output_attention_mul
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.在GRU层后添加Attention层

    代码如下(示例):

    def modelAttentionAfterGRU():
        K.clear_session() #清除之前的模型
        inputs = Input(shape=(TIME_STEPS, INPUT_DIM,))
        GRU_out = GRU(units, return_sequences=True)(inputs)
    
        attention_mul = Flatten()(attention_mul)
        output = Dense(3, activation='softmax')(attention_mul)
        model = Model(input=[inputs], output=output)
        return model
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3.在双向GRU层后添加Attention层

    def modelAttentionBiLSTM():
        K.clear_session()
        inputs = Input(shape=(TIME_STEPS, INPUT_DIM,))
        units = 128
        attention_mul = Flatten()(attention_mul)
        inputs= Dense(3, activativa='softmax')(attention_mul)
        model = Model(input=[inputs], output=output)
        return model
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    def getData(data_length):
        x_data = []
        label = []
        specimen_size = 1500 #设定输入序列长度,只取前1500个数据点
        #特征值取值范围,用于归一化处理
        d_max = 8922;d_min = 0;d_gap = d_max-d_min
        c_max = 29;c_min = 0;c_gap = c_max-c_min
        p = getDocumentList('./SCENARIO_DATA')
        for pp in p:
            q = getDocumentList('./SCENARIO_DATA/%s'%(pp))
            for qq in q:
                tree = ET.parse('./SCENARIO_DATA/%s/%s'%(pp,qq))
                root = tree.getroot()#获取xml文档的根节点
                if (root[0].tag=='轰炸' or root[0].tag=='反辐射' or root[0].tag=='护航'):
                    x_signal = [ [root[0][i].attrib[j] for j in ['x','y','z']] for i in range(len(root[0])) if root[0][i].tag=='数据' and i<specimen_size]
                    if(len(x_signal)>1000):
                        x_signal=list(np.array(x_signal,dtype=float))
                        d0 = 0
                        x_feature = []
                        if(len(x_signal)<data_length):
                            data_length = len(x_signal)
                        for i in range(0,data_length-5,3):
                            d = 0
                            for j in range(i,i+5):
                                dx = math.pow(x_signal[j+1][0]-x_signal[j][0],2)
                                dy = math.pow(x_signal[j+1][1]-x_signal[j][1],2)
                                dz = math.pow(x_signal[j+1][2]-x_signal[j][2],2)
                                d += math.sqrt(dx+dy+dz)
                            a = (d/15-d0/15)/6
                            d0 = d #保留用于下一段加速度的计算
                            #使用窗口中的三个点构建三角形拟合二次曲线
                            len1 = math.sqrt( math.pow(x_signal[i+2][0]-x_signal[i][0],2)+math.pow(x_signal[i+2][1]-x_signal[i][1],2)+math.pow(x_signal[i+2][2]-x_signal[i][2],2) )
                            len2 = math.sqrt( math.pow(x_signal[i+2][0]-x_signal[i+4][0],2)+math.pow(x_signal[i+2][1]-x_signal[i+4][1],2)+math.pow(x_signal[i+2][2]-x_signal[i+4][2],2) )
                            len3 = math.sqrt( math.pow(x_signal[i+4][0]-x_signal[i+2][0],2)+math.pow(x_signal[i+4][1]-x_signal[i][1],2)+math.pow(x_signal[i+4][2]-x_signal[i][2],2) )
                            if( len1==0 or len2==0 or len3==0):
                                c = 0
                            else:
                                half = (len1+len2+len3)/2
                                if(half<len1 or half<len2 or half<len3):
                                    c = 0
                                else:
                                    h = 2*math.sqrt( half*(half-len1)*(half-len2)*(half-len3) )/len3
                                    xh = math.sqrt(len1*len1-h*h)
                                    poly = np.polyfit([0,xh,len3],[1,h,0],deg=2)
                                    c = abs(poly[0])
                            x_feature.append([(d-d_min)/d_gap,(a-a_min)/a_gap,(c-c_min)/c_gap])#归一化处理
        
                        if len(x_feature)<500:
                            for j in range(500-len(x_feature)):
                                x_feature.append([0,0,0])
    
                        if root[0].tag=='轰炸':
                            label.append(0)
                            x_data.append(x_feature)
                        elif root[0].tag=='反辐射':
                            label.append(1)
                            x_data.append(x_feature)
                        elif root[0].tag=='护航':
                            label.append(2)
                            x_data.append(x_feature)
    
        x_data=np.array(x_data,dtype=float)
        #print(Counter(label))
        return x_data,label
    
    INPUT_DIM = 3 #输入特征维度
    TIME_STEPS = 500 #输入序列长度
    
    if __name__ == '__main__':
        
        x_data,y_data = getData(1500)
        training_time = []
        weighted_error_rate = []
        reduce_lr =  tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',factor=0.1,verbose=1,min_lr=0.0001,patience=10)#min_lr=0.0001
        for i_test in range(5):
            x_train,x_test, y_train,y_test= train_test_split(x_data, y_data, test_size=0.2, random_state=i_test, shuffle=True, stratify=y_data)
            start = time.time()
            #m = modelGRU() 
            m.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
            m.summary()
            historyGRU = m.fit([x_train], y_train, epochs=200, batch_size=32, validation_split=0.1,shuffle=True,callbacks=[reduce_lr])
            end = time.time()
            training_time.append(end-start)
            pred = m.predict(x_test)
            weighted_error_rate.append(weighted_error_rate_i)
        print("training_time: %0.3f s" % (np.mean(training_time)))  #均值和方差
        print("weighted_error_rate: %0.3f (± %0.3f)" % (np.mean(weighted_error_rate), np.var(weighted_error_rate))) #均值和方差
    
        #模型训练时的Loss可视化
        accGRU = historyGRU.history['accuracy']  # 训练集准确率
        lossGRU = historyGRU.history['loss']  # 训练集损失
        plt.plot(lossGRU, label='GRU')
        #plt.title('Training Loss')
        #使用中文图注
        plt.rcParams['font.sans-serif']=['SimHei']
        plt.rcParams['axes.unicode_minus']=False
        plt.xlabel('训练步数')
        plt.ylabel('损失')
        plt.legend()
        #plt.savefig('./训练损失.jpg')
        plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101

    三、各个函数的意义如下

    1、getData()函数负责读取xml文件,并处理成数据序列及对应的标签序列。参数data_length决定了所读取序列的长度。

    2、getDocumentList()函数用于辅助getData()函数进行数据读取。

    3、modelRNN()、modelLSTM()、modelGRU()都用于实现最基本的循环神经网络模型,只是所用神经元类型不同,分别为最基础的RNN、LSTM和GRU。

    4、attention_3d_block()函数定义了Attention层,参数SINGLE_ATTENTION_VECTOR为True时共享注意力权重。注意力权重共享是说,我们的特征在一个时间结点上是多维的,即有可能是多个特征随时间变换一起发生了变换,那对应的注意力算出来也是多维的。此时,是多维特征共享一个注意力权重,还是每一维特征单独有一个注意力权重呢?当SINGLE_ATTENTION_VECTOR=True时,Lambda层将原本多维的注意力权重取平均,RepeatVector层再按特征维度复制粘贴,那么每一维特征的权重都是一样的了,也就是所说的共享一个注意力。

    5、modelAttentionAfterGRU()用于实现在GRU层之后添加Attention层的模型。modelAttentionBiLSTM()用于实现在双向GRU层之后添加Attention层的模型。

    6、全局变量INPUT_DIM表示输入特征的维度;TIME_STEPS = 500 表示输入到神经网络层序列的长度。

    7、主函数中给出了一个示例:读取数据,划分训练集和测试集,多次训练神经网络模型进行交叉验证,计算加权错误率Weighted Error Rate和训练模型所用时间,最后将模型训练过程中的Loss(也可换成其他指标)变化可视化。

  • 相关阅读:
    AspNetCore 成长杂记(一):JWT授权鉴权之生成JWT(其一)
    《机器学习实战》学习笔记(十三)
    spark 集成 ClickHouse 和 MySQL (读和写操作)(笔记)
    08在MyBatis-Plus中配置多数据源
    B. Trouble Sort
    C#文件拷贝工具
    玩碎Java之ThreadLocal的原理
    盘点有趣的人工智能开源项目一
    C语言程序设计-10 指针
    leetcode分类刷题:基于数组的双指针(四、小的移动)
  • 原文地址:https://blog.csdn.net/DeepLearning_/article/details/127798309
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号