TVP

# MindSpore自动微分小技巧

DechinPhy

1100

## 技术背景

Name: mindspore
Version: 2.2.13
Summary: MindSpore is a new open source deep learning training/inference framework that could be used for mobile, edge and cloud scenarios.
Home-page: https://www.mindspore.cn
Author: The MindSpore Authors
Author-email: contact@mindspore.cn
Location: /home/dechin/anaconda3/envs/mindspore-latest/lib/python3.7/site-packages
Requires: packaging, pillow, protobuf, asttokens, numpy, psutil, scipy, astunparse
Required-by: 

## 函数微分

def fE(x, y, z):
return x*z+y

import mindspore as ms
from mindspore import ops, Tensor
x = Tensor([2.0], ms.float32)
y = Tensor([5.0], ms.float32)
print (gfE(x, y, Tensor([3.], ms.float32)))
# [3.]

。假如说我们需要计算

gfE = ops.grad(fE, grad_position=(2, ))
print (gfE(x, y, Tensor([3.], ms.float32)))
# [2.]
print (gfE(x, y, Tensor([3.], ms.float32)))
# (Tensor(shape=[1], dtype=Float32, value= [ 3.00000000e+00]),
#  Tensor(shape=[1], dtype=Float32, value= [ 1.00000000e+00]),
#  Tensor(shape=[1], dtype=Float32, value= [ 2.00000000e+00]))

## 类求导

class Net(nn.Cell):
def __init__(self, z):
super().__init__()
self.z = z
def construct(self, x, y):
return x + y

import mindspore as ms
from mindspore import nn, Parameter, Tensor
class E(nn.Cell):
def __init__(self):
super(E, self).__init__()
self.z = Parameter(Tensor([3.], ms.float32), requires_grad=True, name='z')
def construct(self, x, y):
return x*self.z+y

nt = E()
print (gE(x, y))
# [3.]
print (gE(x, y))
# (Tensor(shape=[1], dtype=Float32, value= [ 3.00000000e+00]),
#  Tensor(shape=[1], dtype=Float32, value= [ 1.00000000e+00]))

nt = E()
# (Tensor(shape=[1], dtype=Float32, value= [ 3.00000000e+00]),
#  Tensor(shape=[1], dtype=Float32, value= [ 1.00000000e+00]))

nt = E()
# [3.]

nt = E()
# [2.]

0 条评论

LV.

• 技术背景
• 函数微分
• 类求导
• 总结概要
• 版权声明