-
Notifications
You must be signed in to change notification settings - Fork 5
/
target.py
60 lines (46 loc) · 1.56 KB
/
target.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
import luigi
from luigi.parameter import _FrozenOrderedDict
import pickle
import json
import numpy as np
import pandas as pd
class ModelTarget(luigi.LocalTarget):
def __init__(self, model_class, *args, **kwargs):
super().__init__(*args, **kwargs)
self.model_class = model_class
def load(self):
return self.model_class.load(self.path)
def dump(self, obj):
self.makedirs()
obj.save(self.path)
class _WrappedJsonEncoder(json.JSONEncoder):
# hook json.dump to hundle with luigi's _FrozenOrderedDict
def default(self, obj):
if isinstance(obj, _FrozenOrderedDict):
return obj.get_wrapped()
return super().default(obj)
class JsonTarget(luigi.LocalTarget):
def load(self):
with self.open("r") as f:
return json.load(f)
def dump(self, obj):
self.makedirs()
with self.open("w") as f:
return json.dump(obj, f, sort_keys=True, indent=4, cls=_WrappedJsonEncoder)
class CsvTarget(luigi.LocalTarget):
def load(self, **kwargs):
if "index_col" not in kwargs:
kwargs["index_col"] = 0
with self.open("r") as f:
return pd.read_csv(f, **kwargs)
def dump(self, obj, **kwargs):
self.makedirs()
df = pd.DataFrame(obj)
with self.open("w") as f:
return df.to_csv(f, **kwargs)
class NpyTarget(luigi.LocalTarget):
def load(self, **kwargs):
return np.load(self.path)
def dump(self, ary):
self.makedirs()
np.save(self.path, np.asarray(ary))