-
Notifications
You must be signed in to change notification settings - Fork 7
/
Rapids_SVM.py
187 lines (148 loc) · 8.55 KB
/
Rapids_SVM.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
## Spark ML Support Vector Machines
from pyspark.sql import SparkSession
from pyspark.sql.types import *
from pyspark.sql.functions import trim
import pandas as pd
import cdsw
import time
import sys
#Check NVidia Rapids Jars
!ls -l $SPARK_RAPIDS_DIR
RapidJarDir = os.path.join(os.environ["SPARK_RAPIDS_DIR"])
RapidJars = [os.path.join(RapidJarDir, x) for x in os.listdir(RapidJarDir)]
RapidgetGPURespource = os.environ["SPARK_RAPIDS_DIR"] + "/getGpusResources.sh"
print(RapidJarDir)
print(RapidJars)
print(RapidgetGPURespource)
## Spark + Rapids on K8s
# Initialize Rapids Spark Session
spark = SparkSession.builder \
.appName("SVM - Rapids") \
.config("spark.plugins","com.nvidia.spark.SQLPlugin") \
.config("spark.rapids.sql.format.csv.read.enabled", "false") \
.config("spark.rapids.sql.enabled", "false") \
.config("spark.executor.resource.gpu.discoveryScript", RapidgetGPURespource) \
.config("spark.executor.resource.gpu.vendor","nvidia.com") \
.config("spark.task.resource.gpu.amount",".25") \
.config("spark.executor.cores","4") \
.config("spark.executor.memoryOverhead","4G") \
.config("spark.executor.resource.gpu.amount","1") \
.config("spark.executor.memory","2G") \
.config("spark.task.cpus","1") \
.config("spark.rapids.memory.pinnedPool.size","2G") \
.config("spark.locality.wait","0s") \
.config("spark.sql.files.maxPartitionBytes","512m") \
.config("spark.sql.shuffle.partitions","10") \
.config("spark.dynamicAllocation.enabled","False") \
.config("spark.jars", ",".join(RapidJars)) \
.config("spark.files", RapidgetGPURespource)\
.getOrCreate()
# Spark + Rapids Tuning Options
# .config("spark.plugins","com.nvidia.spark.SQLPlugin") \
# .config("spark.rapids.sql.format.csv.read.enabled", "false") \
# .config("spark.rapids.sql.enabled", "false") \
# .config("spark.executor.resource.gpu.discoveryScript", RapidgetGPURespource) \
# .config("spark.executor.resource.gpu.vendor","nvidia.com") \
# .config("spark.task.resource.gpu.amount",".25") \
# .config("spark.executor.cores","4") \
# .config("spark.executor.memoryOverhead","4G") \
# .config("spark.executor.resource.gpu.amount","1") \
# .config("spark.executor.memory","2G") \
# .config("spark.task.cpus","1") \
# .config("spark.rapids.memory.pinnedPool.size","2G") \
# .config("spark.locality.wait","0s") \
# .config("spark.sql.files.maxPartitionBytes","512m") \
# .config("spark.sql.shuffle.partitions","10") \
## Spark Version
spark.version
### Start Timer
startTime = time.process_time()
#Define Dataframe Schema
schemaData = StructType([StructField("state", StringType(), True),StructField("account_length", DoubleType(), True),StructField("area_code", StringType(), True),StructField("phone_number", StringType(), True),StructField("intl_plan", StringType(), True),StructField("voice_mail_plan", StringType(), True),StructField("number_vmail_messages", DoubleType(), True), StructField("total_day_minutes", DoubleType(), True), StructField("total_day_calls", DoubleType(), True), StructField("total_day_charge", DoubleType(), True), StructField("total_eve_minutes", DoubleType(), True), StructField("total_eve_calls", DoubleType(), True), StructField("total_eve_charge", DoubleType(), True), StructField("total_night_minutes", DoubleType(), True), StructField("total_night_calls", DoubleType(), True), StructField("total_night_charge", DoubleType(), True), StructField("total_intl_minutes", DoubleType(), True), StructField("total_intl_calls", DoubleType(), True), StructField("total_intl_charge", DoubleType(), True), StructField("number_customer_service_calls", DoubleType(), True), StructField("churned", StringType(), True)])
#Build Dataframe from File
raw_data = spark.read.schema(schemaData).csv('data/churn.all')
churn_data=raw_data.withColumn("intl_plan",trim(raw_data.intl_plan))
reduced_numeric_cols = ["account_length", "number_vmail_messages",
"total_day_charge", "total_eve_charge",
"total_night_charge", "total_intl_calls",
"total_intl_charge","number_customer_service_calls"]
reduced_numeric_cols1 = ["account_length", "number_vmail_messages", "total_day_calls",
"total_day_charge", "total_eve_calls", "total_eve_charge",
"total_night_calls", "total_night_charge", "total_intl_calls",
"total_intl_charge","number_customer_service_calls"]
#Review DataSet Balance
churn_data.registerTempTable("ChurnData")
sqlResult = spark.sql("SELECT churned, COUNT(churned) as Churned FROM ChurnData group by churned")
sqlResult.show()
#Feature Engineering
from pyspark.ml.feature import StringIndexer
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.feature import StandardScaler
#String to Index
label_indexer = StringIndexer(inputCol = 'churned', outputCol = 'label')
plan_indexer = StringIndexer(inputCol = 'intl_plan', outputCol = 'intl_plan_indexed')
input_cols=['intl_plan_indexed'] + reduced_numeric_cols
#Feature Vector Assembler
assembler = VectorAssembler(inputCols = input_cols, outputCol = 'features')
#Standard Scaler
scaler = StandardScaler(inputCol="features", outputCol="scaledFeatures",withStd=True, withMean=False)
#Configure Random Forest Classifier Model
from pyspark.ml import Pipeline
from pyspark.ml.classification import LinearSVC
#svmclassifier = LinearSVC(labelCol = 'label', featuresCol = 'scaledFeatures')
svmclassifier = LinearSVC(labelCol = 'label', featuresCol = 'features')
#Set Random Forest Pipeline Stages
#pipeline = Pipeline(stages=[plan_indexer, label_indexer, assembler, scaler, svmclassifier])
pipeline = Pipeline(stages=[plan_indexer, label_indexer, assembler, svmclassifier])
#Spilt Test and Train Sets
(train, test) = churn_data.randomSplit([0.75, 0.25])
#Spark Model Hyper Turning
from pyspark.ml.tuning import CrossValidator
from pyspark.ml.tuning import ParamGridBuilder
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
#Setting Random Forest Paramaters From Users
user_svm_param_maxIter = [16, 32, 64, 128]
user_svm_param_numFolds = 3
#Settings for Random Forest - Paramaters Grid Search
svm_paramGrid = ParamGridBuilder().addGrid(svmclassifier.maxIter, user_svm_param_maxIter).build()
evaluator = BinaryClassificationEvaluator()
multiEvaluator = MulticlassClassificationEvaluator()
#Setting Paramaters for Crossvalidation
svm_cv = CrossValidator( estimator=pipeline, evaluator=evaluator, estimatorParamMaps=svm_paramGrid, numFolds=user_svm_param_numFolds)
svm_cvmodel = svm_cv.fit(train)
#Evaluating Random Forest Model Performance
from pyspark.sql.functions import udf
svm_predictions = svm_cvmodel.transform(test)
auroc = evaluator.evaluate(svm_predictions, {evaluator.metricName: "areaUnderROC"})
aupr = evaluator.evaluate(svm_predictions, {evaluator.metricName: "areaUnderPR"})
"The AUROC is %s and the AUPR is %s" % (auroc, aupr)
f1score = multiEvaluator.evaluate(svm_predictions, {multiEvaluator.metricName: "f1"})
weightedPrecision = multiEvaluator.evaluate(svm_predictions, {multiEvaluator.metricName: "weightedPrecision"})
weightedRecall = multiEvaluator.evaluate(svm_predictions, {multiEvaluator.metricName: "weightedRecall"})
"The F1 score: %s the Weighted Precision: %s the Weighted Recall is %s" % (f1score, weightedPrecision, weightedRecall)
#Select the Random Forest Best Model after Crossvalidation
svmModel = svm_cvmodel.bestModel
bestSVMModel = svmModel.stages[-1]
#Retrieving Paramaters from the Best RF Model
param_BestModel_Iter = bestSVMModel._java_obj.getMaxIter()
### Stop Timer
stopTime = time.process_time()
elapsedTime = stopTime-startTime
"Elapsed Process Time: %0.8f" % (elapsedTime)
#Return Paramaters to CDSW User Interface
cdsw.track_metric("auroc", auroc)
cdsw.track_metric("aupr", aupr)
cdsw.track_metric("F1", f1score)
cdsw.track_metric("WeightedPrecision", weightedPrecision)
cdsw.track_metric("weightedRecall", weightedRecall)
cdsw.track_metric("maxIter",param_BestModel_Iter)
cdsw.track_metric("cvFolds",user_svm_param_numFolds)
cdsw.track_metric("ProcTime", elapsedTime)
from pyspark.mllib.evaluation import BinaryClassificationMetrics
labelPredictionSet = svm_predictions.select('prediction','label').rdd.map(lambda lp: (lp.prediction, lp.label))
metrics = BinaryClassificationMetrics(labelPredictionSet)
#Save SVM Model to Disk
svmModel.write().overwrite().save("models/spark/svm")
spark.stop()
## End of File