Rav*_*shi 5 python neural-network pytorch
我正在尝试创建nn.Sequential网络的副本。例如,以下是执行相同操作的最简单方法 -
net = nn.Sequential(
nn.Conv2d(16, 32, 3, stride=2),
nn.ReLU(),
nn.Conv2d(32, 64, 3, stride=2),
nn.ReLU(),
)
net_copy = nn.Sequential(
nn.Conv2d(16, 32, 3, stride=2),
nn.ReLU(),
nn.Conv2d(32, 64, 3, stride=2),
nn.ReLU(),
)
Run Code Online (Sandbox Code Playgroud)
然而,重新定义网络就没那么好了。我尝试了以下方法,但没有成功-
net_copy = nn.Sequential(net):在这种方法中,似乎net_copy只是一个共享指针netnet_copy = nn.Sequential(*net.modules()):在这种方法中,net_copy包含更多层。最后,我厌倦deepcopy了以下方法,效果很好-
net_copy = deepcopy(net)
Run Code Online (Sandbox Code Playgroud)
但是,我想知道这是否是正确的方法。我认为这很好,因为它有效。
好吧,我只是使用torch.loadand torch.savewithio.BytesIO
import io, torch
# write to a buffer
buffer = io.BytesIO()
torch.save(model, buffer) #<--- model is some nn.module
print(buffer.tell()) #<---- no of bytes written
del model
# read from buffer
buffer.seek(0) #<--- must see to origin every time before reading
model = torch.load(buffer)
del buffer
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3993 次 |
| 最近记录: |