Skip to content

Commit

Permalink
Add a minimally useful repr to NeuralNet.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamin-work authored and ottonemo committed Dec 6, 2017
1 parent 9eb1a6c commit 4bf56dd
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
25 changes: 25 additions & 0 deletions skorch/net.py
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,31 @@ def load_params(self, f):

self.module_.load_state_dict(model)

def __repr__(self):
params = self.get_params(deep=False)

to_include = ['module']
to_exclude = []
parts = [str(self.__class__) + ' (uninitialized) (']
if self.initialized_:
parts = [str(self.__class__) + ' (initialized) (']
to_include = ['module_']
to_exclude = ['module__']

for key, val in sorted(params.items()):
if not any(key.startswith(prefix) for prefix in to_include):
continue
if any(key.startswith(prefix) for prefix in to_exclude):
continue

val = str(val)
if '\n' in val:
val = '\n '.join(val.split('\n'))
parts.append(' {}={},'.format(key, val))

parts.append(')')
return '\n'.join(parts)


#######################
# NeuralNetClassifier #
Expand Down
49 changes: 49 additions & 0 deletions skorch/tests/test_net.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,55 @@ def test_net_initialized_with_initalized_dataset_and_kwargs_raises(
"Dataset arguments ({'foo': 123}) is not allowed.")
assert exc.value.args[0] == expected

def test_repr_uninitialized_works(self, net_cls, module_cls):
net = net_cls(
module_cls,
module__num_units=55,
)
result = net.__repr__()
expected = """<class 'skorch.net.NeuralNetClassifier'> (uninitialized) (
module=<class 'skorch.tests.test_net.MyClassifier'>,
module__num_units=55,
)"""
assert result == expected

def test_repr_initialized_works(self, net_cls, module_cls):
net = net_cls(
module_cls,
module__num_units=42,
)
net.initialize()
result = net.__repr__()
expected = """<class 'skorch.net.NeuralNetClassifier'> (initialized) (
module_=MyClassifier (
(dense0): Linear (20 -> 42)
(dropout): Dropout (p = 0.5)
(dense1): Linear (42 -> 10)
(output): Linear (10 -> 2)
),
)"""
assert result == expected

def test_repr_fitted_works(self, net_cls, module_cls, data):
X, y = data
net = net_cls(
module_cls,
module__num_units=11,
module__nonlin=nn.PReLU(),
)
net.fit(X[:50], y[:50])
result = net.__repr__()
expected = """<class 'skorch.net.NeuralNetClassifier'> (initialized) (
module_=MyClassifier (
(dense0): Linear (20 -> 11)
(nonlin): PReLU (1)
(dropout): Dropout (p = 0.5)
(dense1): Linear (11 -> 10)
(output): Linear (10 -> 2)
),
)"""
assert result == expected


class MyRegressor(nn.Module):
"""Simple regression module."""
Expand Down

0 comments on commit 4bf56dd

Please sign in to comment.