使用深度学习来进行击剑动作识别的裁判工作

news2024/9/20 15:21:15

在击剑比赛中,当双方几乎同时击中对方时,记分板两边都会亮起。这时裁判需要决定哪一方得分。一般而言,谁更主动或控制了局势就会得分。我尝试训练了一个模型来辅助裁判做这样的判断!目前该模型在花剑测试集上的准确率大约为60%,相比随机选择(左、右或无得分)的33%有了提升。接下来我将对佩剑数据进行测试。(在重剑比赛中,双方同时击中则双方都得分。)

这里有几个主要挑战,首要的是缺乏标注过的击剑视频数据集!通常来说,视频分类领域还没有图像分类那么成熟,即使是像SPORTS 1-M这样的流行视频数据集,仅通过单帧图像就能达到非常不错的准确度。大多数用于视频分类的模型架构结合了卷积神经网络和循环神经网络:卷积层提取每帧的特征,而循环网络则基于这些特征做出最终判断。一个特别有趣的想法是构建一个全循环卷积网络,其中每一层都是循环的。目前我采用了一种需要较少数据的方法,即使用预训练的InceptionV3网络对每个视频帧提取卷积特征(即将每帧转换为1x2048维的向量)。Inception网络中这个特征向量接着被一个全连接层用来分类ImageNet数据库中的图像,但同样的特征向量也可以很好地表示我的视频帧中的情况。然后一个多层LSTM网络在这些特征向量序列上进行训练。我在AWS的p2 spot实例上进行了模型训练。

为了使网络更快地捕捉到相对运动的概念,在将每帧转换为特征向量之前,计算出该帧与前一帧之间的密集光流,并将其映射到彩色轮盘上叠加在该帧上。原始帧被转为黑白,以便网络不必学习区分运动和原始颜色。使用光流的灵感来源于Karen Simonyan和Andrew Zisserman的论文《Two-Stream Convolutional Networks for Action Recognition in Videos》。

我希望对探索机器学习新应用感兴趣的人能够从这里提供的代码中获益。它将引导你从创建自己的数据集一直到如何加载和使用预训练模型,以及训练和部署自己的模型。

创建击剑视频片段数据库 简而言之,我下载了所有世界杯击剑比赛的视频,并使用OpenCV将视频分割成短片段,这些片段涵盖了记分板每次亮起前的时间。然后,我训练了一个小型逻辑回归分类器来识别记分板数字的变化。在某些情况下(仅当双方同时击中且至少有一方命中有效区域时),裁判必须做出判断。根据记分板的变化方式,我们可以自动标记这些片段来表明是谁得分。所有只有一个灯亮的片段都被丢弃,因为它们无法自动标注。

随后,我对视频进行了下采样处理,保留了更多结尾部分的帧。这些片段被水平翻转以增加数据集的大小。之后,我使用OpenCV在片段上叠加了光流图。最后,这些片段被转换为numpy数组并使用hickle包进行保存和压缩。由于文件很大,数据集是以每100个片段为一个块来保存的,每个块的尺寸为100 x 帧数 x 高 x 宽 x 深度。最终我从能找到的比赛视频中获得了大约5,500个片段,加上水平翻转后变成了约11,000个片段。

模型架构 因为我们没有大量的样本,使用迁移学习来提取特征而不是训练自己的卷积层是有意义的。这样只有顶部的循环网络需要从头开始学习。我尝试了几种架构,发现4层带有0.2的dropout率效果不错。如果不使用dropout作为正则化手段,模型会开始过拟合。我计划不久后研究批量归一化作为正则化方法。

使用预训练的Inception网络 这里所做的就是取用InceptionV3网络倒数第二层的张量。~ 正在继续编写中。

下一步 我已经在玩具问题上实现了全循环网络的例子(例如在MNIST数据集上只显示图像的部分切片,模拟时间维度)。很快我会启动服务器并重新下载/处理所有数据,因为这里的互联网速度太慢以至于无法上传完整数据(约40GB),但在笔记本电脑上处理数据然后上传特征向量是没有问题的。首先,我很好奇模型在佩剑数据集上的表现是否会更好,所以将在接下来的一周内运行测试。

 


