I have a lasagane code. I want to create the same network using caffe. I could convert the network. But i need help with the hyperparameters in lasagne. The hyperparameters in lasagne look like:
lr = 1e-2
weight_decay = 1e-5
prediction = lasagne.layers.get_output(net['out'])
loss = T.mean(lasagne.objectives.squared_error(prediction, target_var))
weightsl2 = lasagne.regularization.regularize_network_params(net['out'], lasagne.regularization.l2)
loss += weight_decay * weightsl2
How do i perform the L2 regularization part in caffe? Do I have to add any layer for regularization after each convolution/inner-product layer? Relevant parts from my solver.prototxt is as below:
base_lr: 0.01
lr_policy: "fixed"
weight_decay: 0.00001
regularization_type: "L2"
stepsize: 300
gamma: 0.1
max_iter: 2000
momentum: 0.9
also posted in http://datascience.stackexchange.com. Waiting for answers.
It seems like you already got it right.
The weight_decay meta-parameter combined with regularization_type: "L2" in your 'solver.prototxt' tell caffe to use L2 regularization with weight_decay = 1e-5.
One more thing you might want to tweak is how much regularization affect each parameter. You can set this for each parameter blob in the net via
param { decay_mult: 1 }
For example, an "InnerProduct" layer with bias has two parameters:
layer {
type: "InnerProduct"
name: "fc1"
# bottom and top here
inner_product_param {
bias_term: true
# ... other params
}
param { decay_mult: 1 } # for weights use regularization
param { decay_mult: 0 } # do not regularize the bias
}
By default, decay_mult is set to 1, that is, all weights of the net are regularized the same. You can change that to regularize more/less specific parameter blobs.
Related
Problem description:
I want to train a GRU by using a small dataset, which has 40 training samples. Length of input sequence is 3 and length of output sequence is 1. Below is the configuraions:
hidden units: 128
input size(input feature num): 11
layer: 2
drupout: 0.5
bidirectional: False
lr: 0.0001
optimizer: Adam
batch size: 8
Below is my model. Thank Azhar Khan for helping me format the code.
class GRU(nn.Module):
def __init__(self, GRU_input_num, GRU_hidden_num, GRU_layer_num, dropout, bidirectional, seed):
super(GRU, self).__init__()
torch.manual_seed(seed)
self.GRU_input_num = GRU_input_num
self.GRU_hidden_num = GRU_hidden_num
self.GRU_layer_num = GRU_layer_num
self.dropout = dropout
self.bidirectional = bidirectional
self.direction = 2 if self.bidirectional else 1
if GRU_layer_num > 1:
self.gru = nn.GRU(GRU_input_num, GRU_hidden_num, GRU_layer_num, dropout=dropout, batch_first=True,
bidirectional=bidirectional)
else:
self.gru = nn.GRU(GRU_input_num, GRU_hidden_num, GRU_layer_num, batch_first=True,
bidirectional=bidirectional)
self.predict = nn.Linear(in_features=self.GRU_hidden_num * self.direction * self.GRU_layer_num,
out_features=constants.CATEGORY_NUM * constants.BACTERIA_PER_CATEGORY)
def forward(self, x):
"""GRU forward. Input shape: [batch, input_step, features]"""
# shape of hidden state: [layer * direction, batch, hidden]
batch = x.shape[0]
_, hidden_state = self.gru(x)
hidden_state = hidden_state.permute(1, 0, 2) # [batch, layer * direction, hidden]
hidden_state = hidden_state.contiguous().view(batch, 1, self.GRU_hidden_num * self.direction * self.GRU_layer_num).squeeze(1) # [batch, layer * direction * hidden_num]
return self.predict(hidden_state), hidden_state.cpu().detach().numpy() # [batch, features]
I am curious about how will the hidden state change during training. Here are my observations.
My observations:
Heatmap of hidden state.
I printed the heatmap of hidden states every 25 epochs. x axis is sample index in one batch, y axis is hidden state dimension and the title is the sum of all hidden states. The figures are showed below
after 25 epochs
after 75 epochs
after 150 epochs
after 300 epochs
after 550 epochs
The summation keeps shrink along with training.
Weights of GRU.
I also have a glance to the weights of GRU, below is a snapshot of part of weights.
snapshot of GRU weights
Almost all the weights are end with 'e-40(or 41 etc.)', which mean every single weight close to zero.
My question:
Is this a normal phenomenon? If not, what could be the cause of this issue?
Thanks for anyone who can give me some comments about this, and do let me know what else information you need.
I am a new to caffe and I am experiencing a weird thing when I train my model. For tge same solver prototype, if I train without pre-train model, its test accuracy can increase to 0.9+, however if I finetune with a pre-train model, its accuracy fluctuate between 0.5-0.6. How can I solve the problem, making finetune model test accuracy increase up to 0.9?
Following is my command and configure file:
1 train:
./build/tools/caffe train --solver=solver_cmp.prototxt -gpu 0
2 finetune:
./build/tools/caffe train --solver=solver_cmp.prototxt --weights=pruned_sqznet.caffemodel -gpu 0
3 solver_cmp.prototxt
net: "pruned_sqznet.prototxt"
test_iter: 80
test_interval: 100
base_lr: 0.01
type: "Nesterov"
display: 40
max_iter: 100000
iter_size: 16 #global batch size = batch_size * iter_size
gamma: 0.0001
lr_policy: "poly"
power: 1.0 #linearly decrease LR
momentum: 0.9
weight_decay: 0.005
snapshot: 10000
snapshot_prefix: "examples/crowd/models/cmp_fine"
random_seed: 42
solver_mode: GPU
average_loss: 40
I use torch-caffe-binding to convert caffe model to torch. And I want to delete the loss layer in the end and add other torch layers, could I just delete the layer in the .prototxt file and "train" the model to get the .caffemodel file and import in torch?
And the model uses the lmdb type data, when I use net:forward(input) to train the model, the model just uses the data defined in the data layer instead of uses the inputdata. So how to train the model that uses the lmdb data?
the caffe model has some custom layer so I can't use the loadcaffe to load the model in torch
You have 3 issues here -
You probably need the loss layer for the training (this is what you
want to minimize). So train with it, and after the training is done
remove it from your prototxt before converting to torch.
In order to use the lmdb rather than using the data layer, connect
your input to the first conv layer (assuming your first non-input
layer is conv, e.g. say you have
layer {
name: "input-data"
type: "DummyData"
top: "data"
top: "im_info"
dummy_data_param {
shape { dim: 1 dim: 3 dim: 224 dim: 224 }
}
}
and also
input: "data"
input_shape: {
dim: 1
dim: 3
dim: 224
dim: 224
}
and then
layer {
name: "conv1"
type: "Convolution"
bottom: "data" --> **here put data instead of input-data**
top: "conv1"
convolution_param {
num_output: 96
kernel_size: 3
pad: 1
stride: 1
}
}
As for the custom layer, you'll have to find an equivalent
implementation in torch or implement it on your own
I know this may be better asked in caffe user group but I cannot access the user group and don't know where to pose the question as I'm not sure whether this needs to be raised as an issue in git. In any case, what I'm doing is this:
I have a set of grayscale images that I want to use to train a CNN using caffe. I'm using a modified version of the provided caffenet model definitions with minor modifications (ie: channel = 1 instead of 3 as I have grayscale images). So far, I used the imagenet provided mean image to train the CNN and it trained and generated results. Now I wanted to compute the image mean of my own train/test dataset and use that as the mean image so I used the file in build/tools/ to do this. It needed the images to be in lmdb so I first converted images to lmdb using convert_imageset and then used compute_mean to compute the mean. I ensured that I use --gray flag when using convert_imageset as my images are grayscale. When I rerun caffe, I get the following error. From what I can understand, it's a channel mismatch but I have no idea how to fix this. Any help on this is very much appreciated.
I0829 20:41:50.429733 17065 layer_factory.hpp:77] Creating layer data
I0829 20:41:50.429764 17065 net.cpp:100] Creating Layer data
I0829 20:41:50.429769 17065 net.cpp:408] data -> data
I0829 20:41:50.429790 17065 net.cpp:408] data -> label
I0829 20:41:50.429805 17065 data_transformer.cpp:25] Loading mean file from: data/flickr_style/train_mean.binaryproto
I0829 20:41:50.438251 17065 image_data_layer.cpp:38] Opening file data/flickr_style/train.txt
I0829 20:41:50.446666 17065 image_data_layer.cpp:58] A total of 31740 images.
I0829 20:41:50.451941 17065 image_data_layer.cpp:85] output data size: 10,3,227,227
I0829 20:41:50.459661 17065 net.cpp:150] Setting up data
I0829 20:41:50.459692 17065 net.cpp:157] Top shape: 10 3 227 227 (1545870)
I0829 20:41:50.459697 17065 net.cpp:157] Top shape: 10 (10)
I0829 20:41:50.459699 17065 net.cpp:165] Memory required for data: 6183520
I0829 20:41:50.459707 17065 layer_factory.hpp:77] Creating layer conv1
I0829 20:41:50.459728 17065 net.cpp:100] Creating Layer conv1
I0829 20:41:50.459733 17065 net.cpp:434] conv1 <- data
I0829 20:41:50.459744 17065 net.cpp:408] conv1 -> conv1
F0829 20:41:50.463794 17106 data_transformer.cpp:257] Check failed: img_channels == data_mean_.channels() (3 vs. 1)
*** Check failure stack trace: ***
# 0x7f0712106daa (unknown)
# 0x7f0712106ce4 (unknown)
# 0x7f07121066e6 (unknown)
# 0x7f0712109687 (unknown)
# 0x7f071287d6cd caffe::DataTransformer<>::Transform()
# 0x7f07127fde60 caffe::ImageDataLayer<>::load_batch()
# 0x7f0712839539 caffe::BasePrefetchingDataLayer<>::InternalThreadEntry()
# 0x7f0712886020 caffe::InternalThread::entry()
# 0x7f070a762a4a (unknown)
# 0x7f070603e184 start_thread
# 0x7f07111eb37d (unknown)
# (nil) (unknown)
I have the following in train_val.prototxt
name: "FlickrStyleCaffeNet"
layer {
name: "data"
type: "ImageData"
top: "data"
top: "label"
include {
phase: TRAIN
}
transform_param {
mirror: true
crop_size: 227
mean_file: "data/ilsvrc12/imagenet_mean.binaryproto"
}
image_data_param {
source: "data/flickr_style/mri_train.txt"
batch_size: 10
new_height: 256
new_width: 256
}
}
and this in deploy.prototxt
name: "FlickrStyleCaffeNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 10 dim: 3 dim: 227 dim: 227 } }
}
You (or the interface) have failed to adjust the input for gray scale. Gray has only 1 input channel (value); the model expects 3 channels (RGB). That 3 in the layer's top shape should be 1.
Look in your *.prototxt files for something like this near the top (input layer):
shape {
dim: 10
dim: 3
dim: 227
dim: 227
}
These dimensions are batch_size, channels, rows, and columns. Wherever you have something on this order (there should be only one, and only in input files), change the 3 to 1.
I figured out how to do this. In the train_val.prototxt, there's an image_data_param section under data layer. I had to add is_color: false in it and that fixed the issue.
Thanks everyone for comments and replies, appreciate it.
I am trying to implement a pixel-wise binary classification for images using caffe. For each image having dimension 3x256x256, I have a 256x256 label array in which each entry is marked as either 0 or 1. Also, when I read my HDF5 file using the below code,
dirname = "examples/hdf5_classification/data"
f = h5py.File(os.path.join(dirname, 'train.h5'), "r")
ks = f.keys()
data = np.array(f[ks[0]])
label = np.array(f[ks[1]])
print "Data dimension from HDF5", np.shape(data)
print "Label dimension from HDF5", np.shape(label)
I get the data and label dimension as
Data dimension from HDF5 (402, 3, 256, 256)
Label dimension from HDF5 (402, 256, 256)
I am trying to feed this data into the given hdf5 classification network and while training, I have the following output(using the default solver, but in GPU mode).
!cd /home/unni/MTPMain/caffe-master/ && ./build/tools/caffe train -solver examples/hdf5_classification/solver.prototxt
gives
I1119 01:29:02.222512 11910 caffe.cpp:184] Using GPUs 0
I1119 01:29:02.509752 11910 solver.cpp:47] Initializing solver from parameters:
train_net: "examples/hdf5_classification/train_val.prototxt"
test_net: "examples/hdf5_classification/train_val.prototxt"
test_iter: 250
test_interval: 1000
base_lr: 0.01
display: 1000
max_iter: 10000
lr_policy: "step"
gamma: 0.1
momentum: 0.9
weight_decay: 0.0005
stepsize: 5000
snapshot: 10000
snapshot_prefix: "examples/hdf5_classification/data/train"
solver_mode: GPU
device_id: 0
I1119 01:29:02.519805 11910 solver.cpp:80] Creating training net from train_net file: examples/hdf5_classification/train_val.prototxt
I1119 01:29:02.520031 11910 net.cpp:322] The NetState phase (0) differed from the phase (1) specified by a rule in layer data
I1119 01:29:02.520053 11910 net.cpp:322] The NetState phase (0) differed from the phase (1) specified by a rule in layer accuracy
I1119 01:29:02.520104 11910 net.cpp:49] Initializing net from parameters:
name: "LogisticRegressionNet"
state {
phase: TRAIN
}
layer {
name: "data"
type: "HDF5Data"
top: "data"
top: "label"
include {
phase: TRAIN
}
hdf5_data_param {
source: "examples/hdf5_classification/data/train.txt"
batch_size: 10
}
}
layer {
name: "fc1"
type: "InnerProduct"
bottom: "data"
top: "fc1"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
inner_product_param {
num_output: 2
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
value: 0
}
}
}
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "fc1"
bottom: "label"
top: "loss"
}
I1119 01:29:02.520256 11910 layer_factory.hpp:76] Creating layer data
I1119 01:29:02.520277 11910 net.cpp:106] Creating Layer data
I1119 01:29:02.520290 11910 net.cpp:411] data -> data
I1119 01:29:02.520331 11910 net.cpp:411] data -> label
I1119 01:29:02.520352 11910 hdf5_data_layer.cpp:80] Loading list of HDF5 filenames from: examples/hdf5_classification/data/train.txt
I1119 01:29:02.529341 11910 hdf5_data_layer.cpp:94] Number of HDF5 files: 1
I1119 01:29:02.542645 11910 hdf5.cpp:32] Datatype class: H5T_FLOAT
I1119 01:29:10.601307 11910 net.cpp:150] Setting up data
I1119 01:29:10.612926 11910 net.cpp:157] Top shape: 10 3 256 256 (1966080)
I1119 01:29:10.612963 11910 net.cpp:157] Top shape: 10 256 256 (655360)
I1119 01:29:10.612969 11910 net.cpp:165] Memory required for data: 10485760
I1119 01:29:10.612983 11910 layer_factory.hpp:76] Creating layer fc1
I1119 01:29:10.624948 11910 net.cpp:106] Creating Layer fc1
I1119 01:29:10.625015 11910 net.cpp:454] fc1 <- data
I1119 01:29:10.625039 11910 net.cpp:411] fc1 -> fc1
I1119 01:29:10.645814 11910 net.cpp:150] Setting up fc1
I1119 01:29:10.645864 11910 net.cpp:157] Top shape: 10 2 (20)
I1119 01:29:10.645875 11910 net.cpp:165] Memory required for data: 10485840
I1119 01:29:10.645912 11910 layer_factory.hpp:76] Creating layer loss
I1119 01:29:10.657094 11910 net.cpp:106] Creating Layer loss
I1119 01:29:10.657133 11910 net.cpp:454] loss <- fc1
I1119 01:29:10.657147 11910 net.cpp:454] loss <- label
I1119 01:29:10.657163 11910 net.cpp:411] loss -> loss
I1119 01:29:10.657189 11910 layer_factory.hpp:76] Creating layer loss
F1119 01:29:14.883095 11910 softmax_loss_layer.cpp:42] Check failed: outer_num_ * inner_num_ == bottom[1]->count() (10 vs. 655360) Number of labels must match number of predictions; e.g., if softmax axis == 1 and prediction shape is (N, C, H, W), label count (number of labels) must be N*H*W, with integer values in {0, 1, ..., C-1}.
*** Check failure stack trace: ***
# 0x7f0652e1adaa (unknown)
# 0x7f0652e1ace4 (unknown)
# 0x7f0652e1a6e6 (unknown)
# 0x7f0652e1d687 (unknown)
# 0x7f0653494219 caffe::SoftmaxWithLossLayer<>::Reshape()
# 0x7f065353f50f caffe::Net<>::Init()
# 0x7f0653541f05 caffe::Net<>::Net()
# 0x7f06535776cf caffe::Solver<>::InitTrainNet()
# 0x7f0653577beb caffe::Solver<>::Init()
# 0x7f0653578007 caffe::Solver<>::Solver()
# 0x7f06535278b3 caffe::Creator_SGDSolver<>()
# 0x410831 caffe::SolverRegistry<>::CreateSolver()
# 0x40a16b train()
# 0x406908 main
# 0x7f065232cec5 (unknown)
# 0x406e28 (unknown)
# (nil) (unknown)
Aborted
Basically the error is
softmax_loss_layer.cpp:42] Check failed:
outer_num_ * inner_num_ == bottom[1]->count() (10 vs. 655360)
Number of labels must match number of predictions;
e.g., if softmax axis == 1 and prediction shape is (N, C, H, W),
label count (number of labels) must be N*H*W,
with integer values in {0, 1, ..., C-1}.
I am not able to understand why the number of labels expected is just same as my batch size. How exactly should I tackle this problem ? Is this a problem with my labeling method ?
Your problem is that "SoftmaxWithLoss" layer tries to compare a prediction vector of 2 elements per input image to a label of size 256-by-256 per image.
This makes no sense.
Root cause of the error: I guess what you tired to do is to have a binary classifier applied to each pixel in the image. To that end you defined "fc1" as an "InnerProduct" layer with num_output=2. However, the way caffe sees this is that you have a single binary classifier applied to the entire image. Thus caffe gives you a single binary prediction to the entire image.
How to solve: when working on pixel-wise predictions you no longer need to use "InnerProduct" layers and you have a "fully convolutional net". If you replace "fc1" with a conv layer (for instance a kernel that examine the 5-by-5 environment of each pixel and makes a decision according to this patch):
layer {
name: "bin_class"
type: "Convolution"
bottom: "data"
top: "bin_class"
convolution_param {
num_output: 2 # binary class output
kernel_size: 5 # 5-by-5 patch for prediciton
pad: 2 # make sure spatial output size equals size of label
}
}
Now applying "SoftmaxWithLoss" to bottom: bin_class and bottom: label should work.