pyTorchModel
R2026bDescription
A PyTorchModel object is a wrapper for a
PyTorch® model that facilitates execution in Python® using the MATLAB®
Python interface.
PyTorchModel is a handle object that holds a reference to a PyTorch model instance in Python and settings specifying how MATLAB input data must be converted to torch.Tensor objects for
input to the methods of the model. Use this object to load a PyTorch model, invoke it on inputs, call its other Python object methods, and save it in a different format.
Creation
Syntax
Description
loads a PyTorch model from the file model = pyTorchModel(modelfile)modelfile and returns a
PyTorchModel object.
wraps a MATLAB object with the model = pyTorchModel(pythonObject)py. prefix representing a
PyTorch model in a PyTorchModel object.
instantiates a PyTorch model using the constructor command in Python, loads the weights from the file model = pyTorchModel(modelfile,ConstructorCommand=command)modelfile, and wraps the
result in a PyTorchModel object. For this syntax,
modelfile must be a weight file (saved with
torch.save(model.state_dict(),modelfile)).
instantiates a PyTorch model by executing the specified constructor command in Python and wraps the result in a model = pyTorchModel(ConstructorCommand=command)PyTorchModel object.
loads or wraps a PyTorch model and sets Properties using one or more name-value arguments.model = pyTorchModel(___,Property=Value)
Input Arguments
Properties
Object Functions
forward | Compute PyTorchModel output by invoking Python model on input |
addFunction | Configure data transfer settings for Python method or function of PyTorchModel |
callFunction | Call method of underlying Python PyTorch model instance or function taking model as its first argument |
export | Save underlying PyTorch model in different PyTorch file format |
reload | Reload PyTorch model from stored model loading properties |
Examples
Tips
All numeric inputs passed to the
forwardmethod are automatically converted totorch.Tensorobjects using the data-transfer settings stored in thePyTorchModelobject.Use the
addFunctionmethod to configure data-transfer settings for model methods other thanforward.When the model takes only keyword arguments, pass a MATLAB struct to
forward. The struct is automatically converted to a Python dictionary, with numeric arrays converted totorch.Tensorobjects for the fields specified inInputKeyNames.If you get an "index out of range" error when calling the model, check whether any of the input tensors represent indices. PyTorch uses 0-based indexing, so you must subtract 1 from MATLAB 1-based indices before passing them to the model.
Version History
Introduced in R2026b