基于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:
《动手学深度学习》--阿斯顿张、李牧