分享好友 人工智能首页 频道列表

使用caffe的HDF5数据完毕回归任务

Caffe教程  2023-02-09 19:269430

    一直在研究怎样用caffe做行人检測问题。然而參考那些经典结构比方faster-rcnn等,都是自己定义的caffe层来完毕的检測任务。

这些都要求对caffe框架有一定程度的了解。近期看到了怎样用caffe完毕回归的任务,就想把检測问题当成回归问题来解决。

    我们把行人检測问题当成回归来看待,就须要限制检出目标的个数,由于我们的输出个数是固定的。所以,这里我假定每张图片最多检出的目标个数为2。即每一个目标用4个值来表示其位置信息(中心位置坐标x,y。

BBox的宽和高)。则网络的最后输出是8个值。


制作HDF5数据

    这里我们使用HDF5格式的数据来完毕我们的回归任务,那么首先我们须要的是制作h5格式的数据。

这里以VOC数据集为例。以下是制作HDF5格式数据的python代码。

import h5py
import caffe
import os
import xml.etree.ElementTree as ET
import cv2
import time
import math
from os.path import join, exists
import numpy as np

def convert(size, box):
    dw = 1./size[0]
    dh = 1./size[1]
    x = (box[0] + box[1])/2.0
    y = (box[2] + box[3])/2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x*dw
    w = w*dw
    y = y*dh
    h = h*dh
    return (x,y,w,h)

def shuffle_in_unison_scary(a, b):
    rng_state = np.random.get_state()
    np.random.shuffle(a)
    np.random.set_state(rng_state)
    np.random.shuffle(b)
    
def processImage(imgs):
    imgs = imgs.astype(np.float32)
    for i, img in enumerate(imgs):
        m = img.mean()
        s = img.std()
        imgs[i] = (img - m) / s
    return imgs

TrainImgDir = 'F:/GenerateHDF5/trainImage'
TrainLabelDir = 'F:/GenerateHDF5/trainLabels'
TestImgDir = 'F:/GenerateHDF5/testImg'
TestLabelDir = 'F:/GenerateHDF5/testLabels'

InImg = []
InBBox = []

for rootDir,dirs,files in os.walk(TestLabelDir):                                       #####
    for file in files:
        file_name = file.split('.')[0]
        full_file_name = '%s%s'%(file_name,'.jpg')
        full_file_dir = '%s/%s'%(TestImgDir,full_file_name)                            #####
        Img = cv2.imread(full_file_dir,cv2.CV_LOAD_IMAGE_GRAYSCALE)
        xml_file = open("%s/%s"%(rootDir,file))
        tree = ET.parse(xml_file)
        root = tree.getroot()
        size = root.find('size')
        w = int(size.find('width').text)
        h = int(size.find('height').text)
        
        landmark = np.zeros(8)
        count = 0
        for obj in root.iter('object'):
            count = count + 1
            if count == 3:
                break
            xmlbox = obj.find('bndbox')
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
            bb = convert((w,h), b)
            landmark[(count-1)*4+0]=bb[0]
            landmark[(count-1)*4+1]=bb[1]
            landmark[(count-1)*4+2]=bb[2]
            landmark[(count-1)*4+3]=bb[3]
        
        InBBox.append(landmark.reshape(8))
        Img = cv2.resize(Img,(h,w))
        InImg.append(Img.reshape((1,h,w)))           
            
InImg, InBBox = np.asarray(InImg), np.asarray(InBBox)
InImg = processImage(InImg)
shuffle_in_unison_scary(InImg, InBBox)

outputDir = 'hdf5/'
HDF5_file_name = 'hdf5_test.h5'                                                  #####
if not os.path.exists(outputDir):
    os.makedirs(outputDir)
    
output = join(outputDir,HDF5_file_name)
with h5py.File(output, 'w') as h5:
    h5['data'] = InImg.astype(np.float32)
    h5['labels'] = InBBox.astype(np.float32)
    h5.close()


这里注意一点,全部的BBox数据都要做归一化操作,即全部坐标要除以图片相应的宽高。据说,这样做能使最后得到的结果更好。


制作好了HDF5数据后。注意每一个H5文件大小不能超过2G(这是caffe的规定,假设一个文件超过2G。请分开制作多个)。

然后建立一个TXT文件,文件中写上全部H5文件的绝对路径。比方我这里建立的文件是list_train.txt。

然后我仅仅有一个H5文件,即hdf5_train.h5。所以我的list_train.txt文件中的内容就是/home/XXX/caffe/model/hdf5/hdf5_train.h5


配置solver文件

接下来是caffe的solver文件。这个文件没有什么差别,

test_iter: 20
test_interval: 70
base_lr: 0.0000000005
display: 9
max_iter: 210000
lr_policy: "step"
gamma: 0.1
momentum: 0.9
weight_decay: 0.0001
stepsize: 700
snapshot: 500
snapshot_prefix: "snapshot"
solver_mode: GPU
net: "train_val.prototxt"
solver_type: SGD

配置train_val.prototxt文件

接下来是网络的train_val.prototxt文件。这是caffe的网络结构文件,我们这里以LeNet网络为例。我这里是这种:

name: "LeNet"
layer {
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "labels"
  include {
    phase: TRAIN
  }
  hdf5_data_param {
    source: "list_train.txt"
    batch_size: 50
  }
}
layer {
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "labels"
  include {
    phase: TEST
  }
  hdf5_data_param {
    source: "list_test.txt"
    batch_size: 50
  }
}
layer {
  name: "conv1"
  type: "Convolution"
  bottom: "scaled"
  top: "conv1"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  convolution_param {
    num_output: 20
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "pool1"
  type: "Pooling"
  bottom: "conv1"
  top: "pool1"
  pooling_param {
    pool: MAX
    kernel_size: 2
    stride: 2
  }
}
layer {
  name: "conv2"
  type: "Convolution"
  bottom: "pool1"
  top: "conv2"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  convolution_param {
    num_output: 50
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "pool2"
  type: "Pooling"
  bottom: "conv2"
  top: "pool2"
  pooling_param {
    pool: MAX
    kernel_size: 2
    stride: 2
  }
}
layer {
  name: "ip1"
  type: "InnerProduct"
  bottom: "pool2"
  top: "ip1"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  inner_product_param {
    num_output: 500
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "relu1"
  type: "ReLU"
  bottom: "ip1"
  top: "ip1"
}
layer {
  name: "ip2"
  type: "InnerProduct"
  bottom: "ip1"
  top: "ip2"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  inner_product_param {
    num_output: 8
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "error"
  type: "EuclideanLoss"
  bottom: "ip2"
  bottom: "labels"
  top: "error"
  include {
      phase: TEST
  }
}
layer {
  name: "loss"
  type: "EuclideanLoss"
  bottom: "ip2"
  bottom: "labels"
  top: "loss"
  include {
      phase: TRAIN
  }
}

这里注意的是。最后的一层全连接层,输出的num_output应该是你label的维度,我这里是8。然后最后的loss计算,我使用的是欧氏距离的loss,也能够试着用其它类型的loss。


開始训练

依照以上步骤配置好了,最后就是训练了。

在控制台中输入下面指令来训练我们的数据:

./cafferoot/caffe/tools/caffe train --solver=solver.prototxt

可能是我数据源的问题,我的loss一開始很大。然后一直降不下来。也有可能是LeNet本身网络性能就不好。

关于网络的性能还须要另外再想办法提升。


查看更多关于【Caffe教程】的文章

展开全文
相关推荐
反对 0
举报 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
caffe调试 ubuntu1404+eclipse
转自:http://blog.csdn.net/yaoxingfu72/article/details/47999795首先确保你caffe编译成功,而且makefile.config中将DEBUG:=1那一行取消注释,我的caffe根目录为 caffe-master。你也可以在Eclipse中编译caffe,我是先编译好caffe,然后进入Eclipse中调试1

0评论2023-03-08522

Caffe hdf5 layer data 大于2G 的导入
问题:      Datatype class: H5T_FLOAT,      Check failed: error == cudaSuccess (2 vs. 0)  out of memory.      hdf5 layer 最大的导入的大小是2G, 超过会报错[1]。解决方法:     有人 h5repart -m1g 将数据集分割成多个文件每个是

0评论2023-02-10987

caffe神经网络中不同的lr_policy间的区别
lr_policy可以设置为下面这些值,相应的学习率的计算为:- fixed:   保持base_lr不变.- step:    如果设置为step,则还需要设置一个stepsize,  返回 base_lr * gamma ^ (floor(iter / stepsize)),其中iter表示当前的迭代次数- exp:     返回base_lr

0评论2023-02-10949

Ubuntu配置GPU+CUDA+CAFFE ubuntu配置dns
参考网站:http://blog.csdn.net/xizero00/article/details/43227019/ (主要参考)http://www.cnblogs.com/platero/p/3993877.html (caffe+cudaGPU)http://www.cnblogs.com/platero/p/4118139.html (cuDNN)http://developer.download.nvidia.com/compute/cuda/

0评论2023-02-10616

关于深度学习(deep learning)的常见疑问 --- 谷歌大脑科学家 Caffe缔造者 贾扬清
问答环节问:在finetuning的时候,新问题的图像大小不同于pretraining的图像大小,只能缩放到同样的大小吗?” 答:对的:)问:目前dl在时序序列分析中的进展如何?研究思路如何,能简单描述一下么答:这个有点长,可以看看google最近的一系列machine trans

0评论2023-02-10646

深度学习框架Caffe —— Deep learning in Practice
因工作交接需要, 要将caffe使用方法及整体结构描述清楚。 鉴于也有同学问过我相关内容, 决定在本文中写个简单的tutorial, 方便大家参考。 本文简单的讲几个事情:Caffe能做什么?为什么选择caffe?环境整体结构Protocol buffer训练基本流程Python中训练Debu

0评论2023-02-09598

Caffe 编译: undefined reference to imencode()
本系列文章由 @yhl_leo 出品,转载请注明出处。 文章链接:http://blog.csdn.net/yhl_leo/article/details/52150781 整理之前编译工程中遇到的一个Bug,贴上提示log信息:...CXX/LD -o .build_release/examples/siamese/convert_mnist_siamese_data.bin.build

0评论2023-02-09884

[caffe]caffe资料收集 Caffeine.
1.caffe主页,有各种tutorial。2.Evan Shelhamer的tutorial,包括视频。 

0评论2023-02-09776

caffe_ssd学习-用自己的数据做训练 ssd caffe
几乎没用过linux操作系统,不懂shell编程,linux下shell+windows下UltraEdit勉勉强强生成了train.txt和val.txt期间各种错误辛酸不表,照着examples/imagenet/readme勉勉强强用自己的数据,按imagenet的训练方法,把reference_caffenet训起来了,小笔记本的风

0评论2023-02-09664

caffe Python API 之中值转换
# 编写一个函数,将二进制的均值转换为python的均值def convert_mean(binMean,npyMean):blob = caffe.proto.caffe_pb2.BlobProto()bin_mean = open(binMean, 'rb' ).read()blob.ParseFromString(bin_mean)arr = np.array( caffe.io.blobproto_to_array(blob)

0评论2023-02-09843

Windows10安装ubuntu & caffe GPU版
1.Ubuntu https://www.cnblogs.com/EasonJim/p/7112413.htmlhttps://blog.csdn.net/jesse_mx/article/details/61425361 安装后启动不了,直接进入windows.解决方案:https://www.cnblogs.com/lymboy/p/7783756.htmlhttps://jingyan.baidu.com/article/5553fa

0评论2023-02-091018

caffe(1) 网络结构层参数详解
prototxt文件是caffe的配置文件,用于保存CNN的网络结构和配置信息。prototxt文件有三种,分别是deploy.prototxt,train_val.prototxt和solver.prototxt。solver.prototxt是caffe的配置文件。里面定义了网络训练时候的各种参数,比如学习率、权重衰减、迭代次

0评论2023-02-09738

更多推荐