MindSpore多元自动微分

函数形式与雅可比矩阵形式

$z_{i,j}(x)=y_ix_j$

$J_z(x)= \left[ \begin{array}{l} \frac{\partial z_0}{\partial x_0} & \frac{\partial z_0}{\partial x_1} & \frac{\partial z_0}{\partial x_2}\\ \frac{\partial z_1}{\partial x_0} & \frac{\partial z_1}{\partial x_1} & \frac{\partial z_1}{\partial x_2}\\ \frac{\partial z_2}{\partial x_0} & \frac{\partial z_2}{\partial x_1} & \frac{\partial z_2}{\partial x_2} \end{array} \right]$

$x=[1,2,3]\\ y=[1,3,2]$

$J_z(x)=\left[ \begin{array}{l} 1 & 0 & 0\\ 0 & 0 & 3\\ 0 & 2 & 0\\ \end{array} \right]$

from mindspore import nn, Tensor, ops
import numpy as np
from mindspore import numpy as msnp

class Net(nn.Cell):
def __init__(self, y, index):
super(Net, self).__init__()
self.y = y
self.index = index
self.norm = nn.Norm(-1)

def construct(self, x):
return self.y[self.index]*x

x = Tensor(np.array([1,2,3]).astype(np.float32))
y = Tensor(np.array([[1],[2],[3]]).astype(np.float32))
index = Tensor(np.array([0,2,1]).astype(np.int32))
shape = (y.shape[0], x.shape[0])

print(output)
# [6. 6. 6.]

$\left[ \frac{\partial z_0}{\partial x_0}+\frac{\partial z_1}{\partial x_0}+\frac{\partial z_2}{\partial x_0}, \frac{\partial z_0}{\partial x_1}+\frac{\partial z_1}{\partial x_1}+\frac{\partial z_2}{\partial x_1}, \frac{\partial z_0}{\partial x_2}+\frac{\partial z_1}{\partial x_2}+\frac{\partial z_2}{\partial x_2} \right]$

尝试扩维输入的自动微分

from mindspore import nn, Tensor, ops
import numpy as np
from mindspore import numpy as msnp

class Net(nn.Cell):
def __init__(self, y, index):
super(Net, self).__init__()
self.y = y
self.index = index
self.norm = nn.Norm(-1)

def construct(self, x):
return self.y[self.index]*x

x = Tensor(np.array([1,2,3]).astype(np.float32))
y = Tensor(np.array([[1],[2],[3]]).astype(np.float32))
index = Tensor(np.array([0,2,1]).astype(np.int32))
shape = (y.shape[0], x.shape[0])

print(output)
'''
[[1. 1. 1.]
[3. 3. 3.]
[2. 2. 2.]]
'''

$I=\left[ \begin{array}{l} 1 & 0 & 0\\ 0 & 0 & 1\\ 0 & 1 & 0 \end{array} \right]$

from mindspore import nn, Tensor, ops
import numpy as np
from mindspore import numpy as msnp

class Net(nn.Cell):
def __init__(self, y, index, size):
super(Net, self).__init__()
self.y = y
self.index = index
self.norm = nn.Norm(-1)

def construct(self, x):

x = Tensor(np.array([1,2,3]).astype(np.float32))
y = Tensor(np.array([[1],[2],[3]]).astype(np.float32))
index = Tensor(np.array([0,2,1]).astype(np.int32))
shape = (y.shape[0], x.shape[0])

print(output)
'''
[[1. 0. 0.]
[0. 0. 3.]
[0. 2. 0.]]
'''

版权声明

• 0
点赞
• 1
收藏
觉得还不错? 一键收藏
• 0
评论
09-20 1150
06-26
02-24 1895
08-07 753
12-21 1680
08-10
09-17 1417
03-28 1048

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。