-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathmodule_container.py
More file actions
69 lines (52 loc) · 1.99 KB
/
module_container.py
File metadata and controls
69 lines (52 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
# os.environ['TL_BACKEND'] = 'tensorflow'
# os.environ['TL_BACKEND'] = 'mindspore'
# os.environ['TL_BACKEND'] = 'jittor'
# os.environ['TL_BACKEND'] = 'paddle'
os.environ['TL_BACKEND'] = 'torch'
import numpy as np
from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict
import tensorlayerx as tlx
####################### Holds submodules in a list ########################################
d1 = Linear(out_features=800, act=tlx.nn.ReLU, in_features=784, name='linear1')
d2 = Linear(out_features=800, act=tlx.nn.ReLU, in_features=800, name='linear2')
d3 = Linear(out_features=10, act=tlx.nn.ReLU, in_features=800, name='linear3')
layer_list = ModuleList([d1, d2])
# Inserts a given d2 before a given index in the list
layer_list.insert(1, d2)
layer_list.insert(2, d2)
# Appends d2 from a Python iterable to the end of the list.
layer_list.extend([d2])
# Appends a given d3 to the end of the list.
layer_list.append(d3)
print(layer_list)
class model(Module):
def __init__(self):
super(model, self).__init__()
self._list = layer_list
def forward(self, inputs):
output = self._list[0](inputs)
for i in range(1, len(self._list)):
output = self._list[i](output)
return output
net = model()
print(net.trainable_weights)
print(net)
print(net(tlx.nn.Input((10, 784))))
####################### Holds submodules in a Dict ########################################
class MyModule(Module):
def __init__(self):
super(MyModule, self).__init__()
self.dict = ModuleDict({
'linear1': Linear(out_features=800, act=tlx.nn.ReLU, in_features=784, name='linear1'),
'linear2': Linear(out_features=800, act=tlx.nn.ReLU, in_features=800, name='linear2')
})
def forward(self, x, linear):
x = self.dict[linear](x)
return x
x = tlx.convert_to_tensor(np.ones(shape=(1,784)), dtype=tlx.float32)
net = MyModule()
x = net(x, 'linear1')
print(x)