# coding: utf-8

# In[1]:

############ To use tensorboard, include all the summary op code below, and type: 
# tensorboard --logdir=/tmp/logs_path
# to launch type http://0.0.0.0:6006/ in a search bar 
# to kill ps -e | grep tensorboard in terminal
# the first number is the PID, type kill PID

import tensorflow as tf
import numpy as np
import argparse
import time
import subprocess as sp
import os
import hickle as hkl
print tf.__version__

num_layers = 4
drop_out_prob = 0.8
batch_size = 30
epochs = 30
learning_rate = 0.00001
test_size = 800
validation_size = 600
# In[40]:

videos_loaded = 0
for i in os.listdir(os.getcwd()):
    if i.endswith(".hkl"):
        if 'features' in i:
            print i
            if videos_loaded == 0:
                loaded = hkl.load(i)
            else:
                loaded = np.concatenate((loaded,hkl.load(i)), axis = 0)
            videos_loaded = videos_loaded + 1
            print loaded.shape


# In[41]:

videos_loaded = 0
for i in os.listdir(os.getcwd()):
    if i.endswith(".hkl"):
        if "labels" in i:
            print i
            if videos_loaded == 0:
                labels = hkl.load(i)
            else:
                labels = np.concatenate((labels,hkl.load(i)), axis = 0)
            videos_loaded = videos_loaded + 1
            print labels.shape
## Orders match up! Thats good.



def unison_shuffled_copies(a, b):
    assert len(a) == len(b)
    p = np.random.permutation(len(a))
    return a[p,:,:], b[p,:]

#reorder identically.
loaded, labels = unison_shuffled_copies(loaded,labels)
print loaded.shape, labels.shape

## Take the first 'test_size' examples as a test set. 
test_set = loaded[:test_size]
test_labels = labels[:test_size]
## Take indices from end of test_set to end of validation set size as our validation set
validation_set = loaded[test_size:(validation_size+test_size)]
validation_labels = labels[test_size:(validation_size+test_size)]
test_set_size = len(test_set)
## Now cut off the first 'test_size' + valid set numbers examples, because those are the test and validation sets
loaded = loaded[(test_size+validation_size):]
labels = labels[(test_size+validation_size):]
print "Test Set Shape: ", test_set.shape
print "Validation Set Shape: ", validation_set.shape
print "Training Set Shape: ", loaded.shape

## Save our test to test when we load the model we've trained. 
hkl.dump(test_set, 'test_data.hkl', mode='w', compression='gzip', compression_opts=9)
hkl.dump(test_labels, 'test_lbls.hkl', mode='w', compression='gzip', compression_opts=9)

device_name = "/gpu:0"

with tf.device(device_name):

    tf.reset_default_graph()


    logs_path = '/tmp/4_d-0.8'
    
    ## How often to print results and save checkpoint.
    display_step = 40

    # Network Parameters
    n_input = 2048 # 2048 long covolutional feature vector
    n_hidden = 1024 # hidden layer numfeatures
    n_classes = 3 # There are 3 possible outcomes, left, together, right
    

    # tf Graph input
    x = tf.placeholder("float32", [None, None, n_input]) ## this is [batch_size, n_steps, len_input_feature_vector]
    y = tf.placeholder("float32", [None, n_classes])
    input_batch_size = tf.placeholder("int32", None)

    # Define weights
    weights = {
        'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
    }
    biases = {
        'out': tf.Variable(tf.random_normal([n_classes]))
    }


    def RNN(x, weights, biases):

        
        cell = tf.contrib.rnn.LSTMCell(n_hidden, state_is_tuple=True)
        ## Variational recurrent = True means the same dropout mask is applied at each step. 
        cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=drop_out_prob)
        cell = tf.contrib.rnn.MultiRNNCell([cell] * num_layers, state_is_tuple=True)
        init_state = cell.zero_state(input_batch_size, tf.float32)
        outputs, states = tf.nn.dynamic_rnn(cell,x, initial_state = init_state, swap_memory = True) # swap_memory = True is incredibly important, otherwise gpu will probably run out of RAM
        print states
        # Linear activation, outputs -1 is the last 'frame'.
        return tf.matmul(outputs[:,-1,:], weights['out']) + biases['out']







    with tf.name_scope('Model'):
        pred = RNN(x, weights, biases)
    print "prediction", pred
    # Define loss and optimizer
    with tf.name_scope('Loss'):
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
    with tf.name_scope('SGD'):
        optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

    # Evaluate model
    with tf.name_scope('Accuracy'):
        correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

    # Initializing the variables
    init = tf.global_variables_initializer()

    # Create a summary to monitor cost tensor
    tf.summary.scalar("loss", cost)
    # Create a summary to monitor accuracy tensor
    tf.summary.scalar("training_accuracy", accuracy)
    # Merge all summaries into a single op
    merged_summary_op = tf.summary.merge_all()


