minimum-redundancy maximum-relevancy (MRMR) for feature selection - matlab

I am using a filter measure in feature selection called (MRMR) minimum-redundancy maximum-relevancy. After i run the code below
function testselection
addpath('C:\Users\Desktop\mRMR_0.9_compiled\mi_0.9');
FeaturesFile = dlmread('test.txt')
[x,y]=size(FeaturesFile)
Features=FeaturesFile(:,1:y-1)
classLeble=FeaturesFile(:,y)
[fea] = mrmr_mid_d(Features, classLeble, 5)
end
I got the following error
Undefined function or variable 'estpab'.
Error in mutualinfo (line 21)
[p12, p1, p2] = estpab(vec1,vec2);
Error in mrmr_mid_d (line 17)
t(i) = mutualinfo(d(:,i), f);
Error in mrmr (line 9)
[fea] = mrmr_mid_d(Features, classLeble, 5);
The code for mrmr_mid_d as below
function [fea] = mrmr_mid_d(d, f, K)
% function [fea] = mrmr_mid_d(d, f, K)
%
% MID scheme according to MRMR
%
% By Hanchuan Peng
% April 16, 2003
%
bdisp=0;
nd = size(d,2);
nc = size(d,1);
t1=cputime;
for i=1:nd,
t(i) = mutualinfo(d(:,i), f);
end;
fprintf('calculate the marginal dmi costs %5.1fs.\n', cputime-t1);
[tmp, idxs] = sort(-t);
fea_base = idxs(1:K);
fea(1) = idxs(1);
KMAX = min(1000,nd); %500
idxleft = idxs(2:KMAX);
k=1;
if bdisp==1,
fprintf('k=1 cost_time=(N/A) cur_fea=%d #left_cand=%d\n', ...
fea(k), length(idxleft));
end;
for k=2:K,
t1=cputime;
ncand = length(idxleft);
curlastfea = length(fea);
for i=1:ncand,
t_mi(i) = mutualinfo(d(:,idxleft(i)), f);
mi_array(idxleft(i),curlastfea) = getmultimi(d(:,fea(curlastfea)), d(:,idxleft(i)));
c_mi(i) = mean(mi_array(idxleft(i), :));
end;
[tmp, fea(k)] = max(t_mi(1:ncand) - c_mi(1:ncand));
tmpidx = fea(k); fea(k) = idxleft(tmpidx); idxleft(tmpidx) = [];
if bdisp==1,
fprintf('k=%d cost_time=%5.4f cur_fea=%d #left_cand=%d\n', ...
k, cputime-t1, fea(k), length(idxleft));
end;
end;
return;
%=====================================
function c = getmultimi(da, dt)
for i=1:size(da,2),
c(i) = mutualinfo(da(:,i), dt);
end;
And the code for mutualinfo as follows
function h = mutualinfo(vec1,vec2)
%=========================================================
%
%This is a prog in the MutualInfo 0.9 package written by
% Hanchuan Peng.
%
%Disclaimer: The author of program is Hanchuan Peng
% at <penghanchuan#yahoo.com> and <phc#cbmv.jhu.edu>.
%
%The CopyRight is reserved by the author.
%
%Last modification: April/19/2002
%
%========================================================
%
% h = mutualinfo(vec1,vec2)
% calculate the mutual information of two vectors
% By Hanchuan Peng, April/2002
%
[p12, p1, p2] = estpab(vec1,vec2);
h = estmutualinfo(p12,p1,p2);
Could someone know what is the problem?

If you use this Mutual information computation package, you can see, the estpab function compiled only for some platforms (there are estpab.dll for Win32 platform, estpab.mexglx the ELF32 file and estpab.mexmac for Mac).
So, you have to recompile this package for your platform.
First of all you have to configure mex building system. Call mex -setup and select appropriate compiler.
Than you can recompile the Mutual information computation package by calling makeosmex.
Note: If you get some errors during compilation like
d:\MATLAB work\mi\estcondentropy.cpp(65) : error C2668: 'log' : ambiguous call to overloaded function
you have to modify appropriate line (65 in this example) in appropriate file (estcondentropy.cpp in this example) from the muInf /= log(2); to muInf /= log(2.0);

