Skip to content
This repository has been archived by the owner on Jul 2, 2021. It is now read-only.

Better human readable representation for PickableSequentialChain #892

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions chainercv/links/model/pickable_sequential_chain.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
import inspect

import chainer

Expand Down Expand Up @@ -160,3 +161,24 @@ def copy(self, *args, **kargs):
copied._return_tuple = copy.copy(self._return_tuple)

return copied

def __str__(self):
reps = []
for name in self.layer_names:
layer = self[name]
# Explore better representation by if-block.
if getattr(layer, '__name__', None) == '<lambda>':
rep = inspect.getsource(layer).strip().rstrip(',')
else:
rep = str(layer)
# Add indentation to each line.
rep = '({name}): {rep},'.format(name=name, rep=rep)
for line in rep.splitlines():
reps.append(' {line}\n'.format(line=line))
reps = ''.join(reps)
if reps: # No newline with no layers.
reps = '\n' + reps

return '{cls}({layers})'.format(
cls=self.__class__.__name__, layers=reps,
)
25 changes: 25 additions & 0 deletions tests/links_tests/model_tests/test_pickable_sequential_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,31 @@ def test_deletion_gpu(self):
self.check_deletion()


class TestPickableSequentialChainStr(unittest.TestCase):

def test_str(self):
self.l = PickableSequentialChain()
with self.l.init_scope():
for i in range(2):
setattr(
self.l, 'l{}'.format(i),
ConstantStubLink(np.random.uniform(size=(1, 3, 24, 24))))
setattr(
self.l, 'b{}'.format(i),
ConstantStubLink(np.random.uniform(size=(1, 3, 24, 24))))
self.assertEqual(
str(self.l),
'''\
PickableSequentialChain(
(l0): ConstantStubLink(),
(b0): ConstantStubLink(),
(l1): ConstantStubLink(),
(b1): ConstantStubLink(),
)''',
)
print(str(self.l))


@testing.parameterize(
{'pick': None},
{'pick': 'f2'},
Expand Down