forked from pykeen/pykeen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.py
175 lines (136 loc) 路 4.82 KB
/
file.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# -*- coding: utf-8 -*-
"""Tracking results in local files."""
import csv
import datetime
import json
import logging
import pathlib
from typing import Any, ClassVar, Mapping, Optional, TextIO, Union
from .base import ResultTracker
from ..constants import PYKEEN_LOGS
from ..utils import flatten_dictionary, normalize_path
__all__ = [
"FileResultTracker",
"CSVResultTracker",
"JSONResultTracker",
]
logger = logging.getLogger(__name__)
def _format_key(key: str, prefix: Optional[str] = None) -> str:
"""Prepend prefix is necessary."""
if prefix is None:
return key
return f"{prefix}.{key}"
class FileResultTracker(ResultTracker):
"""Tracking results to a file.
Also allows monitoring experiments, e.g. by
.. code-block::
tail -f results.txt | grep "hits_at_10"
"""
#: The file extension for this writer (do not include dot)
extension: ClassVar[str]
#: The file where the results are written to.
file: TextIO
def __init__(
self,
path: Union[None, str, pathlib.Path] = None,
name: Optional[str] = None,
):
"""Initialize the tracker.
:param path:
The path of the log file.
:param name: The default file name for a file if no path is given. If no default is given,
the current time is used.
"""
if name is None:
name = datetime.datetime.now().isoformat()
path = normalize_path(path, default=PYKEEN_LOGS.joinpath(f"{name}.{self.extension}"), mkdir=True, is_file=True)
logger.info(f"Logging to {path.as_uri()}.")
self.file = path.open(mode="w", newline="", encoding="utf8")
# docstr-coverage: inherited
def end_run(self, success: bool = True) -> None: # noqa: D102
self.file.close()
class CSVResultTracker(FileResultTracker):
"""Tracking results to a CSV file.
Also allows monitoring experiments, e.g. by
.. code-block::
tail -f results.txt | grep "hits_at_10"
"""
extension = "csv"
#: The column names
HEADER = "type", "step", "key", "value"
def __init__(
self,
path: Union[None, str, pathlib.Path] = None,
name: Optional[str] = None,
**kwargs,
):
"""Initialize the tracker.
:param path:
The path of the log file.
:param name: The default file name for a file if no path is given. If no default is given,
the current time is used.
:param kwargs:
Additional keyword based arguments forwarded to csv.writer.
"""
super().__init__(path=path, name=name)
self.csv_writer = csv.writer(self.file, **kwargs)
# docstr-coverage: inherited
def start_run(self, run_name: Optional[str] = None) -> None: # noqa: D102
self.csv_writer.writerow(self.HEADER)
# docstr-coverage: inherited
def _write(
self,
dictionary: Mapping[str, Any],
label: str,
step: Optional[int],
prefix: Optional[str],
) -> None: # noqa: D102
dictionary = flatten_dictionary(dictionary=dictionary, prefix=prefix)
self.csv_writer.writerows((label, step, key, value) for key, value in dictionary.items())
self.file.flush()
# docstr-coverage: inherited
def log_params(
self,
params: Mapping[str, Any],
prefix: Optional[str] = None,
) -> None: # noqa: D102
self._write(dictionary=params, label="parameter", step=0, prefix=prefix)
# docstr-coverage: inherited
def log_metrics(
self,
metrics: Mapping[str, float],
step: Optional[int] = None,
prefix: Optional[str] = None,
) -> None: # noqa: D102
self._write(dictionary=metrics, label="metric", step=step, prefix=prefix)
class JSONResultTracker(FileResultTracker):
"""Tracking results to a JSON lines file.
Also allows monitoring experiments, e.g. by
.. code-block::
tail -f results.txt | grep "hits_at_10"
"""
extension = "jsonl"
def _write(self, obj) -> None:
obj = obj.copy()
for key, value in obj.items():
# Check if value is JSON serializable
try:
json.dumps(value)
except TypeError:
obj[key] = value.__class__.__name__
print(json.dumps(obj), file=self.file, flush=True) # noqa:T201
# docstr-coverage: inherited
def log_params(
self,
params: Mapping[str, Any],
prefix: Optional[str] = None,
) -> None: # noqa: D102
self._write({"params": params, "prefix": prefix})
# docstr-coverage: inherited
def log_metrics(
self,
metrics: Mapping[str, float],
step: Optional[int] = None,
prefix: Optional[str] = None,
) -> None: # noqa: D102
self._write({"metrics": metrics, "prefix": prefix, "step": step})