Model Conversion#

This page covers converting NeurEco Tabular models to Keras, PyTorch, and MATLAB formats for integration with other frameworks.

Overview#

NeurEco models can be converted to popular deep learning frameworks:

  • Keras/TensorFlow — For TensorFlow ecosystem integration

  • PyTorch — For PyTorch ecosystem integration

  • MATLAB — For MATLAB/Simulink integration

The Keras and PyTorch conversions create native framework models that run without the NeurEco engine.

Note

Model conversion requires an embed license and the target framework installed.

Converting to Keras#

Convert your NeurEco model to a native Keras model for TensorFlow integration.

Keras Requirements#

  • NeurEco embed license

  • TensorFlow/Keras installed: pip install tensorflow

Keras Conversion Process#

from NeurEco import NeurEcoTabular as Tabular
from NeurEco.NeurEcoTabular.neureco_to_keras import neureco2keras
import numpy as np

# Load the NeurEco model
neureco_model = Tabular.Regressor()
neureco_model.load("model.ednn")

# Convert to Keras
keras_model = neureco2keras(neureco_model)

# The keras_model is now a standard tf.keras.Model
keras_model.summary()

Using the Keras Model#

import tensorflow as tf

# Make predictions
x_test = np.array([[1.0, 2.0, 3.0, 4.0, 5.0]])
predictions = keras_model.predict(x_test)
print(f"Predictions: {predictions}")

# Save as Keras format
keras_model.save("model_keras.h5")

# Or save in the native .keras format
keras_model.save("model_keras.keras")

# Load later: with Keras 3, import the NeurEco converter module first
# (the converted model uses NeurEco layer classes)
import NeurEco.NeurEcoTabular.neureco_to_keras
loaded_model = tf.keras.models.load_model("model_keras.h5")

Keras Verification#

Verify the converted model produces the same results:

# NeurEco prediction
neureco_output = neureco_model.evaluate(x_test)

# Keras prediction
keras_output = keras_model.predict(x_test)

# Compare
max_diff = np.max(np.abs(neureco_output - keras_output))
print(f"Maximum difference: {max_diff}")

if max_diff < 1e-6:
    print("Conversion verified: outputs match")

Converting to PyTorch#

Convert your NeurEco model to a native PyTorch model.

PyTorch Requirements#

  • NeurEco embed license

  • PyTorch, which pip installs with the NeurEco Python library (see Installation)

PyTorch Conversion Process#

from NeurEco import NeurEcoTabular as Tabular
from NeurEco.NeurEcoTabular.neureco_to_torch import neureco2torch
import torch
import numpy as np

# Load the NeurEco model
neureco_model = Tabular.Regressor()
neureco_model.load("model.ednn")

# Convert to PyTorch (a float32 TorchScript model by default)
torch_model = neureco2torch(neureco_model)

# For a plain torch.nn.Module instead of TorchScript:
# torch_model = neureco2torch(neureco_model, jit_script=False)
print(torch_model)

Using the PyTorch Model#

# Set to evaluation mode
torch_model.eval()

# Make predictions
x_test = torch.tensor([[1.0, 2.0, 3.0, 4.0, 5.0]], dtype=torch.float32)

with torch.no_grad():
    predictions = torch_model(x_test)

print(f"Predictions: {predictions.numpy()}")

# Save the model
torch.save(torch_model.state_dict(), "model_torch.pt")

# Or save the entire model (TorchScript)
torch.jit.save(torch_model, "model_torch_full.pt")

# Load later (without NeurEco)
loaded_model = torch.jit.load("model_torch_full.pt")
loaded_model.eval()

GPU Inference with PyTorch#

# Move model to GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch_model = torch_model.to(device)

# Move data to GPU
x_test = torch.tensor(x_test_np, dtype=torch.float32).to(device)

# Inference on GPU
with torch.no_grad():
    predictions = torch_model(x_test)

PyTorch Verification#

# NeurEco prediction
neureco_output = neureco_model.evaluate(x_test_np)

# PyTorch prediction
torch_model.eval()
with torch.no_grad():
    torch_output = torch_model(torch.tensor(x_test_np, dtype=torch.float32)).numpy()