# In[ ]:

current_epochs = 0
# Launch the graph
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    saver = tf.train.Saver()
    sess.run(init)
    summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())
    step = 0
    
    
        
    # Keep training until we don't have any more data
    while step < (len(labels)/batch_size):
        batch_x = loaded[step*batch_size:(step+1)*batch_size]
        batch_y = labels[step*batch_size:(step+1)*batch_size]
       
        # x is in form batch * frames * conv_feature_size
        # y is in form batch * labels
        # Run optimization op (backprop)
        _,acc,loss,summary = sess.run([optimizer,accuracy,cost,merged_summary_op], feed_dict={x: batch_x, y: batch_y, input_batch_size:batch_size})
        print 'ran'
        ## The divide/multiply makes sense because it is reducing it to an int, i.e getting the whole number, could also cast as int, but this shows intent better.
        summary_writer.add_summary(summary, step*batch_size+current_epochs * (len(labels)/batch_size)*batch_size)

        if step % display_step == 0:
            # Calculate batch accuracy

            # calculate validation-set accuracy, because the GPU RAM is too small for such a large batch (the entire validation set, feed it through bit by bit)
            accuracies = []
            train_drop_out_prob = drop_out_prob
            drop_out_prob = 1.0
            for i in range(0,validation_size/batch_size):
                validation_batch_data = validation_set[i*batch_size:(i+1)*batch_size]
                validation_batch_labels = validation_labels[i*batch_size:(i+1)*batch_size]
                validation_batch_acc,_ = sess.run([accuracy,cost], feed_dict={x: validation_batch_data, y: validation_batch_labels, input_batch_size: batch_size})    
                accuracies.append(validation_batch_acc)
                

            # Create a new Summary object with your measure and add the summary
            summary = tf.Summary()
            summary.value.add(tag="Validation_Accuracy", simple_value=sum(accuracies)/len(accuracies))
            summary_writer.add_summary(summary, step*batch_size +current_epochs * (len(labels)/batch_size)*batch_size)
            # Save a checkpoint
            saver.save(sess, 'fencing_AI_checkpoint')
            
            print "Validation Accuracy - All Batches:", sum(accuracies)/len(accuracies)
            
            ## Set dropout back to regularizaing
            drop_out_prob = train_drop_out_prob
                
            print "Iter " + str(step*batch_size+current_epochs * (len(labels)/batch_size)*batch_size) + ", Minibatch Loss= " + \
                  "{:.6f}".format(loss) + ", Train Accuracy= " + \
                  "{:.5f}".format(acc)
                    
            


        step += 1
        if current_epochs < epochs:
            if step >= (len(labels)/batch_size):
                print "###################### New epoch ##########"
                current_epochs = current_epochs + 1
                learning_rate = learning_rate- (learning_rate*0.15)
                step = 0

                # Randomly reshuffle every batch.
                loaded, labels = unison_shuffled_copies(loaded,labels)

        
    print "Learning finished!"

  





 

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

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

相关文章

Vue开发者工具安装详细教程

