Azzera filtri
Azzera filtri

Error while calling a Keras Model from Matlab

2 visualizzazioni (ultimi 30 giorni)
ARUN
ARUN il 23 Feb 2021
Risposto: surya venu il 19 Apr 2024
Basically, I have regression neural network saved in .H5 format. I want to use the NN model's prediction in my simulink model. I am trying to call the python where the NN model is imported using Keras.load_model. When I call the python with NN model imported I am getting an error but if I call it without the NN model its working fine.
Matlab function to call python:
function y = fcn(in1,in2)
y = 0; % Has to be preassigned, otherwise Simulink throws an error
coder.extrinsic('py.final10.test') % Python functions have to be run extrinsically, meaning no C code generated
y = double(py.final10.test(in1,in2));
end
Python :final10.py
from tensorflow import keras
from keras.models import load_model
import numpy as np
model = load_model('model.h5')
def test(in1,in2):
x1 = in1
x2 = in2
a = np.asarray(x1)
b = np.asarray(x2)
G = np.asarray([a,b])
x3 = G.reshape(1,2)
x4 = model.predict(x3)
print(x4)
y = x1+x2;
return y
If I didn't include the load_model line, I am able to call the python from Matlab. Can anyone help me to solve this issue.
Below is the error, I am getting:
Undefined function 'py.finalv10.test' for input arguments of type 'double'. Error in 'active_vehicleV1/Vehicle/MATLAB Function' (line 4) y = double(py.finalv10.test(in1,in2));

Risposte (1)

surya venu
surya venu il 19 Apr 2024
Hi,
The issue arises because Simulink attempts to generate C code for the py.final10.test function when the load_model line is included. However, C code generation fails for functions involving external libraries like TensorFlow.
Here's how you can solve the problem:
Python Script for Model Loading (model_loader.py):
from tensorflow import keras
from keras.models import load_model
model = load_model('model.h5')
def get_model():
global model
return model
Python Script for Prediction (final10.py):
import numpy as np
def test(in1, in2, loaded_model):
x1 = in1
x2 = in2
a = np.asarray(x1)
b = np.asarray(x2)
G = np.asarray([a, b])
x3 = G.reshape(1, 2)
x4 = loaded_model.predict(x3)
# print(x4) # Optional for debugging
y = x1 + x2
return y
# Load the model outside the function to avoid reloading on every call
loaded_model = get_model()
MATLAB Function (fcn.m):
function y = fcn(in1, in2)
y = 0; % Preassign
coder.extrinsic('py.final10.test', 'py.model_loader.get_model');
% Load the model in the function for better memory management
loaded_model = py.model_loader.get_model();
y = double(py.final10.test(in1, in2, loaded_model));
end
Hope it helps

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by