Refine ANN result precision - matlab

I've a neural network in MATLAB that works well, but it should give me a result of 0 or 1, and it gets +/-0.05 error. (0.02, 0.97, 1.03, ...)
What should I change for the result to be more accurate?
p = [ 0 0 1 1; 0 1 0 1];
t = [0 1 1 0];
net = feedforwardnet(2,'trainlm');
net.trainParam.goal = 0.01*var(t',1);
net.divideFcn = 'dividetrain';
[net,tr] = train(net,p,t);
a = net(p)

Related

How to list all results of probability experiment in Matlab [duplicate]

I am writing a function in Matlab to model the length of stay in hospital of stroke patients. I am having difficulty in storing my output values.
Here is my function:
function [] = losdf(age, strokeType, dest)
% function to mdetermine length of stay in hospitaal of stroke patients
% t = time since admission (days);
% age = age of patient;
% strokeType = 1. Haemorhagic, 2. Cerebral Infarction, 3. TIA;
% dest = 5.Death 6.Nursing Home 7. Usual Residence;
alpha1 = 6.63570;
beta1 = -0.03652;
alpha2 = -3.06931;
beta2 = 0.07153;
theta0 = -8.66118;
theta1 = 0.08801;
mu1 = 22.10156;
mu2 = 2.48820;
mu3 = 1.56162;
mu4 = 0;
nu1 = 0;
nu2 = 0;
nu3 = 1.27849;
nu4 = 0;
rho1 = 0;
rho2 = 11.76860;
rho3 = 3.41989;
rho4 = 63.92514;
for t = 1:1:365
p = (exp(-exp(theta0 + (theta1.*age))));
if strokeType == 1
initialstatevec = [1 0 0 0 0 0 0];
elseif strokeType == 2
initialstatevec = [0 1 0 0 0 0 0];
else
initialstatevec = [0 0 (1-p) p 0 0 0];
end
lambda1 = exp(alpha1 + (beta1.*age));
lambda2 = exp(alpha2 + (beta2.*age));
Q = [ -(lambda1+mu1+nu1+rho1) lambda1 0 0 mu1 nu1 rho1;
0 -(lambda2+mu2+nu2+rho2) lambda2 0 mu2 nu2 rho2;
0 0 -(mu3+nu3+rho3) 0 mu3 nu3 rho3;
0 0 0 -(mu4+nu4+rho4) mu4 nu4 rho4;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0];
Pt = expm(t./365.*Q);
Pt = Pt(strokeType, dest);
Ft = sum(initialstatevec.*Pt);
Ft
end
end
Then to run my function I use:
losdf(75,3,7)
I want to plot my values of Ft in a graph from from 0 to 365 days. What is the best way to do this?
Do I need to store the values in an array first and if so what is the best way to do this?
Many ways to do this, one straightforward way is to save each data point to a vector while in the loop and plot that vector after you exit your loop.
...
Ft = zeros(365,1); % Preallocate Ft as a vector of 365 zeros
for t = 1:365
...
Ft(t) = sum(initialstatevec.*Pt); % At index "t", store your output
...
end
plot(1:365,Ft);

MATLAB Yalmip: unable to run optimizer; error in eliminatevariables

Bottomline:
Matlab throws the errors below and it is not obvious to me what is the root cause. The problem seems to reside in the input arguments, but I cannot figure out exactly what it is. I would greatly appreciate any help in finding it.
Index exceeds matrix dimensions.
Error in eliminatevariables (line 42)
aux(model.precalc.index2) = value(model.precalc.jj2);
Error in optimizer/subsref (line 276)
[self.model,keptvariablesIndex] =
eliminatevariables(self.model,self.model.parameterIndex,thisData(:),self.model.parameterIndex);
Error in SCMv0_justrun (line 68)
[solutions,diagnostics] = controller{inputs};
Background:
I am trying to program a Model Predictive Control but I am not very familiar yet with either Yalmip or mathematical optimization algorithms. I have made sure that the defined inputs and the actual inputs have the same dimensions, hence why I am surprised that the error has to do with matrix dimensions.
The error originates in when my code calls the optimizer.
My code is based on: https://yalmip.github.io/example/standardmpc/
Here is my code (the first part of the code is only needed to define the optimization problem and is marked between "%%%%%"; the error occurs near the end):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yalmip('clear')
clear all
% Model data
A = eye(3);
B = [1 0 -1 0 0 0 0; 0 1 0 -1 0 0 0; 0 0 0 0 1 -1 -1];
nx = 3; % Number of states
nu = 7; % Number of inputs
% MPC data
Q = [10 10 20]';
R = [10 10 1 1 5 3 3]';
C = [50 0; 0 30];
N = 90;
ny = 2;
E = [0 0 0 0 0 1 0; 0 0 0 0 0 0 1];
u = sdpvar(repmat(nu,1,N),repmat(1,1,N));
x = sdpvar(repmat(nx,1,N+1),repmat(1,1,N+1));
r = sdpvar(repmat(ny,1,N+1),repmat(1,1,N+1));
d = sdpvar(ny,1);
pastu = sdpvar(nu,1);
dx = 0.05;
Gx=[-1*eye(3);eye(3)];
gx = [0 0 0 500 500 1000]';
COVd = [zeros(5,7);0 0 0 0 0 10 0; 0 0 0 0 0 0 10];
COVx = zeros(nx,nx);
auxa = eye(5);
auxb = zeros(5,2);
Gu = [-1*eye(7,7); auxa auxb;0 0 0 0 0 1 1];
gu = [zeros(7,1); 200; 200; 50; 50; 100; 500];
Ga = [0 0 0.5 0.5 -1 0 0];
constraints = [];
objective = 0;
for k = 1:N
r{k} = r{k} + d;
objective = objective + Q'*x{k} + R'*u{k} + (r{k}-E*u{k})'*C*(r{k}-E*u{k});
constraints = [constraints, x{k+1} == A*x{k}+B*u{k}];
COVx = A*COVx*A' + B*COVd*B';
COVGx = Gx*COVx*Gx';
StDevGx = sqrt(diag(COVGx));
chance = gx - norminv(1-dx/(length (gx)*N))*StDevGx;
constraints = [constraints, Ga*u{k}==0, Gu*u{k}<=gu, Gx*x{k}<=gx-chance];
end
objective = objective + Q'*x{N+1};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
parameters_in = {x{1},[r{:}],d,pastu};
solutions_out = {[u{:}], [x{:}]};
controller = optimizer(constraints, objective,[],parameters_in,solutions_out);
x = 100*ones(nx,1);
clf;
disturbance = randn(ny,1)*10;
oldu = zeros(nu,1);
hold on
for i = 1:150
future_r = [4*sin((i:i+N)/40);3*sin((i:i+N)/20)];% match dimensions of r
inputs = {x,future_r,disturbance,oldu};
[solutions,diagnostics] = controller{inputs};
U = solutions{1};oldu = U(1);
X = solutions{2};
if diagnostics == 1
error('The problem is infeasible');
end
x = A*x+B*u;
end
It's a bug in the latest version of YALMIP.

How to use train in neural networks for Matlab R2009b

I have input matrix as:
input =
1 0 0 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
0 0 1 0 0
0 1 1 1 0
0 1 1 1 0
and
T = [eye(10) eye(10) eye(10) eye(10)];
The neural network that I created is:
net = newff(input,T,[35], {'logsig'})
%net.performFcn = 'sse';
net.divideParam.trainRatio = 1; % training set [%]
net.divideParam.valRatio = 0; % validation set [%]
net.divideParam.testRatio = 0; % test set [%]
net.trainParam.goal = 0.001;
It works fine till now, but when i use train function the problem arises
[net tr] = train(net,input,T);
and the following error show up in matlab window:
??? Error using ==> network.train at 145
Targets are incorrectly sized for network.
Matrix must have 5 columns.
Error in ==> test at 103
[net tr] = train(net,input,T);
I've also tried the input' and T' as well. Any help is appreciated in advance
If you look at MATLAB's official documentaion of train, you'll notice that T must have the same amount of columns as the input matrix, which is 5 in your case. Instead, try:
T = ones(size(input, 1));
or
T = [1, size(input, 1) - 1];
and see if this works.

matrix dimensions matlab

I Have my function below, the idea being that X is a 3x3 extract from T to be used in the loop, it correctly extracts the 3 rows but for some reason produces far too many columns, see example below.
function T = tempsim(rows, cols, topNsideTemp, bottomTemp, tol)
T = zeros(rows,cols);
T(1,:) = topNsideTemp;
T(:,1) = topNsideTemp;
T(:,rows) = topNsideTemp;
T(rows,:) = bottomTemp;
S = [0 1 0; 1 1 1; 0 1 0];
X = zeros(3,3);
A = zeros(3,3);
for ii = 2:(cols-1);
jj = 2:(rows-1);
X = T([(ii-1) ii (ii+1)], [(jj-1) jj (jj+1)])
A = X.*S;
T = (sum(sum(A)))/5
end
test sample
EDU>> T = tempsim(5,4,100,50,0)
X =
100 100 100 100 100 100 100 100 100
100 0 0 0 0 0 0 0 100
100 0 0 0 0 0 0 0 100
ans =
100 100 100 100 100 100 100 100 100
100 0 0 0 0 0 0 0 100
100 0 0 0 0 0 0 0 100
??? Error using ==> times
Matrix dimensions must agree.
Error in ==> tempsim at 14
A = X.*S;
any thoughts on how to fix this?
There's no need to preallocate X and A if you do a complete assignment anyway. Then, you replace T with a scalar inside the loop, which makes you run into problems in the next iteration. What I'm guessing you want could look something like this:
function T = tempsim(rows, cols, topNsideTemp, bottomTemp, tol)
T = zeros(rows,cols);
T(1,:) = topNsideTemp;
T(:,1) = topNsideTemp;
T(:,rows) = topNsideTemp;
T(rows,:) = bottomTemp;
S = [0 1 0; 1 1 1; 0 1 0];
for ii = 1:(cols-2);
for jj = 1:(rows-2);
X = T(ii:ii+2, jj:jj+2);
A = X.*S;
T(ii,jj) = (sum(sum(A)))/5;
end
end
Although I'm not sure if you really mean to do that – you're working on T while modifying it. As a wild guess, I suspect you might be looking for something like
conv2(T, S/5, 'same')
instead, perhaps after making your fixed-temp borders twice as thick and re-setting them after the call (since conv2 does zero-padding at the outer borders).
Here:
jj = 2:(rows-1);
X = T([(ii-1) ii (ii+1)], [(jj-1) jj (jj+1)])
jj becomes [2 3 4]
so X is
T([1 2 3], [ [2 3 4]-1 [2 3 4] [2 3 4]+1 ])
You probably missed a for loop.

MATLAB neural networks

I'm using a simple XOR input and output data set in order to train a neural network before attempting anything harder but for some reason it won't work.
may someone please explain what I am doing wrong please?
This is my code:
%user specified values
hidden_neurons = 3;
epochs = 10000;
t_input = [1 1; 1 0; 0 1; 0 0];
t_output = [1; 0; 0; 1];
te_input = [1 1; 1 0; 0 1; 0 0];
net = newff(t_input, t_output, 1);
net = init(net);
net = train(net, t_input, t_output);
net.trainParam.show = 50;
net.trainParam.lr = 0.25;
net.trainParam.epochs = epochs;
net.trainParam.goal = 1e-5;
net = train(net, t_input, t_output);
out = sim(net, te_input);
THis is my error message:
??? Error using ==> network.train at 145 Targets are incorrectly sized for
network. Matrix must have 2 columns.
Error in ==> smallNN at 11 net =
train(net, t_input, t_output);
You must have your samples on columns and not rows (like all the NN software in the world do), so change the data sets creation lines in:
t_input = [1 1; 1 0; 0 1; 0 0]';
t_output = [1; 0; 0; 1]';
te_input = [1 1; 1 0; 0 1; 0 0]';
Now it works.