Gluon

# 灵活运用gluon实现神经网络

from mxnet import nd
from mxnet.gluon import nn

net = nn.Sequential()

# net.name_scope()创建了一个名为net的命名空间,所有在with语句块中添加到net中的层都会包含在这个命名空间中
# 这样,可以确保所有这些层都以net.作为前缀,从而帮助组织这些层并将它们与其他命名空间中的层区分开来。
# 系统会自动帮我们添加前缀,导致这个网络变得独一无二,以防出现误差

with net.name_scope():
    net.add(nn.Dense(256, activation='relu'))
    net.add(nn.Dense(10))

print(net)


# 使用 block定义


class MLP(nn.Block):
    def __init__(self, **kwargs):
        super(MLP, self).__init__(**kwargs)
        with self.name_scope():
            self.dense0 = nn.Dense(256)
            self.dense1 = nn.Dense(10)

    def forward(self, x):
        return self.dense1(nd.relu(self.dense0(x)))


net2 = MLP()
print(net2)
net2.initialize()

x = nd.random_uniform(shape=(4, 20))
y = net2(x)
print(y)


# nnBlock到底是什么东西?
# 在gluon 里,nn.Block 是一个一般化的部件。整个神经网络可以是一个nn.Block,单个层也是一个nn.Block。
# 我们可以 (近似)无限地嵌套 nnBlock 来构建新的 nn.Block。
# nnBlock主要提供这个东西
# 1.储存参数
# 2.描述forward如何执行
# 3.自动求导

# nn.Sequential 是一个nn.Block 容器,它通过 add 来添加 nn.Block 。
# 它自动生成forward()函数,其就是把加进来的 nn.Block 逐一运行。

# 嵌套使用

class RecMLP(nn.Block):
    def __init__(self, **kwargs):
        super(RecMLP, self).__init__(**kwargs)
        self.net = nn.Sequential()
        with self.name_scope():
            self.net.add(nn.Dense(256, activation='relu'))
            self.net.add(nn.Dense(128, activation='relu'))
            self.dense = nn.Dense(64)

    def forward(self, x):
        return nd.relu(self.dense(self.net(x)))


rec_mlp = nn.Sequential()
rec_mlp.add(RecMLP())
rec_mlp.add(nn.Dense(10))
print(rec_mlp)

 

posted @ 2023-08-06 12:28  o-Sakurajimamai-o  阅读(11)  评论(0编辑  收藏  举报
-- --