octave nmf_bpas error: vertical dimensions mismatch (8x1 vs 1x400) - octave

I have a problem with non-negative matrix factorization in octave. I try to estimate synergies from Emg-data, but octave only lets me do this for two or more synergies, but not for one. I was able to reproduce the problem with the following code.
nmf_bpas is from the linear-algebra pkg from octave-forge.
V=rand(4, 20);
k=1; k2=2;
[W, H, Iter, HIS]=nmf_bpas(V,k);
with this input I get the following error:
error: vertical dimensions mismatch (4x1 vs 1x20)
error: called from
nmf_bpas>getStopCriterion at line 373 column 19
nmf_bpas at line 266 column 26
when I define k>1 as in the following it works
[W2, H2, Iter2, HIS2]=nmf_bpas(V,k2);
with this input, it works fine, and the output matrices are W2 (4x2) and H2 (2x20).
same problem is when I try it with other codes for nnmf and specify the input data Winit and Hinit for matrices (4x1) and (1x20) (eg.:[W, H] = nmf_pg (V, Winit, Hinit, tol, timelimit, maxiter))
in matlab it works with the nnmf function.
I would be glad about help

This seems to be a bug in nmf_bpas.
From what I can tell, the bug is on line 373. Change
pGrad = [gradW(gradW<0|W>0); gradH(gradH<0|H>0)];
to
pGrad = [gradW(gradW<0|W>0); gradH(gradH<0|H>0)(:)];
and it will work.

Related

tutorial code for octave gives me weird error

