/
salted_demo.py
177 lines (124 loc) · 4.98 KB
/
salted_demo.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
176
177
# Copyright 2018 Scott Gorlin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A demo implementation of a Salted Graph workflow"""
from datetime import date
from hashlib import sha256
from luigi import DateIntervalParameter, DateParameter, FloatParameter, \
LocalTarget, Parameter, Task, build, format
from luigi.date_interval import Week
from luigi.task import flatten
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.externals import joblib
from sklearn.svm import SVC
def get_salted_version(task):
"""Create a salted id/version for this task and lineage
:returns: a unique, deterministic hexdigest for this task
:rtype: str
"""
msg = ""
# Salt with lineage
for req in flatten(task.requires()):
# Note that order is important and impacts the hash - if task
# requirements are a dict, then consider doing this is sorted order
msg += get_salted_version(req)
# Uniquely specify this task
msg += ','.join([
# Basic capture of input type
task.__class__.__name__,
# Change __version__ at class level when everything needs rerunning!
task.__version__,
] + [
# Depending on strictness - skipping params is acceptable if
# output already is partitioned by their params; including every
# param may make hash *too* sensitive
'{}={}'.format(param_name, repr(task.param_kwargs[param_name]))
for param_name, param in sorted(task.get_params())
if param.significant
]
)
return sha256(msg.encode()).hexdigest()
def salted_target(task, file_pattern, format=None, **kwargs):
"""A local target with a file path formed with a 'salt' kwarg
:rtype: LocalTarget
"""
return LocalTarget(file_pattern.format(
salt=get_salted_version(task)[:6], self=task, **kwargs
), format=format)
class Streams(Task):
date = DateParameter()
__version__ = '1.0'
def run(self):
# This really should be an external task, but for simplicity we'll make
# fake data
with self.output().open('w') as out_file:
df = pd.DataFrame(
{'artist':['Scott', 'Sally'],
'track':['Python on my mind', 'What I like about R']})
df.to_csv(out_file, sep='\t')
def output(self):
return LocalTarget('data/stream/{}.tsv'.format(self.date))
class AggregateArtists(Task):
date_interval = DateIntervalParameter()
__version__ = '1.2 - bugfix'
def output(self):
return salted_target(
self, "data/artist_streams_{self.date_interval}-{salt}.tsv")
def requires(self):
return [Streams(date=date) for date in self.date_interval]
def run(self):
dfs = []
for input in self.input():
with input.open('r') as in_file:
df = pd.read_csv(in_file, sep='\t')
dfs.append(df.groupby('artist').size().to_frame('count'))
together = pd.concat(dfs).reset_index().groupby('artist').sum()
with self.output().open('w') as out_file:
together.to_csv(out_file, sep='\t')
class SVCTask(Task):
__version__ = '1.0'
c = FloatParameter(default=100.)
gamma = FloatParameter(default=1.)
kernel = Parameter(default='rbf')
class TrainDigits(SVCTask):
def output(self):
return salted_target(self, 'data/model-{salt}.pkl', format=format.Nop)
def run(self):
# http://scikit-learn.org/stable/tutorial/basic/tutorial.html
digits = load_digits()
svc = SVC(C=self.c, gamma=self.gamma, kernel=self.kernel)
svc.fit(digits.data[::2], digits.target[::2])
with self.output().open('w') as f:
joblib.dump(svc, f, protocol=-1)
class PredictDigits(SVCTask):
def requires(self):
return self.clone(TrainDigits)
def output(self):
return salted_target(self, 'data/accuracy-{salt}.txt')
def run(self):
with self.input().open() as f:
svc = joblib.load(f)
digits = load_digits()
predictions = svc.predict(digits.data[1::2])
with self.output().open('w') as f:
f.write('Accuracy: {}'.format(
(predictions == digits.target[1::2]).mean()
))
if __name__ == '__main__':
agg = AggregateArtists(date_interval=Week.from_date(date(2018, 3, 7)))
# Choose some tasks/params to run, tweak versions, etc
build([
agg,
PredictDigits(),
], local_scheduler=True)