我正在使用caffe进行回归,而我的test.txt
和train.txt
文件是这样的:
/home/foo/caffe/data/finetune/flickr/3860781056.jpg 2.0
/home/foo/caffe/data/finetune/flickr/4559004485.jpg 3.6
/home/foo/caffe/data/finetune/flickr/3208038920.jpg 3.2
/home/foo/caffe/data/finetune/flickr/6170430622.jpg 4.0
/home/foo/caffe/data/finetune/flickr/7508671542.jpg 2.7272
我的问题是,当我在阅读时使用浮动标签时,似乎caffe不允许像2.0这样的浮动标签,例如'test.txt'
文件caffe只能识别
共1张图片
这是错的。
但是当我例如将文件中的2.0更改为2并且以下行相同时,caffe现在给出了
共2张图片
暗示浮动标签是造成问题的原因。
任何人都可以帮助我,解决这个问题,我肯定需要使用浮动标签进行回归,所以有人知道解决方案或解决方案吗?提前致谢。
编辑对于任何面临类似问题的人来说,use caffe to train Lenet with CSV data可能会有所帮助。感谢@Shai。
使用图像数据集输入图层(使用lmdb
或leveldb
后端)时,caffe仅支持每个输入图像一个整数标签。
如果要进行回归并使用浮点标签,则应尝试使用HDF5数据层。例如,参见this question。
在python中,您可以使用h5py
包来创建hdf5文件。
import h5py, os
import caffe
import numpy as np
SIZE = 224 # fixed size to all images
with open( 'train.txt', 'r' ) as T :
lines = T.readlines()
# If you do not have enough memory split data into
# multiple batches and generate multiple separate h5 files
X = np.zeros( (len(lines), 3, SIZE, SIZE), dtype='f4' )
y = np.zeros( (len(lines),1), dtype='f4' )
for i,l in enumerate(lines):
sp = l.split(' ')
img = caffe.io.load_image( sp[0] )
img = caffe.io.resize( img, (SIZE, SIZE, 3) ) # resize to fixed size
# you may apply other input transformations here...
# Note that the transformation should take img from size-by-size-by-3 and transpose it to 3-by-size-by-size
# for example
# transposed_img = img.transpose((2,0,1))[::-1,:,:] # RGB->BGR
X[i] = transposed_img
y[i] = float(sp[1])
with h5py.File('train.h5','w') as H:
H.create_dataset( 'X', data=X ) # note the name X given to the dataset!
H.create_dataset( 'y', data=y ) # note the name y given to the dataset!
with open('train_h5_list.txt','w') as L:
L.write( 'train.h5' ) # list all h5 files you are going to use
一旦你有了所有h5
文件和列出它们的相应测试文件,你就可以在你的train_val.prototxt
中添加一个HDF5输入层:
layer {
type: "HDF5Data"
top: "X" # same name as given in create_dataset!
top: "y"
hdf5_data_param {
source: "train_h5_list.txt" # do not give the h5 files directly, but the list.
batch_size: 32
}
include { phase:TRAIN }
}
澄清:
当我说“caffe每个输入图像只支持一个整数标签”时,我并不是说leveldb / lmdb容器是有限的,我的意思是caffe的工具,特别是convert_imageset
工具。
仔细观察,似乎caffe在leveldb / lmdb中存储Datum
类型的数据,并且此类型的“label”属性被定义为整数(请参阅caffe.proto),因此当使用caffe接口到leveldb / lmdb时,您被限制为单个int32每张图片标签。
Shai's answer已经将浮动标签保存为HDF5格式。如果LMDB是必需/首选的,这里有一个关于如何从float数据创建LMDB的片段(改编自this github comment):
import lmdb
import caffe
def scalars_to_lmdb(scalars, path_dst):
db = lmdb.open(path_dst, map_size=int(1e12))
with db.begin(write=True) as in_txn:
for idx, x in enumerate(scalars):
content_field = np.array([x])
# get shape (1,1,1)
content_field = np.expand_dims(content_field, axis=0)
content_field = np.expand_dims(content_field, axis=0)
content_field = content_field.astype(float)
dat = caffe.io.array_to_datum(content_field)
in_txn.put('{:0>10d}'.format(idx) dat.SerializeToString())
db.close()
我最终调换,切换频道顺序,并使用无符号整数而不是浮点数来获得结果。我建议您从HDF5文件中读取图像,以确保它正确显示。
首先将图像作为无符号整数读取:
img = np.array(Image.open('images/' + image_name))
然后将通道顺序从RGB更改为BGR:
img = img[:, :, ::-1]
最后,从高度x宽度x通道切换到通道x高度x宽度:
img = img.transpose((2, 0, 1))
仅仅改变形状会扰乱你的形象并破坏你的数据!
要回读图像:
with h5py.File(h5_filename, 'r') as hf:
images_test = hf.get('images')
targets_test = hf.get('targets')
for i, img in enumerate(images_test):
print(targets_test[i])
from skimage.viewer import ImageViewer
viewer = ImageViewer(img.reshape(SIZE, SIZE, 3))
viewer.show()
这是我写的一个脚本,它处理自动驾驶汽车任务的两个标签(转向和速度):https://gist.github.com/crizCraig/aa46105d34349543582b177ae79f32f0
除了上面的@Shai's answer,我写了一个支持MultiTaskData类型标签的float
层。
其主要思想是将标签存储在float_data
的Datum
字段中,并且MultiTaskDataLayer
将根据task_num
中设置的label_dimension
和net.prototxt
的值将它们解析为任意数量任务的标签。相关文件包括:caffe.proto
,multitask_data_layer.hpp/cpp
,io.hpp/cpp
。
您可以轻松地将此图层添加到您自己的caffe中并像这样使用它(这是面部表情标签分布学习任务的示例,其中“exp_label”可以是浮点型向量,例如[0.1,0.1,0.5,0.2,0.1 ]表示面部表情(5级)的概率分布。):
name: "xxxNet"
layer {
name: "xxx"
type: "MultiTaskData"
top: "data"
top: "exp_label"
data_param {
source: "expression_ld_train_leveldb"
batch_size: 60
task_num: 1
label_dimension: 8
}
transform_param {
scale: 0.00390625
crop_size: 60
mirror: true
}
include:{ phase: TRAIN }
}
layer {
name: "exp_prob"
type: "InnerProduct"
bottom: "data"
top: "exp_prob"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
inner_product_param {
num_output: 8
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "exp_loss"
type: "EuclideanLoss"
bottom: "exp_prob"
bottom: "exp_label"
top: "exp_loss"
include:{ phase: TRAIN }
}