% create GMM
mu = [0; 5];
sigma = cat(3, 1, 2);
p = [0.5; 0.5];
gmm = gmdistribution(mu, sigma, p);
% view PDF
ezplot(#(x) pdf(gmm,x));
I'm trying to run this small tutorial code since i'm new to octave
but everytime I run this code it gives me error
error: gmdistribution.pdf: X has 500 columns instead of 1
what does this error mean?
How do I fix it?
The error is effectively telling you that you passed a horizontal vector to the gmmdistribution.pdf function, instead of a vertical one, which is what it expects.
This is because ezplot internally generates a horizontal vector of 500 points on the x-axis to plot your graph.
Therefore you can 'transpose' x when you use it in your anonymous function to, get it in the right orientation:
ezplot(#(x) pdf(gmm,x.'));

Tensor shape mismatch error in PyTorch on MNIST dataset, but no error on synthetic data

I am trying to implement a Deep Learning paper (https://github.com/kiankd/corel2019) and having a weird error when supplying real data (MNIST) to it, but no error when using the same synthetic data as the authors used.
The error happens in this function:
def get_armask(shape, labels, device=None):
mask = torch.zeros(shape).to(device)
arr = torch.arange(0, shape[0]).long().to(device)
mask[arr, labels] = -1.
return mask
More specifically this line:
mask[arr, labels] = -1.
The error is:
RuntimeError: The shape of the mask [500] at index 0 does not match the shape of the indexed tensor [500, 10] at index 1
The weird thing is, that if I use the synthetic data, there is no error and it works perfectly. If I print out the shapes, I get the following (both with synthetic data and with MNIST):
mask torch.Size([500, 10])
arr torch.Size([500])
labels torch.Size([500])
The code used to generate the synthetic data is the following:
X_data = (torch.rand(N_samples, D_input) * 10.).to(device)
labels = torch.LongTensor([i % N_classes for i in range(N_samples)]).to(device)
While the code to load MNIST is this:
train_images = mnist.train_images()
X_data_all = train_images.reshape((train_images.shape[0], train_images.shape[1] * train_images.shape[2]))
X_data = torch.tensor(X_data_all[:500,:]).to(device)
X_data = X_data.type(torch.FloatTensor)
labels = torch.tensor(mnist.train_labels()[:500]).to(device)
get_armask is used the following way:
def forward(self, predictions, labels):
mask = get_armask(predictions.shape, labels, device=self.device)
# make the attractor and repulsor, mask them!
attraction_tensor = mask * predictions
repulsion_tensor = (mask + 1) * predictions
# now, apply the special cosine-COREL rules, taking the argmax and squaring the repulsion
repulsion_tensor, _ = repulsion_tensor.max(dim=1)
repulsion_tensor = repulsion_tensor ** 2
return arloss(attraction_tensor, repulsion_tensor, self.lam)
The actual error seems to be different from what is in the error message, but I have no idea where to look. I tried a few things, like changing the learning rate, normalizing the MNIST data to be more or less in the same range as the test data but nothing seems to work.
Any suggestions? Thanks a lot in advance!
After exchanging some emails with the author of the paper we figured out what is the problem. The labels were type of Byte instead of Long, that caused the error. The error message is very misleading, the actual problem has nothing to do with the sizes...

How to solve a second order differential equation on Scilab?

I need to solve this differential equation using Runge-Kytta 4(5) on Scilab:
The initial conditions are above. The interval and the h-step are:
I don't need to implement Runge-Kutta. I just need to solve this and plot the result on the plane:
I tried to follow these instructions on the official "Scilab Help":
https://x-engineer.org/graduate-engineering/programming-languages/scilab/solve-second-order-ordinary-differential-equation-ode-scilab/
The suggested code is:
// Import the diagram and set the ending time
loadScicos();
loadXcosLibs();
importXcosDiagram("SCI/modules/xcos/examples/solvers/ODE_Example.zcos");
scs_m.props.tf = 5000;
// Select the solver Runge-Kutta and set the precision
scs_m.props.tol(6) = 6;
scs_m.props.tol(7) = 10^-2;
// Start the timer, launch the simulation and display time
tic();
try xcos_simulate(scs_m, 4); catch disp(lasterror()); end
t = toc();
disp(t, "Time for Runge-Kutta:");
However, it is not clear for me how I can change this for the specific differential equation that I showed above. I have a very basic knowledge of Scilab.
The final plot should be something like the picture bellow, an ellipse:
Just to provide some mathematical context, this is the differential equation that describes the pendulum problem.
Could someone help me, please?
=========
UPDATE
Based on #luizpauloml comments, I am updating this post.
I need to convert the second-order ODE into a system of first-order ODEs and then I need to write a function to represent such system.
So, I know how to do this on pen and paper. Hence, using z as a variable:
OK, but how do I write a normal script?
The Xcos is quite disposable. I only kept it because I was trying to mimic the example on the official Scilab page.
To solve this, you need to use ode(), which can employ many methods, Runge-Kutta included. First, you need to define a function to represent the system of ODEs, and Step 1 in the link you provided shows you what to do:
function z = f(t,y)
//f(t,z) represents the sysmte of ODEs:
// -the first argument should always be the independe variable
// -the second argument should always be the dependent variables
// -it may have more than two arguments
// -y is a vector 2x1: y(1) = theta, y(2) = theta'
// -z is a vector 2x1: z(1) = z , z(2) = z'
z(1) = y(2) //first equation: z = theta'
z(2) = 10*sin(y(1)) //second equation: z' = 10*sin(theta)
endfunction
Notice that even if t (the independent variable) does not explicitly appear in your system of ODEs, it still needs to be an argument of f(). Now you just use ode(), setting the flag 'rk' or 'rkf' to use either one of the available Runge-Kutta methods:
ts = linspace(0,3,200);
theta0 = %pi/4;
dtheta0 = 0;
y0 = [theta0; dtheta0];
t0 = 0;
thetas = ode('rk',y0, t0, ts, f); //the output have the same order
//as the argument `y` of f()
scf(1); clf();
plot2d(thetas(2,:),thetas(1,:),-5);
xtitle('Phase portrait', 'theta''(t)','theta(t)');
xgrid();
The output:

Octave function definition error

I am trying to use octave for the first time and I want to create a function as follows:
1;
function test=calc(x)
a=x^2;
factorial(a)
endfunction
val = calc (3)
I saved this as calc.m and when I run it I get an error that variable x is not defined.
What am I doing wrong?
Update: The original question I managed to get working but now I ended up with another problem. Please consider the following code:
init = 5.;
function val=prodval(x)
global init;
val=x+init^2;
endfunction
fin=prodval(3)
When I save the script as test.m and run it i get the following error:
>> test
error: for x^A, A must be a square matrix. Use .^ for elementwise power.
error: called from
prodval at line 5 column 6
test at line 7 column 4
What exactly is going on here? I do not see where I defined a matrix by mistake... I also realise that this may not be the best definition of a function but I am trying...
[UPDATE]
For each scope you want a global to be "visible" you have to declare
it as global. Reference
global init = 5;
function val = prodval (x)
global init;
val = x + init^2;
endfunction
fin=prodval(3)
fin = 28

Differential equation; function in Octave

I try to solve a differential equation in Octave. In a first attempt, all my independent variables are set constant (n,y,w). This is my code:
function xdot= f(x,t);
% xdot=zeros(1,1);
X=1.44221E+12;
IO=5.318E+11;
GO=6.81E+11;
beta=0;
gamma=0;
y=58.5021088;
w= 31.29;
n=1363.5;
tw=0.4;
tp=0.3;
sw=0.07;
sp=0.25;
mw=0.593941689;
mp=0.593941689;
% aw=(1-tw)(sw+mw)
% ap=(1-tp)(sp+mp)
xdot=-(X+IO*(1+gamma*(diff(n)/n+diff(y)/y))+GO*beta(tw(diff(n)/n+diff(w)/w)+tp(diff(y)/y-diff(w)/w)-(x*n)/((y-w)((1-tp)(sp+mp)+tp)+((1-tw)(sw+mw)+tw)*w))*x)/(IO*gamma+GO*beta*tw);
endfunction
When I add
t = [0:(1/360):10]
x = lsode ("f", 39290000, t);
to solve the equation in the command line, I get this error:
error: index (0.843942): subscripts must be either integers 1 to (2^31)-1 or logicals
error: lsode: evaluation of user-supplied function failed
error: called from
f at line 23 column 7
It seems to me, in some way I misunderstood how to make the function.
Any help?
EDIT:
This is my new code:
function xdot= f(x,t);
X=1.44221E+12;
IO=5.318E+11;
GO=6.81E+11;
beta=0;
gamma=0;
y=58.5021088;
w= 31.29;
n=1363.5;
tw=0.4;
tp=0.3;
sw=0.07;
sp=0.25;
mw=0.593941689;
mp=0.593941689;
xdot=-X+IO-(x*n)/((y-w)*((1-tp)*(sp+mp)+tp)+w*(tw+(1-tp)*(sp+mp)))
endfunction
It does work if I copy it into the command line but if I start it as programm (f.m) and solve it then I get this error:
error: 'x' undefined near line 25 column 15
error: called from
f at line 25 column 7
From the documentation of lsode:
Syntax: [x, istate, msg] = lsode (fcn, x_0, t)
...
The first argument, fcn, is a string, inline, or function handle that names the function f to call to compute the vector of right hand sides for the set of equations. The function must have the form
xdot = f (x, t)
in which xdot and x are vectors and t is a scalar.
So firstly, your f function is of the wrong form to the one expected by lsode, since it takes 5 arguments as opposed to 2.
Secondly, inside your f function, the variables y, w, and n are overwritten, regardless of whether they were supplied, whereas t and x need to be supplied by the user.
When lsode calls the handle f, it calls it with two arguments as per its specification, which means it instantiates t and y, and calls the function with the remaining input arguments undefined. Of the remaining arguments, w and n are given values inside the function, as we pointed out above, but x remains undefined. So when you run the final calculation which relies on x, you get an error saying it has not yet been defined during the call to this function.
So, to fix this issue, rewrite your function such that its signature is f(x, t), which you can do so easily since y, w, and n are defined inside your function anyway, so they don't really need to be given as inputs.