In [1]:
from pyspark import SparkContext
sc = SparkContext(master = 'local')
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
In [2]:
cuse = spark.read.csv('data/cuse_binary.csv', header=True, inferSchema=True)
cuse.show(5)
In [7]:
from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler
from pyspark.ml import Pipeline
categorical_columns = cuse.columns[:-1]
categorical_columns
Out[7]:
In [9]:
stringindexer_stages = [StringIndexer(inputCol=c, outputCol='stringindexed_' + c) for c in categorical_columns]
# encode label column and add it to stringindexer stages
stringindexer_stages += [StringIndexer(inputCol='y', outputCol='label')]
In [10]:
onehotencoder_stages = [OneHotEncoder(inputCol='stringindexed_' + c, outputCol='onehot_'+c) for c in categorical_columns]
In [13]:
feature_columns = ['onehot_' + c for c in categorical_columns]
vectorassembler_stage = VectorAssembler(inputCols=feature_columns, outputCol='features')
In [15]:
all_stages = stringindexer_stages + onehotencoder_stages + [vectorassembler_stage]
pipeline = Pipeline(stages=all_stages)
In [17]:
pipeline_model = pipeline.fit(cuse)
In [19]:
final_columns = feature_columns + ['features', 'label']
cuse_df = pipeline_model.transform(cuse).select(final_columns)
cuse_df.show(5)
In [20]:
train, test = cuse_df.randomSplit([0.8, 0.2], seed=1234)
In [22]:
from pyspark.ml.classification import RandomForestClassifier
random_forest = RandomForestClassifier(featuresCol='features', labelCol='label')
In [23]:
from pyspark.ml.tuning import ParamGridBuilder
param_grid = ParamGridBuilder().\
addGrid(random_forest.maxDepth, [2, 3, 4]).\
addGrid(random_forest.minInfoGain, [0.0, 0.1, 0.2, 0.3]).\
build()
In [24]:
from pyspark.ml.evaluation import BinaryClassificationEvaluator
evaluator = BinaryClassificationEvaluator()
In [27]:
from pyspark.ml.tuning import CrossValidator
crossvalidation = CrossValidator(estimator=random_forest, estimatorParamMaps=param_grid, evaluator=evaluator)
In [29]:
crossvalidation_mod = crossvalidation.fit(cuse_df)
In [30]:
pred_train = crossvalidation_mod.transform(train)
pred_train.show(5)
In [31]:
pred_test = crossvalidation_mod.transform(test)
pred_test.show(5)
In [39]:
print('Accuracy on training data (areaUnderROC): ', evaluator.setMetricName('areaUnderROC').evaluate(pred_train), "\n"
'Accuracy on training data (areaUnderROC): ', evaluator.setMetricName('areaUnderROC').evaluate(pred_test))
In [43]:
label_pred_train = pred_train.select('label', 'prediction')
label_pred_train.rdd.zipWithIndex().countByKey()
Out[43]:
In [44]:
label_pred_test = pred_test.select('label', 'prediction')
label_pred_test.rdd.zipWithIndex().countByKey()
Out[44]:
In [47]:
print('max depth: ', crossvalidation_mod.bestModel._java_obj.getMaxDepth(), "\n",
'min information gain: ', crossvalidation_mod.bestModel._java_obj.getMinInfoGain())
In [ ]: