热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

【caffe】标准数据层输入

caffe在构造TrainNet时,首先要做的便是data和label的输入。数据层在Caffe的DataLayer中位于最底层,数据可以在高效的数据库

caffe在构造TrainNet时,首先要做的便是data和label的输入。数据层在Caffe的Data Layer中位于最底层,数据可以在高效的数据库中读取,也可以直接在内存中读取,或者从硬盘中直接读取

1. 数据层 LevedB 和 LMDB
层类型为data,主要分为LevedB 和 LMDB
其在*.prototxt文件中如下所示:

layer {name: "mnist"type: "Data"top: "data"top: "label"include {phase: TRAIN}transform param{ #这个参数主要负责输入数据的预处理scale = 0.00390625 #如减均值,尺度变换,随机裁剪或者镜像}data_param{source: "example/mnist/mnist_train.lmdb"}batch_size:64backend: LMDB
}

这里给出一种生成这种pycaffe的生成代码:

n.data, n.label = L.Data(name = 'MNIST', source = "example/mnist/mnist_train.lmdb", batch_size = 64, include = {'phase':0}, backend = P.Data.LMDB, ntop = 2, transform_param = dict(scale = 0.00390625))

2. 内存数据

layer {name: "memory_data"type: "MemoryData"top: "data"top: "label"memory_data_param{batch_size:2height: 100width: 100channels: 1}transform param{ scale: 0.0078125mean_file: "mean.proto"mirror: false}
}

3. HDF5数据

layer{name: "data"type: "HDF5Data"top: "data"top: "label"hdf5_data_param{source: "example/mnist/mnist_train.lmdb"batch_size: 10}
}

pycaffe接口:

n.data, n.label = L.HDF5Data(name = 'data', source = "example/mnist/mnist_train.lmdb", batch_size = 10, ntop = 2)

4. 图像数据Images

layer {name: "data"type: "ImageData"top: "data"top: "label"image_data_param{source: "example/mnist/mnist_train.lmdb"batch_size:50new_height: 256new_width: 256}transform param{ mirror: falsecrop_size: 227mean_file : "mean.proto"}
}

事实caffe可以自己来定义数据输入层,比如FCN代码的Python Layer形式,通过继承data layer的一些函数:
我直接把FCN中的PythonLayer放上来,这里仅仅作为事例:

import caffeimport numpy as np
from PIL import Imageimport randomclass VOCSegDataLayer(caffe.Layer):"""Load (input image, label image) pairs from PASCAL VOCone-at-a-time while reshaping the net to preserve dimensions.Use this to feed data to a fully convolutional network."""def setup(self, bottom, top):"""Setup data layer according to parameters:- voc_dir: path to PASCAL VOC year dir- split: train / val / test- mean: tuple of mean values to subtract- randomize: load in random order (default: True)- seed: seed for randomization (default: None / current time)for PASCAL VOC semantic segmentation.exampleparams = dict(voc_dir="/path/to/PASCAL/VOC2011",mean=(104.00698793, 116.66876762, 122.67891434),split="val")"""# configparams = eval(self.param_str)self.voc_dir = params['voc_dir']self.split = params['split']self.mean = np.array(params['mean'])self.random = params.get('randomize', True)self.seed = params.get('seed', None)# two tops: data and labelif len(top) != 2:raise Exception("Need to define two tops: data and label.")# data layers have no bottomsif len(bottom) != 0:raise Exception("Do not define a bottom.")# load indices for images and labelssplit_f = '{}/ImageSets/Segmentation/{}.txt'.format(self.voc_dir,self.split)self.indices = open(split_f, 'r').read().splitlines()self.idx = 0# make eval deterministicif 'train' not in self.split:self.random = False# randomization: seed and pickif self.random:random.seed(self.seed)self.idx = random.randint(0, len(self.indices)-1)def reshape(self, bottom, top):# load image + label image pairself.data = self.load_image(self.indices[self.idx])self.label = self.load_label(self.indices[self.idx])# reshape tops to fit (leading 1 is for batch dimension)top[0].reshape(1, *self.data.shape)top[1].reshape(1, *self.label.shape)def forward(self, bottom, top):# assign outputtop[0].data[...] = self.datatop[1].data[...] = self.label# pick next inputif self.random:self.idx = random.randint(0, len(self.indices)-1)else:self.idx += 1if self.idx == len(self.indices):self.idx = 0def backward(self, top, propagate_down, bottom):passdef load_image(self, idx):"""Load input image and preprocess for Caffe:- cast to float- switch channels RGB -> BGR- subtract mean- transpose to channel x height x width order"""im = Image.open('{}/JPEGImages/{}.jpg'.format(self.voc_dir, idx))in_ = np.array(im, dtype=np.float32)in_ = in_[:,:,::-1]in_ -= self.meanin_ = in_.transpose((2,0,1))return in_def load_label(self, idx):"""Load label image as 1 x height x width integer array of label indices.The leading singleton dimension is required by the loss."""im = Image.open('{}/SegmentationClass/{}.png'.format(self.voc_dir, idx))label = np.array(im, dtype=np.uint8)label = label[np.newaxis, ...]return labelclass SBDDSegDataLayer(caffe.Layer):"""Load (input image, label image) pairs from the SBDD extended labelingof PASCAL VOC for semantic segmentationone-at-a-time while reshaping the net to preserve dimensions.Use this to feed data to a fully convolutional network."""def setup(self, bottom, top):"""Setup data layer according to parameters:- sbdd_dir: path to SBDD `dataset` dir- split: train / seg11valid- mean: tuple of mean values to subtract- randomize: load in random order (default: True)- seed: seed for randomization (default: None / current time)for SBDD semantic segmentation.N.B.segv11alid is the set of segval11 that does not intersect with SBDD.Find it here: https://gist.github.com/shelhamer/edb330760338892d511e.exampleparams = dict(sbdd_dir="/path/to/SBDD/dataset",mean=(104.00698793, 116.66876762, 122.67891434),split="valid")"""# configparams = eval(self.param_str)self.sbdd_dir = params['sbdd_dir']self.split = params['split']self.mean = np.array(params['mean'])self.random = params.get('randomize', True)self.seed = params.get('seed', None)# two tops: data and labelif len(top) != 2:raise Exception("Need to define two tops: data and label.")# data layers have no bottomsif len(bottom) != 0:raise Exception("Do not define a bottom.")# load indices for images and labelssplit_f = '{}/{}.txt'.format(self.sbdd_dir,self.split)self.indices = open(split_f, 'r').read().splitlines()self.idx = 0# make eval deterministicif 'train' not in self.split:self.random = False# randomization: seed and pickif self.random:random.seed(self.seed)self.idx = random.randint(0, len(self.indices)-1)def reshape(self, bottom, top):# load image + label image pairself.data = self.load_image(self.indices[self.idx])self.label = self.load_label(self.indices[self.idx])# reshape tops to fit (leading 1 is for batch dimension)top[0].reshape(1, *self.data.shape)top[1].reshape(1, *self.label.shape)def forward(self, bottom, top):# assign outputtop[0].data[...] = self.datatop[1].data[...] = self.label# pick next inputif self.random:self.idx = random.randint(0, len(self.indices)-1)else:self.idx += 1if self.idx == len(self.indices):self.idx = 0def backward(self, top, propagate_down, bottom):passdef load_image(self, idx):"""Load input image and preprocess for Caffe:- cast to float- switch channels RGB -> BGR- subtract mean- transpose to channel x height x width order"""im = Image.open('{}/img/{}.jpg'.format(self.sbdd_dir, idx))in_ = np.array(im, dtype=np.float32)in_ = in_[:,:,::-1]in_ -= self.meanin_ = in_.transpose((2,0,1))return in_def load_label(self, idx):"""Load label image as 1 x height x width integer array of label indices.The leading singleton dimension is required by the loss."""import scipy.iomat = scipy.io.loadmat('{}/cls/{}.mat'.format(self.sbdd_dir, idx))label = mat['GTcls'][0]['Segmentation'][0].astype(np.uint8)label = label[np.newaxis, ...]return labe

在Pycaffe的Net生成中:

n.data, n.label = L.Python(module='voc_layers', layer=pylayer,ntop=2, param_str=str(pydata_params))

Python Layer还是比较好用的,可以随心所欲的定义自己的输入。还是要向大牛前辈学习一个


推荐阅读
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 合并列值-合并为一列问题需求:createtabletab(Aint,Bint,Cint)inserttabselect1,2,3unionallsel ... [详细]
  • 本文介绍了使用readlink命令获取文件的完整路径的简单方法,并提供了一个示例命令来打印文件的完整路径。共有28种解决方案可供选择。 ... [详细]
  • 在本教程中,我们将看到如何使用FLASK制作第一个用于机器学习模型的RESTAPI。我们将从创建机器学习模型开始。然后,我们将看到使用Flask创建AP ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • 本文介绍了使用数据库管理员用户执行onstat -l命令来监控GBase8s数据库的物理日志和逻辑日志的使用情况,并强调了对已使用的逻辑日志是否及时备份的重要性。同时提供了监控方法和注意事项。 ... [详细]
  • Python教学练习二Python1-12练习二一、判断季节用户输入月份,判断这个月是哪个季节?3,4,5月----春 ... [详细]
  • ①页面初始化----------收到客户端的请求,产生相应页面的Page对象,通过Page_Init事件进行page对象及其控件的初始化.②加载视图状态-------ViewSta ... [详细]
author-avatar
食品质量的安全
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有