Challenge - 5 Problems
Model Evaluation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateCalculate accuracy of a binary classifier in Spark
Given the following Spark code that evaluates a binary classification model, what is the printed accuracy?
Apache Spark
from pyspark.sql import SparkSession from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml.linalg import Vectors from pyspark.sql import Row spark = SparkSession.builder.master('local').appName('Eval').getOrCreate() data = [ Row(label=1.0, features=Vectors.dense([0.5, 1.0])), Row(label=0.0, features=Vectors.dense([1.5, 2.0])), Row(label=1.0, features=Vectors.dense([1.0, 1.0])), Row(label=0.0, features=Vectors.dense([2.0, 3.0])) ] df = spark.createDataFrame(data) # Simulate predictions predictions = df.withColumn('prediction', df.label) evaluator = BinaryClassificationEvaluator(rawPredictionCol='prediction', labelCol='label', metricName='areaUnderROC') accuracy = predictions.filter(predictions.label == predictions.prediction).count() / predictions.count() print(f"Accuracy: {accuracy}")
Attempts:
2 left
💡 Hint
Check how many rows have prediction equal to label.
✗ Incorrect
Since prediction column is set equal to label, all predictions match labels, so accuracy is 1.0.
❓ data_output
intermediateConfusion matrix counts from Spark DataFrame
Given a Spark DataFrame with columns 'label' and 'prediction' as below, what is the count of true positives (TP)?
Apache Spark
from pyspark.sql import SparkSession from pyspark.sql.functions import col spark = SparkSession.builder.master('local').appName('Confusion').getOrCreate() data = [ (1.0, 1.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0) ] df = spark.createDataFrame(data, ['label', 'prediction']) # Count true positives TP = df.filter((col('label') == 1.0) & (col('prediction') == 1.0)).count() print(f"True Positives: {TP}")
Attempts:
2 left
💡 Hint
True positives are rows where label and prediction both are 1.0.
✗ Incorrect
Rows 1 and 4 have label=1.0 and prediction=1.0, so TP=2.
❓ visualization
advancedROC curve plot from Spark model predictions
You have a Spark DataFrame with columns 'label' and 'rawPrediction' (score). Which code snippet correctly plots the ROC curve using matplotlib?
Apache Spark
import matplotlib.pyplot as plt from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.sql.functions import vector_to_array, col # Assume df_predictions has columns 'label' and 'rawPrediction' (vector of two scores) # Extract probability of positive class prob_df = df_predictions.withColumn('probability', vector_to_array(col('rawPrediction'))[1]) # Collect label and probability to driver labels_probs = prob_df.select('label', 'probability').collect() labels = [row['label'] for row in labels_probs] probs = [row['probability'] for row in labels_probs] # Compute ROC points from sklearn.metrics import roc_curve fpr, tpr, _ = roc_curve(labels, probs) # Plot ROC plt.plot(fpr, tpr, label='ROC curve') plt.plot([0, 1], [0, 1], 'k--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.legend() plt.show()
Attempts:
2 left
💡 Hint
RawPrediction is a vector; extract positive class score before plotting.
✗ Incorrect
RawPrediction is a vector of scores; we must extract the positive class score to compute ROC. Then use sklearn to compute ROC points and matplotlib to plot.
🧠 Conceptual
advancedUnderstanding Precision-Recall tradeoff
In a binary classification task with imbalanced classes, which statement best explains why precision-recall curves are preferred over ROC curves?
Attempts:
2 left
💡 Hint
Think about what happens when negative class is much larger than positive class.
✗ Incorrect
ROC curves can be overly optimistic with imbalanced data because true negative rate dominates. Precision-recall curves highlight performance on positive class.
🔧 Debug
expertIdentify error in Spark model evaluation code
What error will the following Spark code raise when evaluating a regression model's RMSE?
Apache Spark
from pyspark.ml.evaluation import RegressionEvaluator # Assume predictions DataFrame has columns 'label' and 'prediction' evaluator = RegressionEvaluator(labelCol='label', predictionCol='prediction', metricName='rmse') rmse = evaluator.evaluate(predictions) print(f"RMSE: {rmse}") # But predictions DataFrame is empty
Attempts:
2 left
💡 Hint
Think about what happens if the DataFrame has no rows.
✗ Incorrect
RegressionEvaluator requires non-empty DataFrame to compute metrics. Empty DataFrame causes IllegalArgumentException in Spark.
