Split the Data
It is common practice when building machine learning models to split the source data, using some of it to train the model and reserving some to test the trained model. In this project, you will use 70% of the data for training, and reserve 30% for testing.
%scala val splits = DrugsFinalDF.randomSplit(Array(0.7, 0.3)) val train = splits(0) val test = splits(1) val train_rows = train.count() val test_rows = test.count() println("Training Rows: " + train_rows + " Testing Rows: " + test_rows)
Prepare the Training Data
To train the Classification model, you need a training data set that includes a vector of numeric features, and a label column. In this project, you will use the VectorAssembler class to transform the feature columns into a vector, and then rename the drug_indexed column to the label.
VectorAssembler()
VectorAssembler(): is a transformer that combines a given list of columns into a single vector column. It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models like logistic regression and decision trees.
VectorAssembler accepts the following input column types: all numeric types, boolean type, and vector type.
In each row, the values of the input columns will be concatenated into a vector in the specified order.
%scala import org.apache.spark.ml.feature.VectorAssembler val assembler = new VectorAssembler().setInputCols(Array("Age", "Sex_indexed", "BP_indexed", "Cholesterol_indexed", "Na_to_K")).setOutputCol("features") val training = assembler.transform(train).select($"features", $"Drug_indexed".alias("label")) training.show(false) Output: +-------------------------+-----+ |features |label| +-------------------------+-----+ |[15.0,1.0,0.0,1.0,16.725]|0.0 | |[15.0,0.0,0.0,1.0,17.206]|0.0 | |[17.0,0.0,2.0,1.0,10.832]|1.0 | |[18.0,1.0,0.0,0.0,37.188]|0.0 | |[18.0,1.0,0.0,1.0,24.276]|0.0 | |[18.0,1.0,2.0,1.0,8.75] |1.0 | |[19.0,1.0,0.0,0.0,13.313]|2.0 | |[19.0,1.0,0.0,1.0,25.969]|0.0 | |[20.0,1.0,0.0,0.0,11.262]|2.0 | |[20.0,1.0,1.0,1.0,11.686]|1.0 | |[20.0,1.0,2.0,1.0,9.281] |1.0 | |[20.0,0.0,0.0,1.0,35.639]|0.0 | |[21.0,1.0,0.0,1.0,28.632]|0.0 | |[22.0,1.0,0.0,1.0,22.818]|0.0 | |[22.0,1.0,2.0,0.0,8.607] |1.0 | |[22.0,0.0,0.0,1.0,28.294]|0.0 | |[22.0,0.0,1.0,0.0,8.151] |4.0 | |[22.0,0.0,2.0,0.0,11.953]|1.0 | |[23.0,1.0,0.0,0.0,25.355]|0.0 | |[23.0,0.0,1.0,0.0,7.298] |4.0 | +-------------------------+-----+ only showing top 20 rows
Train a Classification Model
Next, you need to train a Classification model using the training data. To do this, create an instance of the LogisticRegression algorithm you want to use and use its fit method to train a model based on the training DataFrame. In this project, you will use a Logistic Regression Classifier algorithm – though you can use the same technique for any of the regression algorithms supported in the spark.ml API
%scala import org.apache.spark.ml.classification.LogisticRegression val lr = new LogisticRegression().setLabelCol("label").setFeaturesCol("features").setMaxIter(10).setRegParam(0.3) val model = lr.fit(training) println ("Model trained!")
Prepare the Testing Data
Now that you have a trained model, you can test it using the testing data you reserved previously. First, you need to prepare the testing data in the same way as you did the training data by transforming the feature columns into a vector. This time you’ll rename the drug_indexed column to trueLabel.
%scala val testing = assembler.transform(test).select($"features", $"Drug_indexed".alias("trueLabel")) testing.show(false) Output: +-------------------------+---------+ |features |trueLabel| +-------------------------+---------+ |[15.0,0.0,2.0,0.0,9.084] |1.0 | |[16.0,1.0,0.0,1.0,15.516]|0.0 | |[16.0,0.0,0.0,1.0,19.007]|0.0 | |[16.0,0.0,1.0,0.0,12.006]|4.0 | |(5,[0,4],[23.0,8.011]) |2.0 | |[23.0,0.0,2.0,1.0,14.02] |1.0 | |[24.0,1.0,0.0,1.0,18.457]|0.0 | |[25.0,0.0,2.0,0.0,19.011]|0.0 | |[28.0,1.0,2.0,0.0,7.798] |1.0 | |[31.0,0.0,0.0,1.0,11.871]|2.0 | |[32.0,1.0,0.0,1.0,10.292]|2.0 | |[32.0,1.0,0.0,1.0,25.974]|0.0 | |[32.0,1.0,1.0,0.0,9.712] |4.0 | |[32.0,1.0,1.0,1.0,10.84] |1.0 | |[35.0,0.0,1.0,1.0,9.17] |1.0 | |[36.0,1.0,0.0,0.0,11.198]|2.0 | |[38.0,1.0,1.0,1.0,29.875]|0.0 | |[39.0,1.0,2.0,1.0,17.225]|0.0 | |(5,[0,4],[40.0,27.826]) |0.0 | |[41.0,1.0,2.0,1.0,22.905]|0.0 | +-------------------------+---------+ only showing top 20 rows
Test the Model
Now you’re ready to use the transform method of the model to generate some predictions. You can use this approach to predict the drug_indexed; but in this case, you are using the test data which includes a known true label value, so you can compare the drug_indexed
%scala val prediction = model.transform(testing) val predicted = prediction.select("features", "prediction", "probability", "trueLabel") predicted.show(10) Output: +--------------------+----------+--------------------+---------+ | features|prediction| probability|trueLabel| +--------------------+----------+--------------------+---------+ |[15.0,0.0,2.0,0.0...| 1.0|[0.21850356537241...| 1.0| |[16.0,1.0,0.0,1.0...| 0.0|[0.44835442092612...| 0.0| |[16.0,0.0,0.0,1.0...| 0.0|[0.53813141818942...| 0.0| |[16.0,0.0,1.0,0.0...| 0.0|[0.32740074405493...| 4.0| |(5,[0,4],[23.0,8....| 2.0|[0.24233238390848...| 2.0| |[23.0,0.0,2.0,1.0...| 1.0|[0.32200810870422...| 1.0| |[24.0,1.0,0.0,1.0...| 0.0|[0.54454179979397...| 0.0| |[25.0,0.0,2.0,0.0...| 0.0|[0.49952181301264...| 0.0| |[28.0,1.0,2.0,0.0...| 1.0|[0.20032783361260...| 1.0| |[31.0,0.0,0.0,1.0...| 0.0|[0.34764491763299...| 2.0| +--------------------+----------+--------------------+---------+
Evaluating a Model (We got 68% Accuracy)
%scala import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator val evaluator = new MulticlassClassificationEvaluator() .setLabelCol("trueLabel") .setPredictionCol("prediction") .setMetricName("accuracy") val accuracy = evaluator.evaluate(prediction) Output: import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator evaluator: org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator = MulticlassClassificationEvaluator: uid=mcEval_4e65e1635ecf, metricName=accuracy, metricLabel=0.0, beta=1.0, eps=1.0E-15 accuracy: Double = 0.6851851851851852
val tp = predicted.filter("prediction == 1 AND truelabel == 1").count().toFloat val fp = predicted.filter("prediction == 1 AND truelabel == 0").count().toFloat val tn = predicted.filter("prediction == 0 AND truelabel == 0").count().toFloat val fn = predicted.filter("prediction == 0 AND truelabel == 1").count().toFloat val metrics = spark.createDataFrame(Seq( ("TP", tp), ("FP", fp), ("TN", tn), ("FN", fn), ("Precision", tp / (tp + fp)), ("Recall", tp / (tp + fn)))).toDF("metric", "value") metrics.show() Output: +---------+----------+ | metric| value| +---------+----------+ | TP| 14.0| | FP| 1.0| | TN| 22.0| | FN| 2.0| |Precision|0.93333334| | Recall| 0.875| +---------+----------+ tp: Float = 14.0 fp: Float = 1.0 tn: Float = 22.0 fn: Float = 2.0