📖 Scenario: You work as a data scientist at an online store. You have built a model to predict if a customer will buy a product (1) or not (0). Now, you want to check how good your model is by calculating some evaluation metrics.
🎯 Goal: Build a Spark DataFrame with actual and predicted labels, set a threshold for classification, calculate accuracy and precision, and print the results.
📋 What You'll Learn
Create a Spark DataFrame with columns actual and predicted with given values
Create a threshold variable called threshold with value 0.5
Calculate accuracy and precision using Spark DataFrame operations and filters
Print the accuracy and precision values
💡 Why This Matters
🌍 Real World
Model evaluation is essential in real-world projects to check if predictions are reliable before using them in business decisions.
💼 Career
Data scientists and machine learning engineers regularly calculate metrics like accuracy and precision to improve and validate their models.
Progress0 / 4 steps
1
Create the initial Spark DataFrame
Create a Spark DataFrame called df with two columns: actual and predicted. Use these exact values: actual = [1, 0, 1, 0, 1], predicted = [0.9, 0.4, 0.2, 0.3, 0.8].
Apache Spark
Hint
Use spark.createDataFrame with a list of tuples and column names.
2
Set the classification threshold
Create a variable called threshold and set it to 0.5. This threshold will decide if predicted values are classified as 1 or 0.
Apache Spark
Hint
Just assign 0.5 to a variable named threshold.
3
Calculate accuracy and precision
Using the DataFrame df and the threshold, create a new column predicted_label that is 1 if predicted >= threshold, else 0. Then calculate accuracy as the fraction of rows where actual equals predicted_label. Calculate precision as the fraction of rows where predicted_label is 1 and actual is also 1, divided by total rows where predicted_label is 1.
Apache Spark
Hint
Use withColumn and when to create predicted_label. Use filter and count() to calculate counts for accuracy and precision.
4
Print the accuracy and precision
Print the values of accuracy and precision using print. Format the output exactly as: Accuracy: {accuracy} and Precision: {precision} where the values are decimals.
Apache Spark
Hint
Use print(f"Accuracy: {accuracy}") and print(f"Precision: {precision}").
Practice
(1/5)
1. Which metric is commonly used to evaluate a classification model's accuracy in Apache Spark?
easy
A. R-squared
B. Root Mean Squared Error
C. Accuracy
D. Mean Absolute Error
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 C
Quick Check:
Classification accuracy = Accuracy [OK]
Hint: Use accuracy for classification, RMSE for regression [OK]
Common Mistakes:
Confusing regression metrics with classification
Using R-squared for classification
Choosing MAE for classification
2. Which of the following is the correct way to create a BinaryClassificationEvaluator in Spark to evaluate areaUnderROC?
easy
A. BinaryClassificationEvaluator(metric="areaUnderROC")
B. BinaryClassificationEvaluator(metricName="areaUnderROC")
C. BinaryClassificationEvaluator(metricName='accuracy')
D. BinaryClassificationEvaluator(metric='accuracy')
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 B
Quick Check:
Use metricName="areaUnderROC" in BinaryClassificationEvaluator [OK]
Hint: Use metricName, not metric, for evaluator metrics [OK]
Common Mistakes:
Using 'metric' instead of 'metricName'
Passing invalid metric names like 'accuracy'
Using single quotes inconsistently
3. Given the following Spark code, what will be the output of the evaluator?
from pyspark.ml.evaluation import RegressionEvaluator
evaluator = RegressionEvaluator(metricName="accuracy")
What is the cause of the error?
medium
A. "accuracy" is not a valid metric for RegressionEvaluator
B. RegressionEvaluator requires a DataFrame input
C. metricName parameter is misspelled
D. RegressionEvaluator cannot be imported from pyspark.ml.evaluation
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 A
Quick Check:
RegressionEvaluator metrics exclude accuracy [OK]
Hint: Use classification evaluator for accuracy metric [OK]
Common Mistakes:
Confusing metric names between evaluators
Assuming metricName typo causes error
Ignoring evaluator import errors
5. You have a Spark ML model for binary classification. You want to evaluate it using both areaUnderROC and F1 score. Which approach correctly evaluates both metrics on the same predictions DataFrame?
hard
A. Use BinaryClassificationEvaluator with metricName="areaUnderROC" and MulticlassClassificationEvaluator with metricName="f1"
B. Use BinaryClassificationEvaluator twice with metricName="areaUnderROC" and metricName="f1" respectively
C. Use RegressionEvaluator with metricName="areaUnderROC" and MulticlassClassificationEvaluator with metricName="f1"
D. Use MulticlassClassificationEvaluator twice with metricName="areaUnderROC" and metricName="f1"
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 A