/
pipelines.py
378 lines (294 loc) · 12.3 KB
/
pipelines.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""Pipeline utility functions for API integration.
This module contains predefined pipelines for API integration.
Those pipelines are made to be used simply and effectively, however,
for more complex cases, it is suggested to build and optimize your own
pipeline from the blocks provided in this toolkit.
"""
import typing
import numpy as np
from sklearn.pipeline import Pipeline
from toolkit import preprocessing, transformers, utils
def get_preprocessing_pipeline(
nvd_attributes: list,
nltk_feed_attributes: list = None,
labeling_func: typing.Callable = None,
share_hooks=False) -> Pipeline:
"""Build the preprocessing pipeline using existing classifier.
The preprocessing pipeline takes as an input a list of CVE objects
and outputs labeled data ready for feature extraction.
*must be fit using `fit_transform` method.*
:param nvd_attributes: list, attributes to output by NVDPreprocessor
The attributes are outputed by NVDPreprocessor and passed
to FeatureExtractor.
:param nltk_feed_attributes: list, attributes for NLTKPreprocessor
List of attributes which will be fed to NLTKPreprocessor.
:param labeling_func: callable object to be used for labeling
The `labeling_func` is used to create a hook for `LabelPreprocessor`
(see `LabelPreprocessor` documentation for more info).
By default `toolkit.utils.find_` function is used for that purpose.
:param share_hooks: boolean, whether to reuse hooks
"""
if labeling_func is None:
labeling_func = utils.find_
return Pipeline(
steps=[
(
'nvd_feed_preprocessor',
preprocessing.NVDFeedPreprocessor(attributes=nvd_attributes)
),
(
'label_preprocessor',
preprocessing.LabelPreprocessor(
feed_attributes=['project', 'description'],
# output only description attribute for NLTK processing
output_attributes=nvd_attributes,
hook=transformers.Hook(key='label_hook',
func=labeling_func,
reuse=share_hooks)
),
),
(
'nltk_preprocessor',
preprocessing.NLTKPreprocessor(
feed_attributes=nltk_feed_attributes,
)
)
]
)
def get_training_pipeline(feature_hooks=None) -> Pipeline:
"""Build the simple training pipeline from FeatureExtractor and NBClassifier.
The pipeline expects as an input preprocessed data
and trains NBClassifier on that data.
*must be fit using `fit_transform` method.*
:param feature_hooks: dict, {feature_key: Hook}
to be used as an argument to `FeatureExtractor`
Specify features which should be extracted from the given set.
The hooks are called for each element of the set and return
corresponding features.
"""
return Pipeline(
steps=[
(
'feature_extractor',
transformers.FeatureExtractor(
feature_hooks=feature_hooks,
# make hooks sharable (useful if training pipeline was used before)
share_hooks=True
)
),
(
'classifier',
transformers.NBClassifier()
)
]
)
def get_full_training_pipeline(labeling_func: typing.Callable = None,
feature_hooks=None,
share_hooks=False) -> Pipeline:
"""Build the full training pipeline with no predefined attributes.
The pipeline accepts raw data, performs preprocessing and feature
extraction and trains NBClassifier on that data.
The customization of feed and output attributes is fully left to user.
It is necessary to provide `fit_params` when fitting, as this pipeline
does not contain any predefined arguments.
*must be fit using `fit_transform` method with `fit_params`*
:param feature_hooks: dict, {feature_key: Hook}
to be used as an argument to `FeatureExtractor`
Specify features which should be extracted from the given set.
The hooks are called for each element of the set and return
corresponding features.
:param labeling_func: callable object to be used for labeling
The `labeling_func` is used to create a hook for `LabelPreprocessor`
(see `LabelPreprocessor` documentation for more info).
By default `toolkit.utils.find_` function is used for that purpose.
:param share_hooks: boolean, whether to reuse hooks
:returns: Pipeline
"""
if labeling_func is None:
labeling_func = utils.find_
return Pipeline(
steps=[
(
'nvd_feed_preprocessor',
preprocessing.NVDFeedPreprocessor()
),
(
'label_preprocessor',
preprocessing.LabelPreprocessor(
hook=transformers.Hook(key='label_hook',
reuse=share_hooks,
func=labeling_func)
)
),
(
'nltk_preprocessor',
preprocessing.NLTKPreprocessor()
),
(
'feature_extractor',
transformers.FeatureExtractor(
feature_hooks=feature_hooks,
share_hooks=True
)
),
(
'classifier',
transformers.NBClassifier()
)
]
)
def get_prediction_pipeline(classifier: transformers.NBClassifier,
attributes: list = None,
feature_hooks: list = None) -> Pipeline:
"""Build the prediction pipeline using existing classifier.
*must be fit using `fit_predict` method.*
:param classifier: pre-trained NBClassifier
:param attributes: list, attributes for NLTKPreprocessor
List of attributes which will be extracted from NVD and passed to NLTK
preprocessor.
:param feature_hooks: dict, {feature_key: Hook}
to be used as an argument to `FeatureExtractor`
Specify features which should be extracted from the given set.
The hooks are called for each element of the set and return
corresponding features.
"""
return Pipeline(
steps=[
(
'nltk_preprocessor',
preprocessing.NLTKPreprocessor(
feed_attributes=attributes
)
),
(
'feature_extractor',
transformers.FeatureExtractor(
feature_hooks=feature_hooks,
# make hooks sharable (useful if training pipeline was used before)
share_hooks=True
)
),
(
'classifier',
classifier
)
]
)
def get_extraction_pipeline(attributes=None,
feature_hooks: list = None,
share_hooks=False) -> Pipeline:
"""Build the extraction pipeline.
:param attributes: list, attributes for NLTKPreprocessor
List of attributes which will be extracted from NVD and passed to NLTK
preprocessor.
:param feature_hooks: dict, {feature_key: Hook}
to be used as an argument to `FeatureExtractor`
Specify features which should be extracted from the given set.
The hooks are called for each element of the set and return
corresponding features.
:param share_hooks: boolean, whether to reuse hooks
"""
return Pipeline(
steps=[
(
'nvd_feed_preprocessor',
preprocessing.NVDFeedPreprocessor(attributes=attributes)
),
(
'nltk_preprocessor',
preprocessing.NLTKPreprocessor(
feed_attributes=attributes
)
),
(
'feature_extractor',
transformers.FeatureExtractor(
feature_hooks=feature_hooks,
# make hooks sharable (useful if training pipeline was used before)
share_hooks=share_hooks
)
),
]
)
def extract_features(data: typing.Union[list, np.ndarray],
attributes: list = None,
nvd_attributes: list = None,
nltk_feed_attributes: list = None,
share_hooks=True,
**kwargs):
"""Extract data by fitting the extraction pipeline.
:param data: input data to the pipeline
:param attributes: list, attributes for NLTKPreprocessor
List of attributes which will be extracted from NVD and passed to NLTK
preprocessor.
:param nvd_attributes: list, attributes to output by NVDPreprocessor
The attributes are outputed by NVDPreprocessor and passed
to FeatureExtractor.
By default same as `attributes`.
:param nltk_feed_attributes: list, attributes for NLTKPreprocessor
List of attributes which will be fed to NLTKPreprocessor.
By default same as `attributes`.
:param share_hooks: bool, whether to reuse hooks
:param kwargs: optional, key word arguments
:feature_hooks: list of feature hooks to be used for feature extraction
:returns: ndarray, featureset
"""
if not any([attributes, nvd_attributes, nltk_feed_attributes]):
raise ValueError("No attributes were provided.")
feature_hooks = kwargs.get('feature_hooks', None)
extraction_pipeline = get_extraction_pipeline(
feature_hooks=feature_hooks,
share_hooks=share_hooks
)
featureset = extraction_pipeline.fit_transform(
data,
# it is important not to filter the data by the handler here
nvd_feed_preprocessor__attributes=nvd_attributes or attributes,
nvd_feed_preprocessor__use_filter=False,
nltk_preprocessor__feed_attributes=nltk_feed_attributes or attributes,
nltk_preprocessor__output_attributes=nvd_attributes
)
return featureset
def extract_labeled_features(data: typing.Union[list, np.ndarray],
nvd_attributes: list,
nltk_feed_attributes: list = None,
feature_hooks: list = None,
labeling_func=None,
share_hooks=True) -> tuple:
"""Extract labeled features from input data.
Extracts labeled features by concatenating and fitting the preprocessing
and extraction pipeline.
This is a wrapper for simplification of preprocessing and feature extraction.
For full functionality it is suggested to build custom pipelines.
:param data: input data to the preprocessing pipeline
:param nvd_attributes: list, attributes to output by NVDPreprocessor
The attributes are outputed by NVDPreprocessor and passed
to FeatureExtractor.
:param nltk_feed_attributes: list, attributes for NLTKPreprocessor
List of attributes which will be fed to NLTKPreprocessor.
:param feature_hooks: List[Hook], hooks used for feature extraction
:param labeling_func: function used for labeling, passed to LabelPreprocessor
:param share_hooks: bool, whether to reuse hooks
:returns: tuple, (featureset, classification labels)
"""
nltk_feed_attributes = nltk_feed_attributes or []
prep_pipeline = get_preprocessing_pipeline(
nvd_attributes=nvd_attributes,
labeling_func=labeling_func,
share_hooks=share_hooks
)
steps, _ = list(zip(*prep_pipeline.steps))
fit_params = {
"%s__feed_attributes" % steps[2]: nltk_feed_attributes,
"%s__output_attributes" % steps[2]: nvd_attributes + ['label']
}
prep_data = prep_pipeline.fit_transform(
X=data,
**fit_params
)
# split the data
extractor = transformers.FeatureExtractor(
feature_hooks=feature_hooks
)
featuresets = extractor.fit_transform(X=prep_data)
return featuresets, np.array(prep_data)[:, -1]