We use model evaluation and metrics to check how well a machine learning model works. It helps us know if the model makes good predictions or needs improvement.
Model evaluation and metrics in Apache Spark
from pyspark.ml.evaluation import RegressionEvaluator, BinaryClassificationEvaluator, MulticlassClassificationEvaluator # Create evaluator object # For regression: evaluator = RegressionEvaluator(labelCol='label', predictionCol='prediction', metricName='rmse') # For binary classification: evaluator = BinaryClassificationEvaluator(labelCol='label', rawPredictionCol='rawPrediction', metricName='areaUnderROC') # For multiclass classification: evaluator = MulticlassClassificationEvaluator(labelCol='label', predictionCol='prediction', metricName='accuracy') # Evaluate metric metric_value = evaluator.evaluate(predictions)
Choose the evaluator based on your problem type: regression, binary classification, or multiclass classification.
Common metrics include RMSE for regression, area under ROC for binary classification, and accuracy for multiclass classification.
from pyspark.ml.evaluation import RegressionEvaluator evaluator = RegressionEvaluator(labelCol='label', predictionCol='prediction', metricName='rmse') rmse = evaluator.evaluate(predictions) print(f"Root Mean Squared Error (RMSE): {rmse}")
from pyspark.ml.evaluation import BinaryClassificationEvaluator evaluator = BinaryClassificationEvaluator(labelCol='label', rawPredictionCol='rawPrediction', metricName='areaUnderROC') auc = evaluator.evaluate(predictions) print(f"Area Under ROC: {auc}")
from pyspark.ml.evaluation import MulticlassClassificationEvaluator evaluator = MulticlassClassificationEvaluator(labelCol='label', predictionCol='prediction', metricName='accuracy') accuracy = evaluator.evaluate(predictions) print(f"Accuracy: {accuracy}")
This program trains a simple logistic regression model on sample data, makes predictions, and evaluates the model using the Area Under ROC metric.
from pyspark.sql import SparkSession from pyspark.ml.classification import LogisticRegression from pyspark.ml.evaluation import BinaryClassificationEvaluator # Start Spark session spark = SparkSession.builder.appName('ModelEvaluationExample').getOrCreate() # Create sample data training = spark.createDataFrame([ (1.0, [0.0, 1.1, 0.1]), (0.0, [2.0, 1.0, -1.0]), (0.0, [2.0, 1.3, 1.0]), (1.0, [0.0, 1.2, -0.5]) ], ['label', 'features']) # Train logistic regression model lr = LogisticRegression(maxIter=10, regParam=0.01) model = lr.fit(training) # Make predictions predictions = model.transform(training) # Evaluate model using Area Under ROC evaluator = BinaryClassificationEvaluator(labelCol='label', rawPredictionCol='rawPrediction', metricName='areaUnderROC') auc = evaluator.evaluate(predictions) print(f"Area Under ROC: {auc}") spark.stop()
Always use a separate test dataset for evaluation to get an honest measure of model performance.
Different metrics tell different stories; choose the one that fits your problem goal.
For classification, rawPredictionCol is often used for metrics like areaUnderROC, not predictionCol.
Model evaluation helps check how well a model predicts new data.
Use the right evaluator and metric for your problem type.
Evaluate on test data to avoid overestimating model quality.
Practice
Solution
Step 1: Understand classification metrics
Classification models predict categories, so accuracy measures correct predictions over total predictions.Step 2: Match metric to model type
Accuracy is the standard metric for classification, while RMSE, MAE, and R-squared are for regression.Final Answer:
Accuracy -> Option CQuick Check:
Classification accuracy = Accuracy [OK]
- Confusing regression metrics with classification
- Using R-squared for classification
- Choosing MAE for classification
Solution
Step 1: Recall evaluator syntax
BinaryClassificationEvaluator uses parameter metricName to specify the metric.Step 2: Check metric value
"areaUnderROC" is a valid metricName; accuracy is not valid for this evaluator.Final Answer:
BinaryClassificationEvaluator(metricName="areaUnderROC") -> Option BQuick Check:
Use metricName="areaUnderROC" in BinaryClassificationEvaluator [OK]
- Using 'metric' instead of 'metricName'
- Passing invalid metric names like 'accuracy'
- Using single quotes inconsistently
from pyspark.ml.evaluation import RegressionEvaluator predictions = spark.createDataFrame([ (3.0, 2.5), (5.0, 5.0), (2.5, 3.0), (7.0, 8.0) ], ["label", "prediction"]) evaluator = RegressionEvaluator(metricName="rmse") rmse = evaluator.evaluate(predictions) print(round(rmse, 2))
Solution
Step 1: Calculate squared errors
Errors: (3.0-2.5)^2=0.25, (5.0-5.0)^2=0, (2.5-3.0)^2=0.25, (7.0-8.0)^2=1.0Step 2: Compute RMSE
Mean squared error = (0.25+0+0.25+1.0)/4 = 0.375; RMSE = sqrt(0.375) ≈ 0.612Final Answer:
0.61 -> Option DQuick Check:
RMSE ≈ 0.61 [OK]
- Calculating mean absolute error instead of RMSE
- Forgetting to take square root
- Rounding errors
from pyspark.ml.evaluation import RegressionEvaluator evaluator = RegressionEvaluator(metricName="accuracy")What is the cause of the error?
Solution
Step 1: Check valid metrics for RegressionEvaluator
RegressionEvaluator supports metrics like rmse, mse, mae, r2 but not accuracy.Step 2: Identify error cause
Using "accuracy" causes an error because it is for classification, not regression.Final Answer:
"accuracy" is not a valid metric for RegressionEvaluator -> Option AQuick Check:
RegressionEvaluator metrics exclude accuracy [OK]
- Confusing metric names between evaluators
- Assuming metricName typo causes error
- Ignoring evaluator import errors
Solution
Step 1: Identify evaluators for each metric
areaUnderROC is supported by BinaryClassificationEvaluator; F1 score is supported by MulticlassClassificationEvaluator.Step 2: Combine evaluators correctly
Use BinaryClassificationEvaluator for areaUnderROC and MulticlassClassificationEvaluator for F1 on the same predictions DataFrame.Final Answer:
Use BinaryClassificationEvaluator with metricName="areaUnderROC" and MulticlassClassificationEvaluator with metricName="f1" -> Option AQuick Check:
BinaryClassificationEvaluator + MulticlassClassificationEvaluator = correct combo [OK]
- Using RegressionEvaluator for classification metrics
- Using BinaryClassificationEvaluator for F1 score
- Using MulticlassClassificationEvaluator for areaUnderROC
Ready to prove it?
Pass the test and this pattern moves unknown
