forked from awantik/pyspark-learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
all_state.py
407 lines (159 loc) · 9.67 KB
/
all_state.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import argparse
import re
from pyspark.sql import SparkSession
from pyspark.ml.feature import StringIndexer, VectorAssembler
from pyspark.ml.regression import RandomForestRegressor, RandomForestRegressionModel
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.tuning import ParamGridBuilder, CrossValidator
from pyspark.mllib.evaluation import RegressionMetrics
#
# Simple and silly solution for the "Allstate Claims Severity" competition on Kaggle
# Competition page: https://www.kaggle.com/c/allstate-claims-severity
#
def process(params):
#
# Initializing Spark session
#
sparkSession = (SparkSession.builder
.appName("AllstateClaimsSeverityRandomForestRegressor")
.getOrCreate())
#****************************
print("Loading input data")
#****************************
# if (params.trainInput.startswith("s3://")):
# sparkSession.conf.set("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
# sparkSession.conf.set("spark.hadoop.fs.s3a.access.key", params.s3AccessKey)
# sparkSession.conf.set("spark.hadoop.fs.s3a.secret.key", params.s3SecretKey)
#*************************************************
print("Reading data from train.csv file")
#*************************************************
trainInput = (sparkSession.read
.option("header", "true")
.option("inferSchema", "true")
.csv(params.trainInput)
.cache())
testInput = (sparkSession.read
.option("header", "true")
.option("inferSchema", "true")
.csv(params.testInput)
.cache())
#*****************************************
print("Preparing data for training model")
#*****************************************
data = (trainInput.withColumnRenamed("loss", "label")
.sample(False, params.trainSample))
[trainingData, validationData] = data.randomSplit([0.7, 0.3])
trainingData.cache()
validationData.cache()
testData = testInput.sample(False, params.testSample).cache()
#******************************************
print("Building Machine Learning pipeline")
#******************************************
#StringIndexer for categorical columns (OneHotEncoder should be evaluated as well)
isCateg = lambda c: c.startswith("cat")
categNewCol = lambda c: "idx_{0}".format(c) if (isCateg(c)) else c
stringIndexerStages = map(lambda c: StringIndexer(inputCol=c, outputCol=categNewCol(c))
.fit(trainInput.select(c).union(testInput.select(c))), filter(isCateg, trainingData.columns))
#Function to remove categorical columns with too many categories
removeTooManyCategs = lambda c: not re.match(r"cat(109$|110$|112$|113$|116$)", c)
#Function to select only feature columns (omit id and label)
onlyFeatureCols = lambda c: not re.match(r"id|label", c)
#Definitive set of feature columns
featureCols = map(categNewCol,
filter(onlyFeatureCols,
filter(removeTooManyCategs,
trainingData.columns)))
#VectorAssembler for training features
assembler = VectorAssembler(inputCols=featureCols, outputCol="features")
#Estimator algorithm
algo = RandomForestRegressor(featuresCol="features", labelCol="label")
stages = stringIndexerStages
stages.append(assembler)
stages.append(algo)
#Building the Pipeline for transformations and predictor
pipeline = Pipeline(stages=stages)
#*********************************************************
print("Preparing K-fold Cross Validation and Grid Search")
#*********************************************************
paramGrid = (ParamGridBuilder()
.addGrid(algo.numTrees, params.algoNumTrees)
.addGrid(algo.maxDepth, params.algoMaxDepth)
.addGrid(algo.maxBins, params.algoMaxBins)
.build())
cv = CrossValidator(estimator=pipeline,
evaluator=RegressionEvaluator(),
estimatorParamMaps=paramGrid,
numFolds=params.numFolds)
#**********************************************************
print("Training model with RandomForest algorithm")
#**********************************************************
cvModel = cv.fit(trainingData)
#********************************************************************
print("Evaluating model on train and test data and calculating RMSE")
#********************************************************************
trainPredictionsAndLabels = cvModel.transform(trainingData).select("label", "prediction").rdd
validPredictionsAndLabels = cvModel.transform(validationData).select("label", "prediction").rdd
trainRegressionMetrics = RegressionMetrics(trainPredictionsAndLabels)
validRegressionMetrics = RegressionMetrics(validPredictionsAndLabels)
bestModel = cvModel.bestModel
featureImportances = bestModel.stages[-1].featureImportances.toArray()
output = ("\n=====================================================================\n" +
"Param trainSample: {0}\n".format(params.trainSample) +
"Param testSample: {0}\n".format(params.testSample) +
"TrainingData count: {0}\n".format(trainingData.count()) +
"ValidationData count: {0}\n".format(validationData.count()) +
"TestData count: {0}\n".format(testData.count()) +
"=====================================================================\n" +
"Param algoNumTrees = {0}\n".format(",".join(params.algoNumTrees)) +
"Param algoMaxDepth = {0}\n".format(",".join(params.algoMaxDepth)) +
"Param algoMaxBins = {0}\n".format(",".join(params.algoMaxBins)) +
"Param numFolds = {0}\n".format(params.numFolds) +
"=====================================================================\n" +
"Training data MSE = {0}\n".format(trainRegressionMetrics.meanSquaredError) +
"Training data RMSE = {0}\n".format(trainRegressionMetrics.rootMeanSquaredError) +
"Training data R-squared = {0}\n".format(trainRegressionMetrics.r2) +
"Training data MAE = {0}\n".format(trainRegressionMetrics.meanAbsoluteError) +
"Training data Explained variance = {0}\n".format(trainRegressionMetrics.explainedVariance) +
"=====================================================================\n" +
"Validation data MSE = {0}\n".format(validRegressionMetrics.meanSquaredError) +
"Validation data RMSE = {0}\n".format(validRegressionMetrics.rootMeanSquaredError) +
"Validation data R-squared = {0}\n".format(validRegressionMetrics.r2) +
"Validation data MAE = {0}\n".format(validRegressionMetrics.meanAbsoluteError) +
"Validation data Explained variance = {0}\n".format(validRegressionMetrics.explainedVariance) +
"=====================================================================\n" +
# "CV params explained: ${cvModel.explainParams()}\n" +
# "RandomForest params explained: ${bestModel.stages[-1].explainParams()}\n" +
"RandomForest features importances:\n {0}\n".format("\n".join(map(lambda z: "{0} = {1}".format(str(z[0]),str(z[1])), zip(featureCols, featureImportances)))) +
"=====================================================================\n")
print(output)
#*****************************************
print("Run prediction over test dataset")
#*****************************************
#Predicts and saves file ready for Kaggle!
if params.outputFile:
(cvModel.transform(testData)
.select("id", "prediction")
.withColumnRenamed("prediction", "loss")
.coalesce(1)
.write.format("csv")
.option("header", "true")
.save(params.outputFile))
#
# entry point - main method
#
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# parser.add_argument("--s3AccessKey", help="The access key for S3", required=True)
# parser.add_argument("--s3SecretKey", help="The secret key for S3", required=True)
parser.add_argument("--trainInput", help="Path to file/directory for training data", required=True)
parser.add_argument("--testInput", help="Path to file/directory for test data", required=True)
parser.add_argument("--outputFile", help="Path to output file")
parser.add_argument("--algoNumTrees", nargs='+', type=int, help="One or more options for number of trees for RandomForest model. Default: 3", default=[3])
parser.add_argument("--algoMaxDepth", nargs='+', type=int, help="One or more values for depth limit. Default: 4", default=[4])
parser.add_argument("--algoMaxBins", nargs='+', type=int, help="One or more values for max bins for RandomForest model. Default: 32", default=[32])
parser.add_argument("--numFolds", type=int, help="Number of folds for K-fold Cross Validation. Default: 10", default=10)
parser.add_argument("--trainSample", type=float, help="Sample fraction from 0.0 to 1.0 for train data", default=1.0)
parser.add_argument("--testSample", type=float, help="Sample fraction from 0.0 to 1.0 for test data", default=1.0)
params = parser.parse_args()
process(params)