How Can I change the read only property of "layers" of DAGNetwork?

71 次查看(过去 30 天)
I want to change the weights, bias trained mean and trained Variance of a cifar network but it gives me a error that "you cannot set the read only propoerty layers of a DAGNetwork ".
My code is
for k=1:16
net.Layers(3,1).TrainedMean(1,1,k)= ...
((net.Layers(3,1).TrainedMean(1,1,k))...
+(net1.Layers(3,1).TrainedMean(1,1,k)))./2;
end
Moreover, when I change my DAGNetwork to struct using 'saveobj' and changes the weights and bias; it changes padding size to empty matrix automatically. How can I change the read only property to set the paddingSize?
Any help would be highly appreciated.

回答(1 个)

Mahmoud Afifi
Mahmoud Afifi 2019-8-12
编辑:Mahmoud Afifi 2019-8-12
You cannot change it directly. However, you can create a new layer with the existing/new values. Then, you can replace the existing layer with this new one.
Here is an example showing how to do that. In this example, we replace the TrainedMean and TrainedVariance of an existing BatchNorm layer with zeros and ones, respectively. Then, we replace the existing batchnorm layer with the new one. Assume here that the batchnorm layer number is 43 in the network layers and its name is 'bn_conv5_3'.
>> layer = setfield(setfield( net.Layers(43) , 'TrainedMean' , zeros(1,1,512)),'TrainedVariance',ones(1,1,512));
>> newlgraph = replaceLayer(net,'bn_conv5_3',layer);
Note that the replaceLayer function is only available in Matlab 2019a or higher. I faced a problem with the replaceLayer function, but hopefully it works with you.
Here is a complete example. Assume we have net_ that have some TrainedMean and TrainedVariance values which we want to copy to net BatchNorm layers.
net= layerGraph(net); %convert to lgraph
for i = 1 : length(net.Layers)
try
L = setfield(setfield(net.Layers(i),'TrainedMean',net_.Layers(i).TrainedMean),'TrainedVariance',net_.Layers(i).TrainedVariance);
net = replaceLayer(net,net.Layers(i).Name,L);
catch
end
end
net = assembleNetwork(net);
Remember that, you have to be very cautious with that because using improperly values from another network will give catastrophic results.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by