Have you ever wanted to optimize a function created in Matlab with the optimization software (Optune this time) in python to make it feel good? I thought I could do something, so I tried it.
Matlab R2018a Win10 python 3.6 (Anaconda)
It is premised that python contains 3.5 or 3.6 (R2020 may be OK with a little further ver?) I put 3.6 in pyenv.
--Allow matlabengine to be loaded
http://yusuke-ujitoko.hatenablog.com/entry/2019/08/06/212756
Open the anaconda prompt with "administrator authority" referring to here and type the following command
At this time, anaconda3 \ "envs \ py36" is for those who have not installed anaconda in the virtualenv environment.
Is it unnecessary?
cd C:\Program Files\MATLAB\R2018a\extern\engines\python
python setup.py install --prefix="C:\Users\****\anaconda3\envs\py36"
**** is the username. Now python and matlab are linked.
First, the matlab function to execute is as follows. Put this in the same folder as the following python code.
function y = func(x)
y = (x-3)^2;
After that, start Spyder and execute the following command on spyder
import sys
sys.path.append("C:\\Users\\****\\anaconda3\\envs\\py36lib\\site-packages")
import matlab.engine
import optuna
def objective(trial):
x = trial.suggest_uniform('x', -10, 10)
#Now read the Matlab function and return the score for x
score = eng.func(x)
return score
#Main function from here
eng = matlab.engine.start_matlab()
study = optuna.create_study()
study.optimize(objective, n_trials=1000)
The Matlab function func is called on python as shown below, and the result is optimized by Optune. (In this case, the minimum value of 3 can be predicted with 1000 tries). This time it's a simple function, so you don't have to search for it, but it would be easier if you could optimize the complex functions you created in the past. As for variables, python's "x = trial.suggest_uniform ('x', -10, 10)" is simply increased to x1, x2 ... Even those who are good at Matlab and not good at python can optimize various things.
abridgement
[I 2020-09-21 20:52:03,537] Trial 997 finished with value: 0.611554463759686 and parameters: {'x': 2.217980522135359}. Best is trial 551 with value: 3.107692752820123e-07.
[I 2020-09-21 20:52:03,549] Trial 998 finished with value: 1.5139869920248414 and parameters: {'x': 4.230441787336907}. Best is trial 551 with value: 3.107692752820123e-07.
[I 2020-09-21 20:52:03,560] Trial 999 finished with value: 0.5050438774658341 and parameters: {'x': 3.7106643915842654}. Best is trial 551 with value: 3.107692752820123e-07.
study.best_value
Out[14]: 3.107692752820123e-07
study.best_params
Out[15]: {'x': 2.9994425331621684}
There was no space to paste the sushi license. Optuna is amazing. But I'm sure Matlab also has a function (toolbox) that can do this ... Please let me know.
Recommended Posts