欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mxnet基础到提高(37)-自定义前向操作

程序员文章站 2022-04-05 09:46:23
...
from mxnet import nd
from mxnet.gluon import nn

class MixMLP(nn.Block):
    def __init__(self, **kwargs):
        # Run `nn.Block`'s init method
        super(MixMLP, self).__init__(**kwargs)
        self.blk = nn.Sequential()
    def forward(self, x):
        y = nd.relu(self.blk(x))
        return y
net = MixMLP()
net.initialize()
x=nd.array([[-10,20],[20,-30]])
y=net(x)
print(y)

[[ 0. 20.]
[20. 0.]]
<NDArray 2x2 @cpu(0)>

下面计算 向量的模长

from mxnet import nd
from mxnet.gluon import nn
#code:liuxing
class computeNorm(nn.Block):
    def __init__(self, **kwargs):
        # Run `nn.Block`'s init method
        super(computeNorm, self).__init__(**kwargs)
        self.blk = nn.Sequential()
    def forward(self, x):
        y = nd.sqrt(nd.sum(nd.power(x,2),axis=1))
        return y
net = computeNorm()
net.initialize()
x=nd.array([[-10,20],[20,-30]])
y=net(x)
print(y)
x=nd.array([[-10,20,6],[20,-30,9]])
y=net(x)
print(y)

[22.36068 36.05551]
<NDArray 2 @cpu(0)>

[23.151674 37.161808]
<NDArray 2 @cpu(0)>
mxnet基础到提高(37)-自定义前向操作

相关标签: mxnet