In the path C:\Users\Desktop\ isn't the user missing?
Usually windows paths are something like C:\Users\Username\Desktop\
You are probably adding the wrong path, so the program cannot find the function estpab at all.

Related

MATLAB to Scilab conversion: mfile2sci error "File contains no instruction"

I am very new to Scilab, but so far have not been able to find an answer (either here or via google) to my question. I'm sure it's a simple solution, but I'm at a loss. I have a lot of MATLAB scripts I wrote in grad school, but now that I'm out of school, I no longer have access to MATLAB (and can't justify the cost). Scilab looked like the best open alternative. I'm trying to convert my .m files to Scilab compatible versions using mfile2sci, but when running the mfile2sci GUI, I get the error/message shown below. Attached is the original code from the M-file, in case it's relevant.
I Searched Stack Overflow and companion sites, Google, Scilab documentation.
The M-file code follows (it's a super basic MATLAB script as part of an old homework question -- I chose it as it's the shortest, most straightforward M-file I had):
Mmax = 15;
N = 20;
T = 2000;
%define upper limit for sparsity of signal
smax = 15;
mNE = zeros(smax,Mmax);
mESR= zeros(smax,Mmax);
for M = 1:Mmax
aNormErr = zeros(smax,1);
aSz = zeros(smax,1);
ESR = zeros(smax,1);
for s=1:smax % for-loop to loop script smax times
normErr = zeros(1,T);
vESR = zeros(1,T);
sz = zeros(1,T);
for t=1:T %for-loop to carry out 2000 trials per s-value
esr = 0;
A = randn(M,N); % generate random MxN matrix
[M,N] = size(A);
An = zeros(M,N); % initialize normalized matrix
for h = 1:size(A,2) % normalize columns of matrix A
V = A(:,h)/norm(A(:,h));
An(:,h) = V;
end
A = An; % replace A with its column-normalized counterpart
c = randperm(N,s); % create random support vector with s entries
x = zeros(N,1); % initialize vector x
for i = 1:size(c,2)
val = (10-1)*rand + 1;% generate interval [1,10]
neg = mod(randi(10),2); % include [-10,-1]
if neg~=0
val = -1*val;
end
x(c(i)) = val; %replace c(i)th value of x with the nonzero value
end
y = A*x; % generate measurement vector (y)
R = y;
S = []; % initialize array to store selected columns of A
indx = []; % vector to store indices of selected columns
coeff = zeros(1,s); % vector to store coefficients of approx.
stop = 10; % init. stop condition
in = 0; % index variable
esr = 0;
xhat = zeros(N,1); % intialize estimated x signal
while (stop>0.5 && size(S,2)<smax)
%MAX = abs(A(:,1)'*R);
maxV = zeros(1,N);
for i = 1:size(A,2)
maxV(i) = abs(A(:,i)'*R);
end
in = find(maxV == max(maxV));
indx = [indx in];
S = [S A(:,in)];
coeff = [coeff R'*S(:,size(S,2))]; % update coefficient vector
for w=1:size(S,2)
r = y - ((R'*S(:,w))*S(:,w)); % update residuals
if norm(r)<norm(R)
index = w;
end
R = r;
stop = norm(R); % update stop condition
end
for j=1:size(S,2) % place coefficients into xhat at correct indices
xhat(indx(j))=coeff(j);
end
nE = norm(x-xhat)/norm(x); % calculate normalized error for this estimate
%esr = 0;
indx = sort(indx);
c = sort(c);
if isequal(indx,c)
esr = esr+1;
end
end
vESR(t) = esr;
sz(t) = size(S,2);
normErr(t) = nE;
end
%avsz = sum(sz)/T;
aSz(s) = sum(sz)/T;
%aESR = sum(vESR)/T;
ESR(s) = sum(vESR)/T;
%avnormErr = sum(normErr)/T; % produce average normalized error for these run
aNormErr(s) = sum(normErr)/T; % add new avnormErr to vector of all av norm errors
end
% just put this here to view the vector
mNE(:,M) = aNormErr;
mESR(:,M) = ESR;
% had an 'end' placed here, might've been unmatched
mNE%reshape(mNE,[],Mmax)
mESR%reshape(mESR,[],Mmax)]
figure
dimx = [1 Mmax];
dimy = [1 smax];
imagesc(dimx,dimy,mESR)
colormap gray
strESR = sprintf('Average ESR, N=%d',N);
title(strESR);
xlabel('M');
ylabel('s');
strNE = sprintf('Average Normed Error, N=%d',N);
figure
imagesc(dimx,dimy,mNE)
colormap gray
title(strNE)
xlabel('M');
ylabel('s');
The command used (and results) follow:
--> mfile2sci
ans =
[]
****** Beginning of mfile2sci() session ******
File to convert: C:/Users/User/Downloads/WTF_new.m
Result file path: C:/Users/User/DOWNLO~1/
Recursive mode: OFF
Only double values used in M-file: NO
Verbose mode: 3
Generate formatted code: NO
M-file reading...
M-file reading: Done
Syntax modification...
Syntax modification: Done
File contains no instruction, no translation made...
****** End of mfile2sci() session ******
To convert the foo.m file one has to enter
mfile2sci <path>/foo.m
where stands for the path of the directoty where foo.m is. The result is written in /foo.sci
Remove the ```` at the begining of each line, the conversion will proceed normally ?. However, don't expect to obtain a working .sci file as the m2sci converter is (to me) still an experimental tool !

How to optimize new test problem using PlatEMO?

I tried to follow the main tutorial of PlatEMO but I failed to compile it. I tried to modify an already existed function but I've got too many errors.
This is the code I already tried:
classdef counster < PROBLEM
%HELP COUNSTER
methods
%% Initialization
function obj = counster()
obj.Global.M = 2;
if isempty(obj.Global.D)
obj.Global.D = 2;
end
obj.Global.lower =[0,zeros(1,obj.Global.D-1)-2];
obj.Global.upper = [1,zeros(1,obj.Global.D-1)+2];
obj.Global.encoding = 'real';
end
%% Calculate objective values
function PopObj = CalObj(obj,X)
PopObj(:,1) = X(1);
PopObj(:,2) = (1 + X(2))/X(1);
end
%% Calculate constraint violations
function PopCon = CalCon(obj,X)
PopCon(:,1)=-9*X(1)-X(2)+6;
PopCon(:,2)= -9*X(1)-X(2)+1;
end
end
end
and this is an example of built-in function which is correctly working:
classdef CF4 < PROBLEM
% <problem> <CF>
% Constrained benchmark MOP
%------------------------------- Reference --------------------------------
% Q. Zhang, A. Zhou, S. Zhao, P. N. Suganthan, W. Liu, and S. Tiwari,
% Multiobjective optimization test instances for the CEC 2009 special
% session and competition, School of CS & EE, University of Essex, Working
% Report CES-487, 2009.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2018-2019 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------
methods
%% Initialization
function obj = CF4()
obj.Global.M = 2;
if isempty(obj.Global.D)
obj.Global.D = 10;
end
obj.Global.lower = [0,zeros(1,obj.Global.D-1)-2];
obj.Global.upper = [1,zeros(1,obj.Global.D-1)+2];
obj.Global.encoding = 'real';
end
%% Calculate objective values
function PopObj = CalObj(obj,X)
D = size(X,2);
J1 = 3 : 2 : D;
J2 = 2 : 2 : D;
Y = X - sin(6*pi*repmat(X(:,1),1,D)+repmat(1:D,size(X,1),1)*pi/D);
h = Y.^2;
temp = Y(:,2) < 3/2*(1-sqrt(1/2));
h(temp,2) = abs(Y(temp,2));
h(~temp,2) = 0.125 + (Y(~temp,2)-1).^2;
PopObj(:,1) = X(:,1) + sum(h(:,J1),2);
PopObj(:,2) = 1-X(:,1) + sum(h(:,J2),2);
end
%% Calculate constraint violations
function PopCon = CalCon(obj,X)
t = X(:,2) - sin(6*pi*X(:,1)+2*pi/size(X,2)) - 0.5*X(:,1) + 0.25;
PopCon = -t./(1+exp(4*abs(t)));
end
%% Sample reference points on Pareto front
function P = PF(obj,N)
P(:,1) = (0:1/(N-1):1)';
P(:,2) = 1 - P(:,1);
temp1 = 0.5<P(:,1) & P(:,1)<=0.75;
temp2 = 0.75<P(:,1);
P(temp1,2) = -0.5*P(temp1,1)+3/4;
P(temp2,2) = 1 - P(temp2,1)+0.125;
end
end
end
>> main('-algorithm',#MOPSO,'-problem',#counster,'-N',200,'-M',10);
It meant to plot a pareto front of counster problem but I have got this:
Index exceeds matrix dimensions.
Error in INDIVIDUAL (line 79)
obj(i).obj = Objs(i,:);
Error in GLOBAL/Initialization (line 151)
Population = INDIVIDUAL(obj.problem.Init(N));
Error in MOPSO (line 23)
Population = Global.Initialization();
Error in GLOBAL/Start (line 120)
obj.algorithm(obj);
Error in main (line 62)
Global.Start();

cell2mat not supported for C code generation in MATLAB Coder

I am trying to convert a neural network function written in MATLAB to C function by using MATLAB Codel APP. But when I try to convert, I am getting as
cell2mat is not supported for code generation arrayfun is not supported for code generation
How can I replace these functions?
My code is as given below. Input X is a 1x2500 matrix and output is a 1x6 matrix.
Full code is aavailable in this link boneGrwNN
function Y = boneGrwNN(X)
x1_step1.ymin = -1;
% ===== SIMULATION ========
% Format Input Arguments
isCellX = iscell(X);
if ~isCellX, X = {X}; end;
% Dimensions
TS = size(X,2); % timesteps
if ~isempty(X)
Q = size(X{1},1); % samples/series
else
Q = 0;
end
% Allocate Outputs
Y = cell(1,TS);
% Time loop
for ts=1:TS
% Input 1
X{1,ts} = X{1,ts}';
Xp1 = mapminmax_apply(X{1,ts},x1_step1);
% Layer 1
a1 = tansig_apply(repmat(b1,1,Q) + IW1_1*Xp1);
% Layer 2
a2 = softmax_apply(repmat(b2,1,Q) + LW2_1*a1);
% Output 1
Y{1,ts} = a2;
Y{1,ts} = Y{1,ts}';
end
% Format Output Arguments
if ~isCellX, Y = cell2mat(Y); end
end
% ===== MODULE FUNCTIONS ========
% Map Minimum and Maximum Input Processing Function
function y = mapminmax_apply(x,settings)
y = bsxfun(#minus,x,settings.xoffset);
y = bsxfun(#times,y,settings.gain);
y = bsxfun(#plus,y,settings.ymin);
end
% Competitive Soft Transfer Function
function a = softmax_apply(n,~)
if isa(n,'gpuArray')
a = iSoftmaxApplyGPU(n);
else
a = iSoftmaxApplyCPU(n);
end
end
function a = iSoftmaxApplyCPU(n)
nmax = max(n,[],1);
n = bsxfun(#minus,n,nmax);
numerator = exp(n);
denominator = sum(numerator,1);
denominator(denominator == 0) = 1;
a = bsxfun(#rdivide,numerator,denominator);
end
function a = iSoftmaxApplyGPU(n)
nmax = max(n,[],1);
numerator = arrayfun(#iSoftmaxApplyGPUHelper1,n,nmax);
denominator = sum(numerator,1);
a = arrayfun(#iSoftmaxApplyGPUHelper2,numerator,denominator);
end
function numerator = iSoftmaxApplyGPUHelper1(n,nmax)
numerator = exp(n - nmax);
end
function a = iSoftmaxApplyGPUHelper2(numerator,denominator)
if (denominator == 0)
a = numerator;
else
a = numerator ./ denominator;
end
end
% Sigmoid Symmetric Transfer Function
function a = tansig_apply(n,~)
a = 2 ./ (1 + exp(-2*n)) - 1;
end
How can I generate C code for this function ?
You can generate standalone C code only from functions supported by code generation. If you really need C code because your environment doesn't support Matlab, then you have to manually convert unsupported functions or use coder.ceval in order to use external C code that implements the same functions.
In your example, you could replace arrayfun calls with traditional for-loops. In order to implement your own cell2mat code, just type open cell2mat so see the source code of the function and try to replicate its logics within your code.

adding bounds to code, matlab

I am trying to add bounds to the code but having troubling figuring out where to put them. The equation goes: f(x) = e^(6x) + 1.441e^(2x) − 2.079e^(4x) − 0.333 = 0, -1>=x<=0
function c = newton(x0, delta)
c = x0;
fc = f(x0);
fprintf('initial guess: c=%d, fc=%d\n',c,fc)
if abs(fc) <= delta % check to see if initial guess satisfies
return; % convergence criterion.
end;
while abs(fc) > delta,
fpc = fprime(c);
if fpc==0, % if fprime is 0, abort.
error('fprime is 0') % the error function prints message and exits
end;
c = c - fc/fpc; % Newton step
fc = f(c);
fprintf(' c=%d, fc=%d\n',c,fc)
end;
function fx = f(x)
fx = exp(6*x)+1.441*exp(2*x)-2.079*exp(4*x)-0.333; % Enter your function here.
return;
function fprimex = fprime(x)
fprimex = 6*exp(6*x)+6*exp(2*x)*(ln(2))^2-4*exp(4*x)*ln(8); % Enter the derivative of function
return;
I would add the check after the Newton step. This won't protect against someone entering a -1 or 1 as an initial guess, but that could be done when you do your input validation. I took Ander Biguri's advice and changed the c to x:
function x = newton(x0, delta)
x = x0;
fx = f(x0);
fprintf('initial guess: x=%f, fx=%f\n',x,fx)
if abs(fx) <= delta % check to see if initial guess satisfies
return; % convergence criterion.
end;
while abs(fx) > delta,
fpx = fprime(x);
if fpx==0, % if fprime is 0, abort.
error('fprime is 0') % the error function prints message and exits
end;
x = x - fx/fpx; % Newton step
if( x > 1 || x < -1 )
error('x out of bounds!');
end
fx = f(x);
fprintf(' x=%f, fx=%f\n',x,fx)
end
end
function fx = f(x)
fx = exp(6*x)+1.441*exp(2*x)-2.079*exp(4*x)-0.333; % Enter your function here.
end
function fprimex = fprime(x)
fprimex = 6*exp(6*x)+6*exp(2*x)*(log(2))^2-4*exp(4*x)*log(8); % Enter the derivative of function
end
Here's the output I get:
>> x = newton(0.5, 0.5*1e-4)
initial guess: x=0.500000, fx=8.307733
x=0.375798, fx=2.908518
x=0.263566, fx=1.003444
x=0.165026, fx=0.340291
x=0.081315, fx=0.113210
x=0.012704, fx=0.036909
x=-0.041514, fx=0.011793
x=-0.082894, fx=0.003695
x=-0.113515, fx=0.001136
x=-0.135581, fx=0.000341
x=-0.151084, fx=0.000098
x=-0.161526, fx=0.000025
x =
-0.1615

error function aborted matlab

Hi i am running a model in simulink from matlab and i am taking this error
Error using run (line 28) Call to MATLAB function aborted: The first
input argument of the "mpc" command must be one of the following: an
LTI object, an IDMODEL object or a structure of models and offsets.
Block Subsystem2/Control plant (#38) While executing: State During
Action
The embedeed block that i take the erro contains the code
function w0u = MPC(p,x,Sb_bus,Sb,vt,q,theta0,ku,xs,u,vf,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,v0,wb,r,t0,umaxnow,time,samplingsTime,Rn,Qn,Rw,Qw,ud,uMinMPC,uMaxMPC,udMaxMPC,wmin,wminw,wmax,wmaxw,tFLR,aFLR,genset3connected,debuggingfile,mpcOn,mpcValSaveTime,mpcValFileName,useUMaxNow,wNLstart)
coder.extrinsic('mpc');
w0u = zeros(2,1);
[w0u] = mpc(p,x,Sb_bus,Sb,vt,q,theta0,ku,xs,u,vf,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,v0,wb,r,t0,umaxnow,time,samplingsTime,Rn,Qn,Rw,Qw,ud,uMinMPC,uMaxMPC,udMaxMPC,wmin,wminw,wmax,wmaxw,tFLR,aFLR,genset3connected,debuggingfile,mpcOn,mpcValSaveTime,mpcValFileName,useUMaxNow,wNLstart);
end
And the function mpc is
function [w0u] = mpc(p,Sb_bus,Sb,vt,q,x,theta0,ku,xs,u,umaxnow,vf,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,v0,wb,r,t0,time,samplingsTime,Rn,Qn,Rw,Qw,ud,uMinMPC,uMaxMPC,udMaxMPC,wmin,wminw,wmax,wmaxw,tFLR,aFLR,genset3connected,debuggingfile,mpcOn,mpcValSaveTime,mpcValFileName,useUMaxNow,wNLstart)
persistent tupdated w0set
eml.extrinsic('saveVariables');
H = [10; 7];
D = [.02;.025];
if (isempty(tupdated))
% Initialize variables
tupdated = time;
w0set = wNLstart;
elseif (time < t0)
% Wait until t0
elseif (mpcOn == 0)
% If turned off, do nothing.
elseif (time >= tupdated + samplingsTime)
% Update w0
Pbus = sum(p.*Sb)/sum(Sb);
Qbus = sum(q.*Sb)/sum(Sb);
pFLR = aFLR*Sb(end)/Sb_bus*Pbus;
X = [Pbus;Qbus;x];
u0 = u;
udw = ud(1);
%% Calculate the state space equations
[A B B0 Cu Du ~, ud] = makeLinearSystem(H,D,p,Sb_bus,Sb,q,X,vf,vt,theta0,ku,xs,u0,wb,r,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,w0set,v0,samplingsTime,ud);
[Aw Bw B0w Cuw Duw ~, udw] = makeLinearWorstCaseSystem(H,D,p,Sb_bus,Sb,q,X,vf,vt,theta0,ku,xs,u0,wb,r,KvP,KvI,Kp,Ki,Kd,Droop,DroopAvr,w0set,v0,samplingsTime,genset3connected,pFLR,udw);
%% Discretize
if(genset3connected)
% Discretize system for normal case
[Ad Bd B0d] = makediscrete(A,B,B0,samplingsTime);
% Discretize system after FLR reacts
[AdFLRp, ~, ~] = makediscrete(Aw,Bw,B0w,samplingsTime-tFLR);
else
% Sets Ad, Bd, B0d and AdFLRp to remove compilation error (matrices
% must have the same size for all cases)
Ad = A;
Bd = B;
B0d = B0;
AdFLRp = Aw;
end
% Discretize system for failure case
[Adw Bdw B0dw] = makediscrete(Aw,Bw,B0w,samplingsTime);
%% Find input optimal
[dw0opt PHI PSI dw] = findInput(X,Ad,Bd,B0d,Cu,Du,Adw,Bdw,B0dw,Cuw,Duw,AdFLRp,pFLR,Rn,Qn,Rw,Qw,ud,udw,u,umaxnow,uMinMPC,uMaxMPC,udMaxMPC,wmin,wmax,wminw,wmaxw,p,Sb,genset3connected,time,debuggingfile,useUMaxNow);
%% Save internal values for plotting
if(mpcValSaveTime >= time && mpcValSaveTime< time + samplingsTime)
saveVariables(mpcValFileName,PHI,PSI,dw)
end
w0set = w0set + dw0opt;
tupdated = time;
end
w0u =w0set;
end
what i have to do?