Skip to content

Commit 2597812

Browse files
committed
New JSON serializer
Signed-off-by: Jiri Podivin <[email protected]>
1 parent a4bdc10 commit 2597812

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/evaluate/saving.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,26 @@
44
import sys
55
from datetime import datetime
66
from pathlib import Path
7+
import numpy as np
78

89
from datasets.utils.filelock import FileLock
910

1011
from . import __version__
1112

1213

14+
class NpEncoder(json.JSONEncoder):
15+
"""Numpy aware JSON encoder.
16+
"""
17+
def default(self, o):
18+
if isinstance(o, np.floating):
19+
return float(o)
20+
if isinstance(o, np.integer):
21+
return int(o)
22+
if isinstance(o, np.ndarray):
23+
return o.tolist()
24+
return super().default(o)
25+
26+
1327
def save(path_or_file, **data):
1428
"""
1529
Saves results to a JSON file. Also saves system information such as current time, current commit
@@ -40,7 +54,7 @@ def save(path_or_file, **data):
4054

4155
with FileLock(str(file_path) + ".lock"):
4256
with open(file_path, "w") as f:
43-
json.dump(data, f)
57+
json.dump(data, f, cls=NpEncoder)
4458

4559
# cleanup lock file
4660
try:

0 commit comments

Comments
 (0)