📖 Scenario: You are working as a data scientist on a project to predict if a person earns more than $50K a year based on census data. You want to build a machine learning model using Apache Spark's MLlib. To get the best model, you will tune the hyperparameters of a Decision Tree classifier using CrossValidator.
🎯 Goal: Build a Decision Tree classification model and use CrossValidator to find the best hyperparameters for maxDepth and maxBins. Finally, print the best model's parameters.
📋 What You'll Learn
Create a DataFrame with sample census data
Set up a Decision Tree classifier
Create a ParamGridBuilder with maxDepth and maxBins values
Use CrossValidator with a BinaryClassificationEvaluator
Print the best model's maxDepth and maxBins
💡 Why This Matters
🌍 Real World
Hyperparameter tuning helps improve machine learning model accuracy by finding the best settings automatically.
💼 Career
Data scientists and machine learning engineers use hyperparameter tuning with tools like Spark to build better predictive models at scale.
Progress0 / 4 steps
1
Create the initial DataFrame
Create a Spark DataFrame called data with these exact rows and columns: ("age", "education_num", "income") with values (25, 10, 0), (38, 13, 1), (28, 9, 0), (44, 10, 1), (18, 7, 0).
Apache Spark
Hint
Use spark.createDataFrame with a list of tuples and specify the column names as a list.
2
Set up the Decision Tree classifier and ParamGrid
Create a Decision Tree classifier called dt with label column income and features column features. Then create a ParamGridBuilder called paramGrid that sets maxDepth to [2, 3] and maxBins to [20, 30].
Apache Spark
Hint
Use DecisionTreeClassifier(labelCol="income", featuresCol="features") and ParamGridBuilder().addGrid(...).build().
3
Create the CrossValidator and fit the model
Create a CrossValidator called cv with estimator=dt, estimatorParamMaps=paramGrid, and a BinaryClassificationEvaluator with label column income. Then fit cv on a DataFrame called assembled_data that has a features vector column created from age and education_num.
Apache Spark
Hint
Use VectorAssembler to create features, then CrossValidator with the given parameters, and call fit().
4
Print the best model's hyperparameters
Print the best model's maxDepth and maxBins values from cvModel.bestModel using print statements.
Apache Spark
Hint
Use cvModel.bestModel._java_obj.getMaxDepth() and cvModel.bestModel._java_obj.getMaxBins() to get the values.
Practice
(1/5)
1. What is the main purpose of using CrossValidator in Apache Spark's machine learning pipeline?
easy
A. To visualize the model's performance metrics
B. To train the model on the entire dataset without validation
C. To clean and preprocess the input data
D. To find the best hyperparameters by testing multiple data splits
Solution
Step 1: Understand CrossValidator's role
CrossValidator splits data into training and validation sets multiple times to evaluate model performance.
Step 2: Identify the purpose of hyperparameter tuning
It tests different hyperparameter combinations to find the best model settings.
Final Answer:
To find the best hyperparameters by testing multiple data splits -> Option D
Quick Check:
CrossValidator = Best hyperparameters [OK]
Hint: CrossValidator tests parameters on data splits to find best model [OK]
Common Mistakes:
Thinking CrossValidator trains on full data without validation
Confusing CrossValidator with data cleaning tools
Assuming CrossValidator is for visualization only
2. Which of the following is the correct way to create a parameter grid using ParamGridBuilder in Spark ML?
easy
A. paramGrid = ParamGridBuilder().addGrid(model.maxDepth, [2, 5]).build()
B. paramGrid = ParamGridBuilder.addGrid(model.maxDepth, [2, 5]).build()
C. paramGrid = ParamGridBuilder().addGrid(model.maxDepth = [2, 5]).build()
D. paramGrid = ParamGridBuilder().addGrid([2, 5], model.maxDepth).build()
Solution
Step 1: Recall ParamGridBuilder syntax
ParamGridBuilder is instantiated, then addGrid is called with parameter and list of values.
Step 2: Check each option's syntax
paramGrid = ParamGridBuilder().addGrid(model.maxDepth, [2, 5]).build() correctly calls ParamGridBuilder() then addGrid(model.maxDepth, [2, 5]) and finally build().
Final Answer:
paramGrid = ParamGridBuilder().addGrid(model.maxDepth, [2, 5]).build() -> Option A
Hint: Always end ParamGridBuilder with .build() to create grid [OK]
Common Mistakes:
Forgetting to call .build() after addGrid
Using wrong evaluator for classification
Setting numFolds less than 2 (valid but uncommon)
5. You want to tune two hyperparameters of a RandomForestClassifier: numTrees with values [10, 20] and maxDepth with values [5, 10]. How many total models will CrossValidator train if numFolds=3?
hard
A. 30 models
B. 6 models
C. 12 models
D. 60 models
Solution
Step 1: Calculate total hyperparameter combinations
numTrees has 2 values, maxDepth has 2 values, so total combinations = 2 * 2 = 4.
Step 2: Multiply by number of folds
CrossValidator trains each combination on each fold, so total models = 4 * 3 = 12.
Step 3: Re-check calculation
Wait, the question asks how many total models trained. Each fold trains one model per combination, so total = combinations * folds = 4 * 3 = 12.
Final Answer:
12 models -> Option C
Quick Check:
Combinations * folds = 12 [OK]
Hint: Multiply parameter combos by folds for total models trained [OK]
Common Mistakes:
Multiplying number of values incorrectly
Forgetting to multiply by number of folds
Confusing total models with total parameter combos
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.