欢迎大家订阅【Vue2Vue3】入门到实践 专栏&#xff0c;开启你的 Vue 学习之旅&#xff01; 文章目录 前言一、下载二、安装三、调试 前言 Vue 是一个框架&#xff0c;也是一个生态&#xff0c;其功能覆盖了大部分前端开发常见的需求。本文详细讲解了 Vue 开发者工具的安装。 …

ES7.17.5 float类型 terms带来的隐患

背景 1.用户在mapping中加一个字段 testid&#xff0c;结果写数据的时候使用 testId&#xff0c;同时也没有strict限制动态mapping&#xff0c;只是使用了默认的 true&#xff0c;即允许动态生成mapping 2.动态生成的字段 testId 被识别成了 float&#xff0c;用户为了方便&a…

【Netty 一】

Netty是什么 Netty 是一个高性能、异步事件驱动的 NIO 框架&#xff0c;基于 JAVA NIO 提供的 API 实现。它提供了对 TCP、 UDP 和文件传输的支持&#xff0c;作为一个异步 NIO 框架&#xff0c; Netty 的所有 IO 操作都是异步非阻塞 的&#xff0c; 通过 Future-Listener 机制…

ssrf漏洞之——漏洞复现

漏洞介绍 SSRF漏洞&#xff1a;SSRF(Server-Side Request Forgery:服务器端请求伪造) 是一种由恶意访问者构造url&#xff0c;由服务端对此url发起请求的一个安全漏洞。 漏洞原理 SSRF 形成的原因大都是由于服务端提供了从其他服务器应用获取数据的功能&#xff0c;并且没有对目…

Autosar(Davinci) --- 创建一个Implementation Data Types

前言 这里我们讲一下如何创建一个Implementation Data Types&#xff08;IDT) 一、什么是IDT 二、如何创建一个IDT 鼠标右键【Implementation Data Types】,选择【new Type Reference...】 起一个名字【IdtDoorState】&#xff0c;Data Types选择【boolean】&#xff0c;这里…

RFID光触发标签应用于制造业供应链管理的应用与探索

制造业作为国民经济的支柱产业&#xff0c;其供应链管理的复杂性和重要性日益凸显&#xff0c;在全球化竞争的背景下&#xff0c;企业需要更高效、更精准、更智能的供应链解决方案来满足市场需求&#xff0c;提高客户满意度&#xff0c;降低运营成本&#xff0c;RFID光触发标签…

【mysql】mysql的卸载和安装

mysql的卸载 mysql是否安装&#xff1a; 首先我们先来看看mysql是否安装&#xff1a; 快捷键winR输入cmd&#xff0c;进入命令输入框 输入mysql --version 查看mysql的版本 如果出现了mysql的版本就说明你已经安装了 系统用户root -p就是输入密码所以代码如下 mysql -ur…

AI大模型编写多线程并发框架(六十一):从零开始搭建框架

系列文章目录 文章目录 系列文章目录前言一、项目背景二、第一轮对话-让AI大模型理解我们的诉求二、第二轮对话-优化任务处理方法和结果处理方法三、参考文章 前言 在这个充满技术创新的时代&#xff0c;AI大模型正成为开发者们的新宠。它们可以帮助我们完成从简单的问答到复杂…

模拟实现STL中的unordered_map和unordered_set

目录 1.unordered_map和unordered_set简介 2.unordered_map和unordered_set设计图 3.迭代器的设计 4.哈希表的设计 5.my_unordered_map和my_unordered_set代码 1.unordered_map和unordered_set简介 unordered_map和unordered_set的使用非常类似于map和set&#xff0c;两…

【Linux】日志函数

欢迎来到 破晓的历程的 博客 ⛺️不负时光&#xff0c;不负己✈️ 文章目录 引言日志内容日志等级日志函数的编写函数原型参数说明功能描述使用场景示例代码 引言 日志在程序设计中扮演着至关重要的角色&#xff0c;它不仅是程序运行情况的记录者&#xff0c;还是问题诊断、性…

【机器学习】智驭未来:机器学习如何重塑现代城市管理新生态

