How to execute Python script inside a Matlab '' for loop ''?

4 views (last 30 days)
I have two Matlab " for loops " like this,
%Matlab Code:
for M=1:NoRun
for ii=1:NoP
z1 = position(ii,1,M);
z2 = position(ii,2,M);
And inside the second " for loop " I have a ' Python script ' with variables "z1" and "z2" like this,
#Python Code:
# Initialising the ANN
model0 = Sequential()
# Adding 1 hidden layer: the input layer and the first hidden layer
model0.add(Dense(units = z1, activation = 'tanh', input_dim = 4, kernel_initializer=my_init))
# Adding 2 hidden layer
model0.add(Dense(units = z2, activation = 'tanh', kernel_initializer=my_init))
# Adding output layer
model0.add(Dense(units = 6, activation = 'softmax', kernel_initializer=my_init))
# Set up Optimizer
Optimizer = tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.99)
# Compiling the ANN
model0.compile(optimizer = Optimizer, loss = 'categorical_crossentropy', metrics=['accuracy','categorical_crossentropy','mse'])
# Fitting the ANN to the Train set, at the same time observing quality on Valid set
history = model0.fit(X_train, y_train_dummy, validation_data=(X_test, y_test_dummy), batch_size = 100, epochs = 1500)
# Generate prediction for all Train, Valid set and Experimental set
y_train_pred_model0 = model0.predict(X_train)
y_test_pred_model0 = model0.predict(X_test)
y_exp_pred_model0 = model0.predict(E_data)
# find final prediction by taking class with highest probability
y_train_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_train_pred_model0])
y_test_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_test_pred_model0])
y_exp_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_exp_pred_model0])
# check what metrics are in fact available in history
history.history.keys()
ac = (accuracy_score(y_test, y_test_pred_model0))*100
I need the value of accuracy_score 'ac' after each time executing the for loop, such that i can give this value to another variable inside this loop like this (written in Matlab)
%Matlab Cade:
Accurcy(M,ii)=ac;
F1=(Accurcy);
IAE(M,ii)=-F1;
pBestFF(ii)=min(IAE(:,ii));
if (pBestFF(ii)-IAE(M,ii))==0
pBestX(ii,:)=position(ii,:,M); %% Personal Best Particles
end
end % Second for loop ends here.
%% Global Best(gBest) Calculation
gBestFF=min(pBestFF);
for ii=1:NoP
if (IAE(M,ii)-gBestFF)==0
gBestX=position(ii,:,M);
end
end
% Calculation of Particle Velocity and Position
c1=2; c2=2;
inertia(M)=((NoRun - M)*(0.9 - 0.4))/NoRun + 0.4;
for ii=1:NoP
for jj=1:dimension
velocity(ii,jj,M+1) =inertia(M)* velocity(ii,jj,M) + c1*rand(1)*(pBestX(ii,jj) -
position(ii,jj,M)) + c2*rand(1)*(gBestX(jj) - position(ii,jj,M));%% Velocity update
velocity(ii,jj,M+1) = min(vmax(jj),max(vmin(jj),velocity(ii,jj,M+1)));
position(ii,jj,M+1) = position(ii,jj,M) + velocity(ii,jj,M+1);
position(ii,jj,M+1)=min(smax(jj),max(smin(jj),position(ii,jj,M+1)));
end
end
gbestFF1=[gbestFF1 gBestFF];
Nrun1=[Nrun1 M];
end % First for loop ends here.
I am doing this in Matlab. Suggest your Ideas for how to do this in Matlab.

Answers (1)

Bo Li
Bo Li on 17 Feb 2020
Hopefully I understand the question correctly. I wonder you can create a Python function in a Python file mymodule.py to wrap your Python script for example myFunc like following:
#mymodule.py
#myFunc accepts z1 and z2 as inputs, returns ac as output
def myFunc(z1, z2):
#Python logic
return ac
Then you MATLAB loops could look like following:
for M=1:NoRun
for ii=1:NoP
z1 = position(ii,1,M);
z2 = position(ii,2,M);
ac = py.mymodule.myFunc(z1, z2); #mymodule.py should be in Python PATH or current folder
%use ac in more MATLAB logic
  4 Comments
Bo Li
Bo Li on 20 Feb 2020
You will need to have CPython installed on your machine in order to invoke Python script from MATLAB. Depending on your MATLAB version, you might use either pyenv or pyversion to set up the Python interpreter:
Bo Li
Bo Li on 24 Feb 2020
"how can I import Python script in matlab and pass the arguments (variables) to it and get the result from it, to pass the result to further Matlab Program"
%Say you create a Python file mymodule.py in folder "C:\work" and you have CPython 3.7 installed in "C:\python3" folder. You can launch MATLAB and do following in MATLAB:
>>cd c:\work
>>pyenv('Version', 'C:\python3\bin\python')
>>ac=py.mymodule.myFunc(1,2) %py.mymodule imports the Python module in MATLAB

Sign in to comment.

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!