MXNet模型构造

基于Block类的模型构造:

回顾一下之前我们是怎么使用MXNet进行模型构造的?

from mxnet import nd
from mxnet.gluon import nn

x = nd.random.uniform(shape=(10,10)
net = nn.Sequential()
net.add(nn.Dense(10, activation='relu')
net.initialize()
net(x)

直接实例化Sequential类得到顺序连接网络net,然后通过add来顺序添加层数。


MXNet提供了更加灵活的模型构造方法——继承Block类构造

Block类是nn模块里提供的一个模型构造类,其实上面的Sequential类就是继承自Block类。

这里我们定义一个MLP类,其继承自Block类,我们重载Block类中的构造函数__init__和前向传播函数forward:

from mxnet import nd
from mxnet.gluon import nn

#直接定义MLP类,继承自block类
class MLP(nn.Block):
    def __init__(self, **kwargs):
        super(MLP, self).__init__(**kwargs)# super()函数是调用父类的一个方法super(MLP,self).__init()调用MLP的父类的构造函数
        self.hidden = nn.Dense(256, activation='relu')
        self.output = nn.Dense(10)
        
    def forward(self, x):
        return self.output(self.hidden(x))

X = nd.random.uniform(shape=(2,20))
net = MLP()
net.initialize()
net(X)

ok,感觉棒棒哒。


接下来自定义一个MySequential()其功能和nn中的Sequential类相似,让我们便于理解Sequential类

class MySequential(nn.Block):
    def __init__(self, **kwargs):
        super(MySequential, self).__init__(**kwargs)
        
    def add(self, block):
        # 下面的_children是一个orderedDict类型,即一个按顺序添加key-value的字典
        # initialize函数时,系统会自动对_children里所有的成员初始化
        self._children[block.name] = block
    
    def forward(self, x):
        # 这里顺序使用key-value的值
        for block in self._children.values():
            x = block(x)
        return x

net = MySequential()
net.add(nn.Dense(256, activation='relu'))
net.add(nn.Dense(10))
net.initialize()
net(X)

构造复杂模型:

class FancyMLP(nn.Block):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.rand_weight = self.params.get_constant(
            'rand_weight', nd.random.uniform(shape=(20,20)))
        self.dense = nn.Dense(20, activation='relu')
        
    def forward(self, x):
        x = self.dense(x)
        x = nd.relu(nd.dot(x, self.rand_weight.data()) + 1)
        x = self.dense(x)
        while x.norm().asscalar() > 1:
            x /= 2
        if x.norm().asscalar() < 0.8:
            x *= 10
        return x.sum()

net = FancyMLP()
net.initialize()
net(x)

因为FancyMLP和Sequential类都是Block类的子类,我们可以嵌套调用它们:

class NestMLP(nn.Block):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.net = nn.Sequential()
        self.net.add(nn.Dense(64, activation='relu'),
                     nn.Dense(32, activation='relu'),
                     nn.Dense(16, activation='relu'))
        self.dense = nn.Dense(16, activation='relu')
        
    def forward(self, x):
        return self.dense(self.net(x))
    
net = nn.Sequential()
net.add(NestMLP(), nn.Dense(20), FancyMLP())
net.initialize()
net(X)

看着好像很复杂,NestMLP类里面嵌套了Sequential类,外面定义的Sequential实例net又嵌套了NestMLP,nn.Dense(20)和FancyMLP()。但是我们只要按顺序执行NestMLP,nn.Dense(20), FancyMLP()就行了。

 

 

Reference:

《动手学深度学习》--阿斯顿张、李牧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值