记录自己的UCF—Crime代码debug

昨天同门用了一天的时间帮我代码调通,再一次让我感觉到自己是个菜鸡,想想自己一个机器学习的代码都还没有好好看,所以未来的几天里痛定思痛,好好把手头里的这个代码调试一下,弄清楚每一句话都是干嘛的,都有什么意思。于是乎打算写篇文章也能记录一下自己的菜鸡之旅。

AL_Train.py

AllClassPath路径赋值为全部数据集的路径 
output__dir  
weights_path权重
model_path模型保存路径

Create Full connected Model

1.选择模型

Sequential:Keras有两种类型的模型,顺序模型以及函数式模型。而其中顺序模型是单输入单输出,一条路通到底,层与层之间只有相邻关系,没有跨层连接。

2.构建网络层

model.add(Dense(512, input_dim=4096,kernel_initializer='glorot_normal',kernel_regularizer=l2(0.001),activation='relu'))
# 512是节点数,input_dim是输入维度,也就是一阶的长度,kernel_initializer权重初始化的方法,权重规范化函数 activated激活函数

dropout随机失活60%

AdaGrad:优化的梯度下降算法,将每一个参数的每一次迭代的梯度取平方累加后在开方。用全局学习率除以这个数,作为学习率的动态更新。因为每个参数在动态更新时肯定是不一样的。

model.compile():用于配置训练方法时,告知训练时用的优化器,损失函数和准确率评测标准。

Load_dataset

listdir:返回一个列表,其中包含由path指定的目录中的条目名称。乱序

datetime.now():获得当前时间

Load_dataset_Train_batch()

np.random.permutation()对数据随机排列

Abnor_list_iter = Abnor_list_iter[Num_abnormal-n_exp:]
#对列表进行切片,第一个参数为开始,第二个为结尾

All_Video.append(line.strip())
#line.strip()去掉换行符

np.vstack()以行的形式堆叠列表形成新数组

All_Videos=[]
    with open(AbnormalPath+"anomaly.txt", 'r') as f1: #file contain path to anomaly video file.
      for line in f1:   
          All_Videos.append(line.strip())      #将视频文件名字存储为一个文档,然后读取每个名字,用strip()函数去掉换行
    AllFeatures = []
    print("Loading Anomaly videos Features...")

    Video_count=-1
    for iv in Abnor_list_iter:        #随机挑选了30个异常视频
        Video_count=Video_count+1
        VideoPath = os.path.join(AbnormalPath, All_Videos[iv])
        f = open(VideoPath, "r")
        words = f.read().split()              #将预处理过的视频txt文件进行切割
        num_feat = len(words) / 4096          #输入模型通道为4096
        
        count = -1;
        VideoFeatues = []
        for feat in range(0, int(num_feat)):
            feat_row1 = np.float32(words[feat * 4096:feat * 4096 + 4096])  #每次读取4096个数据
            count = count + 1
            if count == 0:
                VideoFeatues = feat_row1
            if count > 0:
                VideoFeatues = np.vstack((VideoFeatues, feat_row1)) 

        if Video_count == 0:
            AllFeatures = VideoFeatues
        if Video_count > 0:
            AllFeatures = np.vstack((AllFeatures, VideoFeatues))    #将全部的异常视频的数据形成一个大的数组,一个维度为4096,另一个为32*30
    print("Abnormal Features loaded")

    All_Videos=[]
    with open(NormalPath+"normal.txt", 'r') as f1: #file contain path to normal video file.
        for line in f1:
            All_Videos.append(line.strip())
    
    print("Loading Normal videos...")
  
    for iv in Norm_list_iter:
        VideoPath = os.path.join(NormalPath, All_Videos[iv])
        f = open(VideoPath, "r")
        words = f.read().split()
        feat_row1 = np.array([])
        num_feat = len(words) /4096
        count = -1;
        VideoFeatues = []
        for feat in range(0, int(num_feat)):
            feat_row1 = np.float32(words[feat * 4096:feat * 4096 + 4096])
            count = count + 1
            if count == 0:
                VideoFeatues = feat_row1
            if count > 0:
                VideoFeatues = np.vstack((VideoFeatues, feat_row1))
            feat_row1 = []
        AllFeatures = np.vstack((AllFeatures, VideoFeatues))

    print("Features loaded")     #与异常数据处理相同,然后再将正常处理得到的数据一起加载到异常的后面形成一个4096*1920(960*2)的数组
    AllLabels = np.zeros(32*batchsize, dtype='uint8') #初始化一个1920的数组,用来存储标签
    th_loop1=n_exp*32      #前960为异常视频
    th_loop2=n_exp*32-1    #后960为正常视频

    for iv in range(0, 32*batchsize):
            if iv< th_loop1:
                AllLabels[iv] = int(0)     #异常视频标签为0
            if iv > th_loop2:
                AllLabels[iv] = int(1)     #正常视频标签为1

视频特征以及视频标签处理完成,函数参数为正常以及异常视频的路径,返回全部视频特征以及视频标签

train_on_batch

是Keras提供的api(函数等等)对一个mini-batch的数据进行更新。

 def train_on_batch(self, x, y,sample_weight=None,class_weight=None):
#参数X为模型输入,参数Y为标签,sample_weight为每个样本对应的权重,class_weight类别权重,主要用于类别不平衡

custom_objective()自定义损失函数

1.flatten()将数组降为一维数据

2.T.stack()矩阵拼接函数,将两个或者多个拼接为一个数组

3.T.concatenate()将数据按行或按列拼在一起

 

 

C3D.py

preprocess_input()

get.file():从网上下载文件,参数分别为fname:下载后文件名,origin:下载的地址链接,cache_subdir:模型保存在哪个文件下。return返回值,返回文件的绝对地址

 

 

detect_test.py

os.path.basename():返回路径的最后一个文件名

cv2.VideoCapture(video_path):读取目的地址的视频文件 

ret, frame = cap.read():ret返回是否成功获取帧,frame是捕获到的图像


def get_video_clips(video_path):
    frames = get_video_frames(video_path)
    clips = sliding_window(frames, params.frame_count, params.frame_count)
    return clips, len(frames)


def get_video_frames(video_path):
    cap = cv2.VideoCapture(video_path)
    frames = []
    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
          frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
        else:
            break
    return frames

将视频剪切成为帧,然后将图像转化为灰度图,在进行切片,将16张图片放在一个切片中用于提取特征

numpy.linspace():在大间隔内,输出特定的小间隔的数据

numpy.ceil():计算大于等于该值的最小整数

imresize():改变图像的大小

 

到此项目基本上看完了

 

Summarize

有两个网络构成,一个是分类网络,一个是特征提取网络,其中特征提取网络的去权重已知。至于怎么用I3D代换,后续再来补。

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值