Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
124: Using Spark MLlib from Scala
When you first dive into Spark MLlib, the biggest shock isn't usually the math—it's the API. If you're used to standard Scala collections or even basic Spark DataFrames, you'll find that MLlib is very opinionated about how data is structured. It doesn't want a bunch of separate columns for your features; it wants one single column containing a vector of those features.
Creating some synthetic churn data
Let's build a simple model to predict customer churn. I'll start by creating a small dataset. In a real project, you'd be loading this from S3 or a database, but for this example, we'll just hardcode some values so you can run this immediately.
import org.apache.spark.sql.SparkSession
import org.apache.spark.ml.classification.LogisticRegression
import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator
val spark = SparkSession.builder().appName("ChurnPrediction").master("local[*]").getOrCreate()
import spark.implicits._
val data = Seq(
(1, 12.0, 50.0, 0), // Tenure, MonthlyCharge, Churned
(2, 1.0, 80.0, 1),
(3, 24.0, 40.0, 0),
(4, 2.0, 90.0, 1),
(5, 36.0, 30.0, 0),
(6, 5.0, 70.0, 1)
).toDF("id", "tenure", "monthly_charge", "label")
The "Vector" hurdle
Here is where I usually trip up when I'm rushing. My instinct is to just throw this DataFrame into the model and tell it which columns are the features. I'll show you what I mean—I tried to do this the first time I wrote this snippet:
// THIS WILL FAIL
val lr = new LogisticRegression()
val model = lr.fit(data)
If you run that, Spark will throw an AnalysisException complaining that it can't find a column named "features". MLlib algorithms are designed to be generic, so they don't look for "tenure" or "monthly_charge"; they look for exactly one column called `features` (by default) that holds a Vector. To fix this, we have to use the VectorAssembler. Think of it as a "bundler" that squashes multiple numeric columns into a single vector column.
val assembler = new VectorAssembler()
.setInputCols(Array("tenure", "monthly_charge"))
.setOutputCol("features")
val vectorizedData = assembler.transform(data)
vectorizedData.show()
Now our DataFrame has a new column where the values look like [12.0, 50.0]. This is exactly what the machine learning models expect.
Training the Logistic Regression model
Now that the data is in the right shape, we can actually train the model. I'm choosing Logistic Regression because it's the bread and butter for binary classification (churn vs. no-churn). I'll explicitly set the label column since we named ours "label" (which happens to be the default, but it's good practice to be explicit).
val lr = new LogisticRegression()
.setLabelCol("label")
.setFeaturesCol("features")
val lrModel = lr.fit(vectorizedData)
// Let's see how the model performs on the same data
val predictions = lrModel.transform(vectorizedData)
predictions.select("id", "label", "prediction").show()
Evaluating the results
Looking at the table is fine for five rows, but for anything real, you need a metric. I'll use the BinaryClassificationEvaluator. By default, this calculates the Area Under the ROC curve (AUC). An AUC of 1.0 is perfect; 0.5 is basically guessing.
val evaluator = new BinaryClassificationEvaluator()
.setLabelCol("label")
.setRawPredictionCol("probability")
val auc = evaluator.evaluate(predictions)
println(s"Model AUC: $auc")
It's a simple pipeline: Data → VectorAssembler → Model → Evaluator. Once you memorize that sequence, using MLlib from Scala becomes much less intimidating.
📋 Practical Task
Build a House Price Linear Regression Pipeline
In this exercise, you will move from classification to regression. Your goal is to predict a continuous house price based on two features: sqft and num_rooms.
- Create a synthetic DataFrame with at least 5 rows containing
sqft(Double),num_rooms(Double), andprice(Double). - Use a
VectorAssemblerto combinesqftandnum_roomsinto a singlefeaturescolumn. - Use
org.apache.spark.ml.regression.LinearRegressionto train a model usingpriceas the label. - Transform the data to get predictions and print the final DataFrame showing the actual price vs. the predicted price.
There are no comments for now.