mxnet随笔-卷积神经网络基础(2)

版权声明:本博客所有文章版权归博主刘兴所有,转载请注意来源 https://blog.csdn.net/AI_LX/article/details/88359542

构造具有灵活正向函数的网络
创建nn.Block一个子类和实现两种方法:

from mxnet import nd
from mxnet.gluon import nn
class MixMLP(nn.Block):
    def __init__(self, **kwargs):
        super(MixMLP, self).__init__(**kwargs)
        self.blk = nn.Sequential()
        self.blk.add(nn.Dense(5, activation='relu'),
                     nn.Dense(7, activation='relu'))
        self.dense = nn.Dense(4)
    def forward(self, x):
        y = nd.relu(self.blk(x))
        print(y)
        return self.dense(y)

net = MixMLP()
print(net)
net.initialize()

x = nd.random.uniform(shape=(2,3))
y = net(x)
print(y.shape)
print(net.blk[0].weight.data().shape, net.blk[1].weight.data().shape)

MixMLP(
(blk): Sequential(
(0): Dense(None -> 5, Activation(relu))
(1): Dense(None -> 7, Activation(relu))
)
(dense): Dense(None -> 4, linear)
)

[[0.00156497 0.000491 0. 0. 0.0014739 0.
0.00275145]
[0.00237477 0.00133392 0. 0. 0.00215758 0.00239905
0.00092076]]
<NDArray 2x7 @cpu(0)>
(2, 4)
(5, 3) (7, 5)

猜你喜欢

转载自blog.csdn.net/AI_LX/article/details/88359542