%% Create 2-D Upsampling Layer Using Tranposed 2-D Convolution
% Create an upsampling layer, frequently used in semantic segmentation networks.
%
%% Create Transposed 2-D Convolution Layer
% Set the transposed convolution layer parameters. The filter size and amount of cropping to apply are selected such that the output feature map width and height equals the input feature map width and height times the selected factor. For example, if the input width and height is 4, the output width and height is 12 for an upsampling factor of 3. Note that the number of filter and channels used in the layer depend on the network architecture the layer is used in.

factor = 3;
filterSize = 2*factor - mod(factor,2);
cropping = (factor-mod(factor,2))/2;
numFilters = 1;
numChannels = 1;

upsample = transposedConv2dLayer(filterSize,numFilters, ...
    'NumChannels',numChannels,'Stride',factor,'Cropping',cropping)

%
%% Bilinear Weight Initialization
% Calculate bilinear interpolation coefficients and use them to initialize the layer weights. In addition, initialize the bias to zero. These weights and bias values enable the transposed convolution layer to act as a 2-D upsampling layer that you can use to resize input feature maps.

center = filterSize/2 + 0.5;
dist = abs(center - (1:filterSize));
w = dist/(filterSize/2);
w = 1 - w;
bilinearWeights = w' * w;

upsample.Weights = repmat(bilinearWeights,1,1,numFilters,numChannels);
upsample.Bias = zeros(1,1,numFilters);

%
%% Freeze Weights and Bias
% Freeze the weights and bias to prevent the layer weights and bias from changing during training. Freezing them lets the transposed convolution layer act as a pure upsampling layer.

upsample.WeightLearnRateFactor = 0;
upsample.BiasLearnRateFactor = 0;

% Copyright 2012 The MathWorks, Inc.