Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add assignment support for Sequential #4931

Merged
merged 5 commits into from Feb 7, 2018
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 22 additions & 10 deletions torch/nn/modules/container.py
@@ -1,7 +1,8 @@
import warnings
from collections import OrderedDict, Iterable
import string
from itertools import islice

import torch
import warnings
from .module import Module


Expand Down Expand Up @@ -38,6 +39,12 @@ class Sequential(Module):
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
]))

# Example of accessing modules in Sequential
# Specify the module by index
model[1] = nn.Sigmoid()
# Specify the module by name if initialized with OrderedDict
model.relu1 = nn.LeakyReLU()

This comment was marked as off-topic.

"""

def __init__(self, *args):
Expand All @@ -49,18 +56,23 @@ def __init__(self, *args):
for idx, module in enumerate(args):
self.add_module(str(idx), module)

def _get_item_by_idx(self, iterator, idx):
"""Get the idx-th item of the iterator"""
size = len(self)
if not (-size <= idx < size):

This comment was marked as off-topic.

raise IndexError('index {} is out of range'.format(idx))
idx %= size
return next(islice(iterator, idx, None))

def __getitem__(self, idx):
if isinstance(idx, slice):
return Sequential(OrderedDict(list(self._modules.items())[idx]))
else:
if not (-len(self) <= idx < len(self)):
raise IndexError('index {} is out of range'.format(idx))
if idx < 0:
idx += len(self)
it = iter(self._modules.values())
for i in range(idx):
next(it)
return next(it)
return self._get_item_by_idx(self._modules.items(), idx)

This comment was marked as off-topic.


def __setitem__(self, idx, module):
key = self._get_item_by_idx(self._modules.keys(), idx)
return setattr(self, key, module)

def __len__(self):
return len(self._modules)
Expand Down