MATLAB: How to manually modify weights in a SeriesNetwork

Deep Learning Toolboxdeep neural networks

For some of my studies on deep neural nets, I need to change select weights in a (previously trained) SeriesNetwork by hand, and evaluate changes in the classification results. Ideally, I would like to do
net.Layers(k).Weights = W;
where net is a SeriesNetwork (a class in the Neural Network Toolbox), k is an integer that indexes a fully connected layer, and W is a suitable array. I would then classify inputs with the net modified in this way.
However, the field net.Layers(k).Weights is read-only, so the instruction above will generate the following error message:
You cannot set the read-only property 'Layers' of SeriesNetwork.
Is there some way to circumvent this restriction?
Here is what I tried, to no avail: First define an array of Layers by saying something like this:
layers = [imageInputLayer([28 28 1])
% Severa layers here
classificationLayer()];
then initialize the weights as desired, and finally make these layers into a SeriesNetwork with the class’s constructor:
net = SeriesNetwork(layers);
While this does create a new SeriesNetwork, attempting to classify an input with
y = classify(net, x);
where x is a suitable input results in the following error message:
Error using nnet.internal.cnn.layer.FullyConnected/forwardPropagateSize (line 99)
An input size for the layer must be defined in order to call forwardPropagateSize.
Error in SeriesNetwork>iDetermineLayerOutputSize (line 417)
inputSize = layers{i}.forwardPropagateSize(inputSize);
Error in SeriesNetwork/get.OutputSize (line 80)
val = iDetermineLayerOutputSize( internalLayers, outputLayerIdx );
Error in SeriesNetwork/predict (line 185)
Y = precision.cast( zeros([this.OutputSize dispatcher.NumObservations]) );
Error in SeriesNetwork/classify (line 250)
scores = this.predict( X, varargin{:} );
What is missing in my use of the constructor to make net a fully-fledged SeriesNetwork that can be used with classify?

Best Answer

See this Q/A .