mygrad.save#

mygrad.save(file: str | Path | BinaryIO, tensor: Tensor) None[source]#

Saves a tensor and its gradient information.

This docstring was adapted from that of numpy.save()

Parameters:
filestr | Path | BinaryIO

The file or file-path that where the tensor data and its gradient will be saved. Note that the file will be saved as a .npz file.

tensorTensor

The tensor to be saved. If it has an associated gradient, that will be saved as well.

See also

mygrad.load

Notes

This function uses numpy.savez(file, data=tensor.data, grad=tensor.grad) to save the tensor’s data and its gradient. No grad field is included if the tensor does not have a gradient.

Examples

>>> import mygrad as mg
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = mg.arange(10.0)
>>> mg.save(outfile, x)
>>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> mg.load(outfile)
Tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])

An example of saving a tensor that has an associated gradient.

>>> (x * x).backward()
>>> x.grad
array([ 0.,  2.,  4.,  6.,  8., 10., 12., 14., 16., 18.])
>>> outfile = TemporaryFile()
>>> x = mg.arange(10.0)
>>> mg.save(outfile, x)
>>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> loaded = mg.load(outfile)
>>> loaded
Tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> loaded.grad
array([ 0.,  2.,  4.,  6.,  8., 10., 12., 14., 16., 18.])