# Compare
max_diff = np.max(np.abs(neureco_output - torch_output))
print(f"Maximum difference: {max_diff}")

Using with MATLAB#

NeurEco models can be used in MATLAB through the FMU export or Python integration.

Option 1: FMU Import#

Export your model as FMU and import into MATLAB/Simulink:

In Python:

model.export_fmu("model.fmu")

In MATLAB/Simulink:

  1. Add an FMU Import block to your Simulink model

  2. Browse and select the exported .fmu file

  3. Configure inputs and outputs

  4. Run your simulation

Option 2: MATLAB Python Integration#

Call NeurEco directly from MATLAB using MATLAB’s Python integration:

In MATLAB:

% Setup Python environment (if needed)
pyenv('Version', 'path/to/python');

% Import NeurEco
neureco = py.importlib.import_module('NeurEco.NeurEcoTabular');

% Load model
model = neureco.Regressor();
model.load('model.ednn');

% Prepare input data
x_test = py.numpy.array([1.0, 2.0, 3.0, 4.0, 5.0]);
x_test = x_test.reshape(int32(1), int32(5));

% Evaluate
result = model.evaluate(x_test);

% Convert to MATLAB array
predictions = double(result);

Option 3: Generated C Code#

Export to C and use MATLAB Coder or S-Function:

In Python:

model.export_c("model.h", precision="float64")

In MATLAB:

Create an S-Function wrapper or use MATLAB Coder to integrate the C code into Simulink.

Complete Conversion Example#

Here’s a complete workflow showing all conversion options:

from NeurEco import NeurEcoTabular as Tabular
from NeurEco.NeurEcoTabular.neureco_to_keras import neureco2keras
from NeurEco.NeurEcoTabular.neureco_to_torch import neureco2torch
import numpy as np

# Load the trained NeurEco model
model = Tabular.Regressor()
model.load("energy_model.ednn")

# Prepare test data
x_test = np.genfromtxt("x_test.csv", delimiter=";", skip_header=True)

# Get NeurEco predictions (baseline)
neureco_predictions = model.evaluate(x_test)

# === Convert to Keras ===
keras_model = neureco2keras(model)
keras_predictions = keras_model.predict(x_test)
keras_model.save("energy_keras.h5")
print(f"Keras max diff: {np.max(np.abs(neureco_predictions - keras_predictions))}")

# === Convert to PyTorch ===
torch_model = neureco2torch(model)
torch_model.eval()
import torch
with torch.no_grad():
    torch_predictions = torch_model(torch.tensor(x_test, dtype=torch.float32)).numpy()
torch.jit.save(torch_model, "energy_torch.pt")
print(f"PyTorch max diff: {np.max(np.abs(neureco_predictions - torch_predictions))}")

# === Export to FMU for MATLAB ===
model.export_fmu("energy_matlab.fmu")

# === Export to C for embedded ===
model.export_c("energy_embedded.h", precision="float32")

# === Export to ONNX for cross-platform ===
model.export_onnx("energy_onnx.onnx", precision="float32")

print("All conversions complete!")

# Cleanup
model.delete()

Best Practices#

  1. Always verify: Compare outputs between original and converted models

  2. Match precision: Use consistent precision (float32) across frameworks

  3. Test edge cases: Verify behavior on boundary inputs

  4. Document conversions: Keep track of which NeurEco model version was converted

  5. Keep originals: Always retain the .ednn file as the source of truth

Troubleshooting#

Keras conversion fails:

  • Ensure TensorFlow is installed: pip install tensorflow

  • Check TensorFlow version compatibility

PyTorch conversion fails:

  • Check that the installed PyTorch is the version your NeurEco package requires (see Installation)

  • Check CUDA version if using GPU

Output differences:

  • Small differences (< 1e-5) are normal due to floating-point precision

  • Larger differences may indicate precision mismatch (float32 vs float64)

MATLAB integration issues:

  • Verify Python path is correctly configured in MATLAB

  • Check that required Python packages are installed

Next Steps#