1、修改ResNet网络
function net = resnet_single()
net = load('imagenet-resnet-50-dag.mat') ;
net = dagnn.DagNN.loadobj(net) ;
net.removeLayer('fc1000') ;
net.removeLayer('prob') ;
dropoutBlock = dagnn.DropOut('rate',0.9);
net.addLayer('dropout',dropoutBlock,{'pool5'},{'pool5d'},{});
fc8Block = dagnn.Conv('size',[1 1 2048 8],'hasBias',true,'stride',[1,1],'pad',[0,0,0,0]);
net.addLayer('fc8',fc8Block,{'pool5d'},{'prediction'},{'fc8f','fc8b'});
lossBlock = dagnn.Loss('loss', 'softmaxlog');
net.addLayer('softmaxloss',lossBlock,{'prediction','label'},'objective');
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ... {'prediction','label'}, 'top1err') ;
2、构建Siamese网络
net1 = resnet_single();
net1 = net1.saveobj() ;
net2 = net1;
for i = 1 : length(net2.layers);
net2.layers(i).name = strcat(net2.layers(i).name,'_2');
for j = 1 : length(net2.layers(i).inputs);
net2.layers(i).inputs{j} = strcat(net2.layers(i).inputs{j},'_2');
end;
for j = 1 : length(net2.layers(i).outputs);
net2.layers(i).outputs{j} = strcat(net2.layers(i).outputs{j},'_2');
end;
end;
for i = 1 : length(net2.vars);
net2.vars(i).name = strcat(net2.vars(i).name,'_2');
end;
net1.vars = [net1.vars,net2.vars];
net1.layers = [net1.layers,net2.layers];
net = dagnn.DagNN.loadobj(net1) ;
net.addLayer('SiameseLoss',dagnn.SiameseLoss(), {'pool5','pool5_2'}, {'objective_s'});
3、构建TripletLoss网络
net1 = resnet_single();
net1 = net1.saveobj() ;
net2 = net1;
for i = 1 : length(net2.layers);
net2.layers(i).name = strcat(net2.layers(i).name,'_2');
for j = 1 : length(net2.layers(i).inputs);
net2.layers(i).inputs{j} = strcat(net2.layers(i).inputs{j},'_2');
end;
for j = 1 : length(net2.layers(i).outputs);
net2.layers(i).outputs{j} = strcat(net2.layers(i).outputs{j},'_2');
end;
end;
for i = 1 : length(net2.vars);
net2.vars(i).name = strcat(net2.vars(i).name,'_2');
end;
net3 = net1;
for i = 1 : length(net3.layers);
net3.layers(i).name = strcat(net3.layers(i).name,'_3');
for j = 1 : length(net3.layers(i).inputs);
net3.layers(i).inputs{j} = strcat(net3.layers(i).inputs{j},'_3');
end;
for j = 1 : length(net3.layers(i).outputs);
net3.layers(i).outputs{j} = strcat(net3.layers(i).outputs{j},'_3');
end;
end;
for i = 1 : length(net3.vars);
net3.vars(i).name = strcat(net3.vars(i).name,'_3');
end;
net1.vars = [net1.vars,net2.vars,net3.vars];
net1.layers = [net1.layers,net2.layers,net3.layers];
net = dagnn.DagNN.loadobj(net1) ;
net.addLayer('TripletLoss',dagnn.TripletLoss('margin',0.1),{'pool5','pool5_2','pool5_3'},{'objective_triplet'});