I am implementing CGAN in https://www.mathworks.com/help/deeplearning/ug/train-conditional-generative-adversarial-network.html
and when i run it i am getting this error: Undefined function or variable 'projectAndReshapeLayer'
I searched and found out that i need to make a file called projectAndReshapeLayer.m and i got the code from matalb site and made it but when i am running it i get this error:
Abstract classes cannot be instantiated. Class 'projectAndReshapeLayer' inherits abstract methods or properties but does not implement
them. See the list of methods and properties that 'projectAndReshapeLayer' must implement if you do not intend the class to be abstract.
when i click "See the list of methods and properties" I get:
Abstract methods for class projectAndReshapeLayer:
backward % defined in nnet.layer.Layer
when i searched i understood that i need a backward function in the projectAndReshapeLayer.m code that I added but I cant find it can anyone help?
this is the projectAndReshapeLayer.m file:
classdef projectAndReshapeLayer < nnet.layer.Layer
properties
% (Optional) Layer properties.
OutputSize
end
properties (Learnable)
% Layer learnable parameters.
Weights
Bias
end
methods
function layer = projectAndReshapeLayer(outputSize, numChannels, name)
% Create a projectAndReshapeLayer.
% Set layer name.
layer.Name = name;
% Set layer description.
layer.Description = "Project and reshape layer with output size " + join(string(outputSize));
% Set layer type.
layer.Type = "Project and Reshape";
% Set output size.
layer.OutputSize = outputSize;
% Initialize fully connect weights and bias.
fcSize = prod(outputSize);
layer.Weights = initializeGlorot(fcSize, numChannels);
layer.Bias = zeros(fcSize, 1, 'single');
end
function Z = predict(layer, X)
% Forward input data through the layer at prediction time and
% output the result.
%
% Inputs:
% layer - Layer to forward propagate through
% X - Input data, specified as a 1-by-1-by-C-by-N
% dlarray, where N is the mini-batch size.
% Outputs:
% Z - Output of layer forward function returned as
% an sz(1)-by-sz(2)-by-sz(3)-by-N dlarray,
% where sz is the layer output size and N is
% the mini-batch size.
% Fully connect.
weights = layer.Weights;
bias = layer.Bias;
X = fullyconnect(X,weights,bias,'DataFormat','SSCB');
% Reshape.
outputSize = layer.OutputSize;
Z = reshape(X, outputSize(1), outputSize(2), outputSize(3), []);
end
end
end
function weights = initializeGlorot(numOut, numIn)
% Initialize weights using uniform Glorot.
varWeights = sqrt( 6 / (numIn + numOut) );
weights = varWeights * (2 * rand([numOut, numIn], 'single') - 1);
end
Related
I am using the input parser functionality a lot but now I am facing the following issue:
I am coding an object that computes the rate-of-change of time series, i.e. one input argument is a matrix of doubles (timeSeries). A second input parameter is the time period used to compute the rate-of-change (lag). lag can be a vector wherby different rate-of-changes will be computed. A third input vector is called weightVector. weightVector will be used to compute an average of all rate-of-changes and applies the appropriate weights to the respective rate-of-change results.
Now, I always like to define some default values when using input parser. I would like to define weightVector to be an equal weighted vector. However, the length of the default weightVector is dependent on the length of lag. For example, if lag = [1,2,3], then weightVectorshould equal [1/3, 1/3, 1/3]. How am I supposed to code a situation like this? My current code for the constructor looks like this:
function obj = roc(timeSeries, varargin)
%% Input parser
% 1. Create input parser instance
p = inputParser;
% 2. Default values for input arguments
default_lag = 1;
default_weightVector = 1/length(lag); % This line is causing
% problems as LAG isn't
% defined, yet.
% 3. Validation of input arguments
valid_lag = {'vector', 'nonempty', 'integer', 'positive'};
check_lag = #(x) validateattributes(x, {'numeric'}, valid_lag);
valid_weightVector = {'vector', 'nonempty'};
check_weightVector = #(x) validateattributes(x, {'numeric'}, ...
valid_weightVector);
% 4. Add input arguments to input scheme
p.addRequired('timeSeries');
p.addParamater('lag', default_lag, check_lag);
p.addParameter('weightVector', default_weightVector, check_weightVector);
% 5. Parse input arguments
parse(p, timeSeries, varargin{:});
% 6. Assign results to variables
lag = p.Results.lag;
weightVector = p.Results.weightVector;
%% Main code
end % Constructor
function obj = roc(timeSeries, varargin)
%% Input parser
% 1. Create input parser instance
p = inputParser;
% 2. Default values for input arguments
default_lag = 1;
default_weightVector = 1;
% 3. Validation of input arguments
valid_lag = {'vector', 'nonempty', 'integer', 'positive'};
check_lag = #(x) validateattributes(x, {'numeric'}, valid_lag);
% 4. Add input arguments to input scheme
p.addRequired('timeSeries');
p.addParameter('lag', default_lag, check_lag);
p.addParameter('weightVector', default_weightVector);
% 5. Parse input arguments
parse(p, timeSeries, varargin{:});
% 6. Assign results to variables
lag = p.Results.lag;
if check_weightVector(p.Results.weightVector, lag) == true
weightVector = p.Results.weightVector;
end
function vout = check_weightVector(weightVector, lag) % validation function
if length(lag) ~= length(weightVector)
error('lengthWeightVector:WrongNumberOfElements', 'The number of elements in "weightVector" must correspond to the number of elements in "lag"');
elseif sum(weightVector) ~= 1
error('sumWeightVector:SumNotEqualToOne', 'The sum of elements in "weightVector" must equal 1');
end
vout = true;
end
%% Main code
end
I have a very simple question, but I didn't figure out how to solve this.I have the function definition below:
function model = oasis(data, class_labels, parms)
% model = oasis(data, class_labels, parms)
%
% Code version 1.3 May 2011 Fixed random seed setting
% Code version 1.2 May 2011 added call to oasis_m.m
% Code version 1.1 May 2011 handle gaps in class_labels
%
% Input:
% -- data - Nxd sparse matrix (each instance being a ROW)
% -- class_labels - label of each data point (Nx1 integer vector)
% -- parms (do sym, do_psd, aggress etc.)
%
% Output:
% -- model.W - dxd matrix
% -- model.loss_steps - a binary vector: was there an update at
% each iterations
% -- modeo.parms, the actual parameters used in the run (inc. defaults)
%
% Parameters:
% -- aggress: The cutoff point on the size of the correction
% (default 0.1)
% -- rseed: The random seed for data point selection
% (default 1)
% -- do_sym: Whether to symmetrize the matrix every k steps
% (default 0)
% -- do_psd: Whether to PSD the matrix every k steps, including
% symmetrizing them (defalut 0)
% -- do_save: Whether to save the intermediate matrices. Note that
% saving is before symmetrizing and/or PSD in case they exist
% (default 0)
% -- save_path: In case do_save==1 a filename is needed, the
% format is save_path/part_k.mat
% -- num_steps - Number of total steps the algorithm will
% run (default 1M steps)
% -- save_every: Number of steps between each save point
% (default num_steps/10)
% -- sym_every: An integer multiple of "save_every",
% indicates the frequency of symmetrizing in case do_sym=1. The
% end step will also be symmetrized. (default 1)
% -- psd_every: An integer multiple of "save_every",
% indicates the frequency of projecting on PSD cone in case
% do_psd=1. The end step will also be PSD. (default 1)
% -- use_matlab: Use oasis_m.m instead of oasis_c.c
% This is provided in the case of compilation problems.
%
I want to use this function, but I don't figure how to set the parameters, or use the default values. What is the variable parms in this case, it is an object that keep all the other variables? Can I make something python like syntax where we put the name of the parameter plus value? For example:
model = oasis(data_example, labels_example, agress = 0.2)
Additionally, If I have understood correctly, I get two Objects in the Output, which is model and modeo, so I need to make this call to receive all contents this function returns?
[model,modeo] = oasis(data_example, labels_example, ?(parms)?)
From your function definition it seems like params is simply a placeholder for the parameters. Typically the parameters themselves are passed as pairs of inputs in the form:
model = oasis(data, class_labels, 'do_sym',do_symValue, 'do_psd', do_psdValue,...)
where do_symValue and do_psdValue are the values you want to pass as the respective parameters.
As for the functions return value, it returns a single struct with members W, loss_steps, and parms. I believe that what you thought as a second output (modelo) is simply a typo in the text - at least based on the function's definition.
From the documentation above, I don't know which one is the right, but there are two common ways for optional parameters in matlab.
parameter value pairs:
model = oasis(data, class_labels, 'do_sym',1,'do_psd',0)
structs:
params.do_sym=1
params.do_psd=0
model = oasis(data, class_labels, params)
Probably one of these two possibilities is right.
So I have these two made up .m files. This is an example of the problem I'm having and the math is pseudo-math
rectangle.m:
function [vol, surfArea] = rectangle(side1, side2, side3)
vol = ...;
surfArea = ...;
end
ratio.m:
function r = ratio(f,constant)
% r should return a scaled value of the volume to surface area ratio
% based on the constant provided.
% This line doesn't work but shows what I'm intending to do.
[vol,surfArea] = f
r = constant*vol*surfArea;
end
What I'm unsure how to do is pass the rectangle function as f and then access vol and surfArea from within the ratio function. I've read and the Mathworks page on function handles and function functions and have come up empty handed on figuring out how to do this. I'm new to MATLAB so that doesn't help either.
Let me know if you need anymore info.
Thanks!
The correct way of passing the function rectangle as and argument of ratio is
r = ratio( #recangle, constant )
You can then call [vol,surfArea] = f(s1,s2,s3) from within ratio, but it requires the sideX arguments to be known.
If ratio should not require to know these arguments, then you could create an object function and pass this as a reference argument. Or better, you could create a rectangle class altogether:
classdef Rectangle < handle
properties
side1, side2, side3;
end
methods
% Constructor
function self = Rectangle(s1,s2,s3)
if nargin == 3
self.set_sides(s1,s2,s3);
end
end
% Set sides in one call
function set_sides(self,s1,s2,s3)
self.side1 = s1;
self.side2 = s2;
self.side3 = s3;
end
function v = volume(self)
% compute volume
end
function s = surface_area(self)
% compute surface area
end
function r = ratio(self)
r = self.volume() / self.surface_area();
end
function r = scaled_ratio(self,constant)
r = constant * self.ratio();
end
end
end
While I didn't bring this up in my question above, this is what I was searching for.
So what I wanted to do was pass some of rectangles arguments to ratio while being able to manipulate any chosen number of rectangles arguments from within the ratio function. Given my .m files that above, a third .m would look something like this. This solution ended up using MATLAB's anonymous functions.
CalcRatio.m:
function cr = calcRatio(length)
% Calculates different volume to surface area ratios given
% given different lengths of side2 of the rectangle.
cr = ratio(#(x) rectangle(4,x,7); %<-- allows the 2nd argument to be
% manipulated by ratio function
end
ratio.m:
function r = ratio(f,constant)
% r should return a scaled value of the volume to surface area ratio
% based on the constant provided.
% Uses constant as length for side2 -
% again, math doesnt make any sense, just showing what I wanted to do.
[vol,surfArea] = f(constant);
r = constant*vol*surfArea;
end
I'm new to Matlab.
I'm trying to apply PCA function(URL listed below)into my palm print recognition program to generate the eigenpalms. My palm print grey scale images dimension are 450*400.
Before using it, I was trying to study these codes and add some codes to save the eigenvector as .mat file. Some of the %comments added by me for my self understanding.
After a few days of studying, I still unable to get the answers.
I decided to ask for helps.I have a few questions to ask regarding this PCA.m.
PCA.m
What is the input of the "options" should be? of "PCA(data,details,options)"
(is it an integer for reduced dimension? I was trying to figure out where is the "options" value passing, but still unable to get the ans. The msgbox of "h & h2", is to check the codes run until where. I was trying to use integer of 10, but the PCA.m processed dimension are 400*400.)
The "eigvector" that I save as ".mat" file is ready to perform Euclidean distance classifier with other eigenvector? (I'm thinking that eigvector is equal to eigenpalm, like in face recognition, the eigen faces. I was trying to convert the eigenvector matrix back to image, but the image after PCA process is in Black and many dots on it)
mySVD.m
In this function, there are two values that can be changed, which are MAX_MATRIX_SIZE set by 1600 and EIGVECTOR_RATIO set by 0.1%. May I know these values will affect the results? ( I was trying to play around with the values, but I cant see the different. My palm print image dimension is set by 450*400, so the Max_matrix_size should set at 180,000?)
** I hope you guys able to understand what I'm asking, please help, Thanks guys (=
Original Version : http://www.cad.zju.edu.cn/home/dengcai/Data/code/PCA.m
mySVD: http://www.cad.zju.edu.cn/home/dengcai/Data/code/mySVD.m
% Edited Version by me
function [eigvector, eigvalue] = PCA(data,details,options)
%PCA Principal Component Analysis
%
% Usage:
% [eigvector, eigvalue] = PCA(data, options)
% [eigvector, eigvalue] = PCA(data)
%
% Input:
% data - Data matrix. Each row vector of fea is a data point.
% fea = finite element analysis ?????
% options.ReducedDim - The dimensionality of the reduced subspace. If 0,
% all the dimensions will be kept.
% Default is 0.
%
% Output:
% eigvector - Each column is an embedding function, for a new
% data point (row vector) x, y = x*eigvector
% will be the embedding result of x.
% eigvalue - The sorted eigvalue of PCA eigen-problem.
%
% Examples:
% fea = rand(7,10);
% options=[]; %store an empty matrix in options
% options.ReducedDim=4;
% [eigvector,eigvalue] = PCA(fea,4);
% Y = fea*eigvector;
%
% version 3.0 --Dec/2011
% version 2.2 --Feb/2009
% version 2.1 --June/2007
% version 2.0 --May/2007
% version 1.1 --Feb/2006
% version 1.0 --April/2004
%
% Written by Deng Cai (dengcai AT gmail.com)
%
if (~exist('options','var'))
%A = exist('name','kind')
% var = Checks only for variables.
%http://www.mathworks.com/help/matlab/matlab_prog/symbol-reference.html#bsv2dx9-1
%The tilde "~" character is used in comparing arrays for unequal values,
%finding the logical NOT of an array,
%and as a placeholder for an input or output argument you want to omit from a function call.
options = [];
end
h2 = msgbox('not yet');
ReducedDim = 0;
if isfield(options,'ReducedDim')
%tf = isfield(S, 'fieldname')
h2 = msgbox('checked');
ReducedDim = options.ReducedDim;
end
[nSmp,nFea] = size(data);
if (ReducedDim > nFea) || (ReducedDim <=0)
ReducedDim = nFea;
end
if issparse(data)
data = full(data);
end
sampleMean = mean(data,1);
data = (data - repmat(sampleMean,nSmp,1));
[eigvector, eigvalue] = mySVD(data',ReducedDim);
eigvalue = full(diag(eigvalue)).^2;
if isfield(options,'PCARatio')
sumEig = sum(eigvalue);
sumEig = sumEig*options.PCARatio;
sumNow = 0;
for idx = 1:length(eigvalue)
sumNow = sumNow + eigvalue(idx);
if sumNow >= sumEig
break;
end
end
eigvector = eigvector(:,1:idx);
end
%dt get from C# program, user ID and name
evFolder = 'ev\';
userIDName = details; %get ID and Name
userIDNameWE = strcat(userIDName,'\');%get ID and Name with extension
filePath = fullfile('C:\Users\***\Desktop\Data Collection\');
userIDNameFolder = strcat(filePath,userIDNameWE); %ID and Name folder
userIDNameEVFolder = strcat(userIDNameFolder,evFolder);%EV folder in ID and Name Folder
userIDNameEVFile = strcat(userIDNameEVFolder,userIDName); % EV file with ID and Name
if ~exist(userIDNameEVFolder, 'dir')
mkdir(userIDNameEVFolder);
end
newFile = strcat(userIDNameEVFile,'_1');
searchMat = strcat(newFile,'.mat');
if exist(searchMat, 'file')
filePattern = strcat(userIDNameEVFile,'_');
D = dir([userIDNameEVFolder, '*.mat']);
Num = length(D(not([D.isdir])))
Num=Num+1;
fileName = [filePattern,num2str(Num)];
save(fileName,'eigvector');
else
newFile = strcat(userIDNameEVFile,'_1');
save(newFile,'eigvector');
end
You pass options in a structure, for instance:
options.ReducedDim = 2;
or
options.PCARatio =0.4;
The option ReducedDim selects the number of dimensions you want to use to represent the final projection of the original matrix. For instance if you pick option.ReducedDim = 2 you use only the two eigenvectors with largest eigenvalues (the two principal components) to represent your data (in effect the PCA will return the two eigenvectors with largest eigenvalues).
PCARatio instead allows you to pick the number of dimensions as the first eigenvectors with largest eigenvalues that account for fraction PCARatio of the total sum of eigenvalues.
In mySVD.m, I would not increase the default values unless you expect more than 1600 eigenvectors to be necessary to describe your dataset. I think you can safely leave the default values.
I want to write a block, which sends all image files from selected directory.
Images are of different sizes, so output signal size should vary.
Unfortunately I was unable to find a way to change signal size at each step. There are many of undocumented features here, in examples like
block.OutputPort(1).DimensionsMode = 'Variable';
and
block.OutputPort(1).CurrentDimensions = [1 block.InputPort(1).Data];
and so on. I was unable to deduce correct way to operate all this stuff yet...
UPDATE
For example, this S-function
function Test_SF_01(block)
% Level-2 MATLAB file S-Function.
setup(block);
function setup(block)
% Register number of ports and parameters
block.NumInputPorts = 0;
block.NumOutputPorts = 1;
block.NumDialogPrms = 0;
% Setup functional port properties to dynamically inherited
block.SetPreCompOutPortInfoToDynamic;
% Register the properties of the output port
block.OutputPort(1).DimensionsMode = 'Variable';
block.OutputPort(1).SamplingMode = 'Sample';
% Register sample times
% [-1, 0] : Inherited sample time
block.SampleTimes = [-1 0];
% Register methods called at run-time
block.RegBlockMethod('Outputs', #Outputs);
function Outputs(block)
block.OutputPort(1).CurrentDimensions = floor(rand(1,2)*10)+1;
causes an error
Invalid variable dimensions assignment for output port 1 of
'Test_01/Level-2 MATLAB S-Function'. The number of variable dimensions
is 1. However, the length of the MATLAB array is 2
why?
The following S-function generates variable dimension signal. They key problem was that initial set of Dimensions property defines MAXIMAL values of dimensions, which is absolutely not clear from docs, while error messages are mostly irrelevant.
function Test_SF_01(block)
% Level-2 MATLAB file S-Function.
setup(block);
function setup(block)
% Register number of ports and parameters
block.NumInputPorts = 0;
block.NumOutputPorts = 1;
block.NumDialogPrms = 0;
% Setup functional port properties to dynamically inherited
block.SetPreCompOutPortInfoToDynamic;
% Register the properties of the output port
block.OutputPort(1).DimensionsMode = 'Variable';
block.OutputPort(1).Dimensions = [10000 10000];
block.OutputPort(1).SamplingMode = 'Sample';
% Register sample times
% [-1, 0] : Inherited sample time
block.SampleTimes = [-1 0];
% Register methods called at run-time
block.RegBlockMethod('Outputs', #Outputs);
function Outputs(block)
dims = floor(rand(1,2)*10)+1;
block.OutputPort(1).CurrentDimensions = dims;
data = rand(dims);
block.OutputPort(1).Data = data;
Have you also looked at the following code example from the doc? See Operations for Variable-Size Signals. There's a bit more in there than what you have in your code. Probably best to start from the basic template msfuntmpl_basic.m as they do in the doc.
function setup(block)
% Register the properties of the output port
block.OutputPort(1).DimensionsMode = 'Variable';
block.RegBlockMethod('SetInputPortDimensionsMode', #SetInputDimsMode);
function DoPostPropSetup(block)
%Register dependency rules to update current output size of output port a depending on
%input ports b and c
block.AddOutputDimsDependencyRules(a, [b c], #setOutputVarDims);
%Configure output port b to have the same dimensions as input port a
block.InputPortSameDimsAsOutputPort(a,b);
%Configure DWork a to have its size reset when input size changes.
block.DWorkRequireResetForSignalSize(a,true);
function SetInputDimsMode(block, port, dm)
% Set dimension mode
block.InputPort(port).DimensionsMode = dm;
block.OutputPort(port).DimensionsMode = dm;
function setOutputVarDims(block, opIdx, inputIdx)
% Set current (run-time) dimensions of the output
outDimsAfterReset = block.InputPort(inputIdx(1)).CurrentDimensions;
block.OutputPort(opIdx).CurrentDimensions = outDimsAfterReset;