&#x1f4dd;个人主页&#x1f339;&#xff1a;Eternity._ &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f339; ❀目录 &#x1f50d;1. 引言&#xff1a;迈向智能城市的新时代&#x1f4d2;2. 智驭交通&#xff1a;机器学习在智能交通管理中的应用&#x1…

仿Muduo库实现高并发服务器——LoopThreadPool模块

这个模块需要具备那些基础知识。 线程创建相关操作&#xff0c;锁&#xff0c;条件变量。 设置线程数量&#xff1a; _thread_count 是线程池中&#xff0c;记录线程数量的成员。 创建线程池&#xff1a; 上图就是线程池的创建&#xff0c;将线程与EventLoop对象 通过数组下…

关于嘉立创eda中同一个项目下多个原理图是否独立

嘉立创项目底下&#xff0c;如果你新建了多张原理图&#xff0c;如下 我发现&#xff0c;多张原理图是互相连接的&#xff0c;所以命名是不能重复的 多页原理图 | 嘉立创EDA标准版用户指南https://docs.lceda.cn/cn/Schematic/Multi-Sheet/index.html 上面是嘉立创原文介绍 综…

豆瓣评分7.9!世界级讲师耗时5年整理出的Python学习手册!

Python是一门流行的开源编程语言&#xff0c;广泛用于各个领域的独立程序与脚本化应用中。它不仅免费、可移植、功能强大&#xff0c;同时相对简单&#xff0c;而且使用起来充满乐趣。从软件业界的任意一角到来的程序员&#xff0c;都会发现Python着眼于开发者的生产效率以及软…

编程仙尊——深入理解指针(2)

目录 4.const修饰指针 4.1const修饰变量 5.指针运算 5.1指针-整数 5.2指针-指针 5.3指针的关系运算 6.assert断言 4.const修饰指针 4.1const修饰变量 在编程中&#xff0c;为了防止代码在运行过程中变量的内容意外改变&#xff0c;可以使用const函数&#xff0c;对变量…

介绍python的回归模型原理知识

一.回归 1.什么是回归 回归&#xff08;Regression&#xff09;最早是英国生物统计学家高尔顿和他的学生皮尔逊在研究父母和子女的身高遗传特性时提出的。1855年&#xff0c;他们在《遗传的身高向平均数方向的回归》中这样描述“子女的身高趋向于高于父母的身高的平均值&…

Linux云计算 |【第二阶段】SHELL-DAY2

主要内容&#xff1a; 条件测试&#xff08;字符串比较、整数比较、文件状态&#xff09;、IF选择结构&#xff08;单分支、双分支、多分支&#xff09;、For循环结构、While循环结构 一、表达式比较评估 test 命令是 Unix 和 Linux 系统中用于评估条件表达式的命令。它通常用…

小乌龟运动控制-1 小乌龟划圆圈

目录 第一章 小乌龟划圆圈 第二章 小乌龟走方形 文章目录 目录前言一、准备工作步骤一&#xff1a;创建ROS工作空间步骤二&#xff1a;创建ROS包和节点步骤三&#xff1a;编写Python代码步骤四&#xff1a;运行ROS节点总结 前言 本教程将教会你如何使用Python编写ROS小海龟节…

【SpringCloud】(一文通)优雅实现远程调用-OpenFeign

目 录 一. RestTemplate存在问题二. OpenFeign介绍三. 快速上手3.1 引入依赖3.2 添加注解3.3 编写 OpenFeign 的客户端3.4 远程调用3.5 测试 四. OpenFeign 参数传递4.1 传递单个参数4.2 传递多个参数4.3 传递对象4.4 传递JSON 五. 最佳实践5.1 Feign 继承方式5.1.1 创建⼀个Mo…

马克思发生器有什么用_马克思发生器工作原理

马克思发生器&#xff08;Marx Generator&#xff09;是一种电气装置&#xff0c;用于产生高压脉冲电压。它由多个电容器组成&#xff0c;这些电容器依次连接在一系列开关之后。首先&#xff0c;每个电容器被并联充电至较低的电压。然后&#xff0c;这些电容器被开关依次串联&a…