Calling python scripts that use "from" keyword to import keras from MATLAB

4 views (last 30 days)
I've set my pyversion as the command-line-downloaded executable of python, and I have added the directory containing all site-packages (modules/libraries) to the python path. When I call the following python script (test_from_import.py), I get an error traceback pointing to the "from" statement.
from tensorflow import keras
import tensorflow.keras
The second line works (if you comment out the first), but then the same error occurs with this:
from tensorflow.keras import backend as K
The way I am calling this test.py file in matlab is as follows:
testDir = '.....'
addpath(testDir)
% Specify Python Executable Library.
pcPythonExe = 'C:\Users\dmattioli\AppData\Local\Programs\Python\Python37\python.exe';
[ver, exec, loaded] = pyversion(pcPythonExe); pyversion
% Ensure python-matlab integration code is on matlab path.
pyFolder = fullfile(matlabroot, 'toolbox', 'matlab', 'external', 'interfaces', 'python');
addpath(pyFolder);
% Folder containing all relevant python libraries.
pyLibraryFolder = 'C:\Users\dmattioli\AppData\Local\Programs\Python\Python37\Lib\site-packages';
% Add folders to python system path.
insert(py.sys.path, int64(0), testDir);
insert(py.sys.path, int64(0), pyFolder);
insert(py.sys.path, int64(0), pyLibraryFolder);
%% Call python script.
py_test_mod = py.importlib.import_module('test_from_import')
% % Using system call instead of matlab-python integration functionality.
% [result, status] = python('test_from_import.py') % Does not return error.
Interestingly enough, these errors don't occur if I follow the instructions in this thread: https://www.mathworks.com/matlabcentral/answers/153867-running-python-script-in-matlab
  2 Comments

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!