-
Notifications
You must be signed in to change notification settings - Fork 117
/
pipeline.py
294 lines (255 loc) · 12.4 KB
/
pipeline.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# Standard imports
from pymongo import MongoClient
import logging
import sys
import os
import numpy as np
import scipy as sp
import time
import json
# Our imports
import emission.storage.timeseries.abstract_timeseries as esta
import emission.storage.decorations.analysis_timeseries_queries as esda
import emission.storage.decorations.trip_queries as esdt
import emission.storage.pipeline_queries as epq
import emission.analysis.section_features as easf
import emission.core.get_database as edb
import emission.core.wrapper.entry as ecwe
import emission.core.wrapper.modeprediction as ecwm
from uuid import UUID
# We are not going to use the feature matrix for analysis unless we have at
# least 50 points in the training set. 50 is arbitrary. We could also consider
# combining the old and new training data, but this is really a bootstrapping
# problem, so we don't need to solve it right now.
minTrainingSetSize = 1000
def predictMode(user_id):
time_query = epq.get_time_range_for_segmentation(user_id)
try:
mip = ModeInferencePipeline()
mip.runPredictionPipeline(user_id, time_query)
if mip.getLastTimestamp() == 0:
logging.debug("after, run, last_timestamp == 0, must be early return")
epq.mark_mode_inference_done(user_id, None)
return
else:
epq.mark_mode_inference_done(user_id, mip.getLastTimestamp())
except:
epq.mark_mode_inference_failed(user_id)
class ModeInferencePipeline:
def __init__(self):
self.featureLabels = ["distance", "duration", "first filter mode", "sectionId", "avg speed",
"speed EV", "speed variance", "max speed", "max accel", "isCommute",
"heading change rate", "stop rate", "velocity change rate",
"start lat", "start lng", "stop lat", "stop lng",
"start hour", "end hour", "close to bus stop", "close to train stop",
"close to airport"]
self.last_timestamp = 0
with open("emission/analysis/classification/inference/mode/mode_id_old2new.txt") as fp:
self.seed_modes_mapping = json.load(fp)
logging.debug("Loaded modes %s" % self.seed_modes_mapping)
def getLastTimestamp(self):
return self.last_timestamp
# At this point, none of the clients except for CCI are supporting ground
# truth, and even cci is only supporting trip-level ground truth. So this
# version of the pipeline will just load a previously created model, that was
# created from the small store of data that we do have ground truth for, and
# we documented to have ~ 70% accuracy in the 2014 e-mission paper.
def runPredictionPipeline(self, uuid, timerange):
ts = esta.TimeSeries.get_time_series(user_id)
toPredictTrips_it = ts.find_entries(['analysis/cleaned_section'], time_query=timerange)
if (toPredictTrips_it.count() == 0):
logging.debug("toPredictTrips_it.count() == 0, early return")
return None
self.loadModelStage()
logging.info("loadModelStage DONE")
(self.toPredictFeatureMatrix, self.tripIds, self.sectionIds) = \
self.generateFeatureMatrixAndIDsStep(toPredictTrips_it)
logging.info("generateFeatureMatrixAndIDsStep DONE")
self.predictedProb = self.predictModesStep()
#This is a matrix of the entries and their corresponding probabilities for each classification
logging.info("predictModesStep DONE")
self.savePredictionsStep()
logging.info("savePredictionsStep DONE")
def loadModelStage(self):
# TODO: Consider removing this import by moving the model save/load code to
# its own module so that we can eventually remove the old pipeline code
import emission.analysis.classification.inference.mode.seed.pipeline as seedp
self.model = seedp.ModeInferencePipelineMovesFormat.loadModel()
# Features are:
# 0. distance
# 1. duration
# 2. first filter mode
# 3. sectionId
# 4. avg speed
# 5. speed EV
# 6. speed variance
# 7. max speed
# 8. max accel
# 9. isCommute
# 10. heading change rate (currently unfilled)
# 11. stop rate (currently unfilled)
# 12. velocity change rate (currently unfilled)
# 13. start lat
# 14. start lng
# 15. stop lat
# 16. stop lng
# 17. start hour
# 18. end hour
# 19. both start and end close to bus stop
# 20. both start and end close to train station
# 21. both start and end close to airport
def updateFeatureMatrixRowWithSection(self, featureMatrix, i, section_entry):
section = section_entry.data
featureMatrix[i, 0] = section.distance
featureMatrix[i, 1] = section.duration
featureMatrix[i, 2] = section.sensed_mode.value
featureMatrix[i, 3] = section['_id']
featureMatrix[i, 4] = easf.calOverallSectionSpeed(section)
speeds = section['speeds']
if speeds != None and len(speeds) > 0:
featureMatrix[i, 5] = np.mean(speeds)
featureMatrix[i, 6] = np.std(speeds)
featureMatrix[i, 7] = np.max(speeds)
else:
# They will remain zero
pass
accels = easf.calAccels(section)
if accels != None and len(accels) > 0:
featureMatrix[i, 8] = np.max(accels)
else:
# They will remain zero
pass
featureMatrix[i, 9] = False
featureMatrix[i, 10] = easf.calHCR(section_entry)
featureMatrix[i, 11] = easf.calSR(section_entry)
featureMatrix[i, 12] = easf.calVCR(section_entry)
if 'start_loc' in section and section['end_loc'] != None:
startCoords = section['start_loc']['coordinates']
featureMatrix[i, 13] = startCoords[0]
featureMatrix[i, 14] = startCoords[1]
if 'end_loc' in section and section['end_loc'] != None:
endCoords = section['end_loc']['coordinates']
featureMatrix[i, 15] = endCoords[0]
featureMatrix[i, 16] = endCoords[1]
featureMatrix[i, 17] = section['start_local_dt']['hour']
featureMatrix[i, 18] = section['end_local_dt']['hour']
if (hasattr(self, "bus_cluster")):
featureMatrix[i, 19] = easf.mode_start_end_coverage(section, self.bus_cluster,105)
if (hasattr(self, "train_cluster")):
featureMatrix[i, 20] = easf.mode_start_end_coverage(section, self.train_cluster,600)
if (hasattr(self, "air_cluster")):
featureMatrix[i, 21] = easf.mode_start_end_coverage(section, self.air_cluster,600)
if self.last_timestamp < section.end_ts:
self.last_timestamp = section.end_ts
# Replace NaN and inf by zeros so that it doesn't crash later
featureMatrix[i] = np.nan_to_num(featureMatrix[i])
def cleanDataStep(self):
runIndices = self.resultVector == 2
transportIndices = self.resultVector == 4
mixedIndices = self.resultVector == 8
airIndices = self.resultVector == 9
unknownIndices = self.resultVector == 0
strippedIndices = np.logical_not(runIndices | transportIndices | mixedIndices | unknownIndices)
logging.debug("Stripped trips with mode: run %s, transport %s, mixed %s, unknown %s unstripped %s" %
(np.count_nonzero(runIndices), np.count_nonzero(transportIndices),
np.count_nonzero(mixedIndices), np.count_nonzero(unknownIndices),
np.count_nonzero(strippedIndices)))
strippedFeatureMatrix = self.featureMatrix[strippedIndices]
strippedResultVector = self.resultVector[strippedIndices]
# In spite of stripping out the values, we see that there are clear
# outliers. This is almost certainly a mis-classified trip, because the
# distance and speed are both really large, but the mode is walking. Let's
# manually filter out this outlier.
distanceOutliers = strippedFeatureMatrix[:,0] > 500000
speedOutliers = strippedFeatureMatrix[:,4] > 100
speedMeanOutliers = strippedFeatureMatrix[:,5] > 80
speedVarianceOutliers = strippedFeatureMatrix[:,6] > 70
maxSpeedOutliers = strippedFeatureMatrix[:,7] > 160
logging.debug("Stripping out distanceOutliers %s, speedOutliers %s, speedMeanOutliers %s, speedVarianceOutliers %s, maxSpeedOutliers %s" %
(np.nonzero(distanceOutliers), np.nonzero(speedOutliers),
np.nonzero(speedMeanOutliers), np.nonzero(speedVarianceOutliers),
np.nonzero(maxSpeedOutliers)))
nonOutlierIndices = np.logical_not(distanceOutliers | speedOutliers | speedMeanOutliers | speedVarianceOutliers | maxSpeedOutliers)
logging.debug("nonOutlierIndices.shape = %s" % nonOutlierIndices.shape)
return (strippedFeatureMatrix[nonOutlierIndices],
strippedResultVector[nonOutlierIndices])
# Feature Indices
def selectFeatureIndicesStep(self):
genericFeatureIndices = list(xrange(0,10))
AdvancedFeatureIndices = list(xrange(10,13))
LocationFeatureIndices = list(xrange(13,17))
TimeFeatureIndices = list(xrange(17,19))
BusTrainFeatureIndices = list(xrange(19,22))
logging.debug("generic features = %s" % genericFeatureIndices)
logging.debug("advanced features = %s" % AdvancedFeatureIndices)
logging.debug("location features = %s" % LocationFeatureIndices)
logging.debug("time features = %s" % TimeFeatureIndices)
logging.debug("bus train features = %s" % BusTrainFeatureIndices)
return genericFeatureIndices + BusTrainFeatureIndices
def generateFeatureMatrixAndIDsStep(self, sectionQuery):
if isinstance(sectionQuery, basestring):
toPredictSections = self.Sections.find(sectionQuery)
numsections = toPredictSections.count()
else:
toPredictSections = list(sectionQuery)
numsections = len(toPredictSections)
logging.debug("Predicting values for %d sections" % numsections)
featureMatrix = np.zeros([numsections, len(self.featureLabels)])
sectionIds = []
tripIds = []
for (i, section) in enumerate(toPredictSections.limit(featureMatrix.shape[0]).batch_size(300)):
if i % 50 == 0:
logging.debug("Processing test record %s " % i)
self.updateFeatureMatrixRowWithSection(featureMatrix, i, section)
sectionIds.append(section['_id'])
tripIds.append(section['trip_id'])
return (featureMatrix[:,self.selFeatureIndices], tripIds, sectionIds)
def predictModesStep(self):
return self.model.predict_proba(self.toPredictFeatureMatrix)
# The current probability will only have results for values from the set of
# unique values in the resultVector. This means that the location of the
# highest probability is not a 1:1 mapping to the mode, which will probably
# have issues down the road. We are going to fix this here by storing the
# non-zero probabilities in a map instead of in a list. We used to have an
# list here, but we move to a map instead because we plan to support lots of
# different modes, and having an giant array consisting primarily of zeros
# doesn't sound like a great option.
# In other words, uniqueModes = [1, 5]
# predictedProb = [[1,0], [0,1]]
# allModes has length 8
# returns [{'walking': 1}, {'bus': 1}]
def convertPredictedProbToMap(self, uniqueModes, predictedProbArr):
currProbMap = {}
uniqueModesInt = [int(um) for um in uniqueModes]
logging.debug("predictedProbArr has %s non-zero elements" % np.count_nonzero(predictedProbArr))
logging.debug("uniqueModes are %s " % uniqueModesInt)
for (j, oldMode) in enumerate(uniqueModesInt):
if predictedProbArr[j] != 0:
uniqueMode = self.seed_modes_mapping[str(oldMode)]
modeName = ecwm.PredictedModeTypes(uniqueMode).name
logging.debug("Setting probability of mode %s (%s) to %s" %
(uniqueMode, modeName, predictedProbArr[j]))
currProbMap[modeName] = predictedProbArr[j]
return currProbMap
def savePredictionsStep(self):
from emission.core.wrapper.user import User
from emission.core.wrapper.client import Client
uniqueModes = sorted(set(self.cleanedResultVector))
for i in range(self.predictedProb.shape[0]):
currTripId = self.tripIds[i]
currSectionId = self.sectionIds[i]
currProb = self.convertPredictedProbToMap(uniqueModes, self.predictedProb[i])
logging.debug("Updating probability for section with id = %s" % currSectionId)
mp = ecwm.Modeprediction()
mp.trip_id = currTripId
mp.section_id = currSectionId
mp.algorithm_id = ecwm.AlgorithmTypes.SEED_RANDOM_FOREST
mp.predicted_mode = currProb
if __name__ == "__main__":
import json
config_data = json.load(open('config.json'))
log_base_dir = config_data['paths']['log_base_dir']
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
filename="%s/pipeline.log" % log_base_dir, level=logging.DEBUG)
modeInferPipeline = ModeInferencePipeline()
modeInferPipeline.runPipeline()