mindscience.common.batched_jacobian
- mindscience.common.batched_jacobian(model)[source]
Calculate Jacobian matrix of network model.
Note
This function internally relies on mindspore.jacrev to compute Jacobian matrices. Therefore, MindSpore version >= 2.0.0 is required.
- Parameters
model (mindspore.nn.Cell) – A network with the input dimension is in_channels and output dimension is out_channels.
- Returns
Tensor, jacobi of the model. With the input dimension is \([batch_size, in_channels]\), output dimension is \([out_channels, batch_size, in_channels]\).
Examples
>>> import numpy as np >>> from mindspore import nn, ops, Tensor >>> from mindspore import dtype as mstype >>> from mindscience.common import batched_jacobian >>> np.random.seed(123456) >>> class Net(nn.Cell): ... def __init__(self, cin=2, cout=1, hidden=10): ... super().__init__() ... self.fc1 = nn.Dense(cin, hidden) ... self.fc2 = nn.Dense(hidden, hidden) ... self.fcout = nn.Dense(hidden, cout) ... self.act = ops.Tanh() ... ... def construct(self, x): ... x = self.act(self.fc1(x)) ... x = self.act(self.fc2(x)) ... x = self.fcout(x) ... return x >>> model = Net() >>> jacobian = batched_jacobian(model) >>> inputs = np.random.random(size=(3, 2)) >>> res = jacobian(Tensor(inputs, mstype.float32)) >>> print(res.shape) (1, 3, 2)