/
dataclasses_example.py
76 lines (58 loc) · 2.04 KB
/
dataclasses_example.py
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
70
71
72
73
74
75
76
""" Example describing dataclasses and how simple-parsing can be used to create
command-line arguments from them.
"""
from dataclasses import dataclass
@dataclass
class Point:
x: float = 1.2
y: float = 4.5
# This generates the following method (among others):
# def __init__(self, x: float = 1.2, y: float = 4.5):
# self.x = x
# self.y = y
if __name__ == "__main__":
p1 = Point(0, 0)
print(p1)
expected = "Point(x=0, y=0)"
#
# Second example: HyperParameters with simple-parsing:
#
from simple_parsing import ArgumentParser
from simple_parsing.helpers import choice
@dataclass
class HParams:
"""Hyper-Parameters of my model."""
# Learning rate.
learning_rate: float = 3e-4
# L2 regularization coefficient.
weight_decay: float = 1e-6
# Choice of optimizer
optimizer: str = choice("adam", "sgd", "rmsprop", default="sgd")
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_arguments(HParams, "hparams")
parser.print_help()
import textwrap
expected += textwrap.dedent(
"""\
usage: dataclasses_example.py [-h] [--learning_rate float]
[--weight_decay float]
[--optimizer {adam,sgd,rmsprop}]
optional arguments:
-h, --help show this help message and exit
HParams ['hparams']:
Hyper-Parameters of my model.
--learning_rate float, --hparams.learning_rate float
Learning rate. (default: 0.0003)
--weight_decay float, --hparams.weight_decay float
L2 regularization coefficient. (default: 1e-06)
--optimizer {adam,sgd,rmsprop}, --hparams.optimizer {adam,sgd,rmsprop}
Choice of optimizer (default: sgd)
"""
)
args = parser.parse_args("")
hparams: HParams = args.hparams
print(hparams)
expected += """\
HParams(learning_rate=0.0003, weight_decay=1e-06, optimizer='sgd')
"""