Feature Engineering & a Classification Example

Apache Spark · MLlib & Ecosystem

Theory

Models need numbers, so feature engineering turns raw columns into a numeric vector. Categorical text such as city or segment goes through StringIndexer (most frequent category gets index 0) and usually OneHotEncoder (one 0/1 slot per category, so the model does not treat index 3 as 'bigger' than index 1). Numbers can be scaled with StandardScaler, and VectorAssembler combines everything into one features column. Set handleInvalid="keep" on the indexer so unseen categories at prediction time do not crash the job.

A classification workflow then splits data with randomSplit([0.8, 0.2], seed=42), fits a pipeline on the training part, scores the test part and measures quality with an evaluator such as BinaryClassificationEvaluator (area under ROC) or MulticlassClassificationEvaluator (accuracy, F1). Fit every transformation that learns from data (indexers, scalers) on training data only, inside the pipeline, to avoid leakage.

Why we use it

Most real ML work is preparing features, not choosing the algorithm. Doing it with MLlib transformers keeps the logic distributed, repeatable and packaged with the model, so training and scoring always build features the same way.

When to use it

Use StringIndexer + OneHotEncoder for nominal categories, scaling for distance or gradient-based models (logistic regression, k-means), and tree models when you want little preprocessing. Always hold out test data and evaluate with a metric that fits the problem, such as AUC for imbalanced churn data.

How it works

  1. Raw table with a label column
  2. Split into train and test with randomSplit(seed)
  3. Is the column categorical? Yes: StringIndexer, then OneHotEncoder. No: Keep numeric; scale if the model needs it.
  4. VectorAssembler builds one features column
  5. Fit the pipeline on train, transform test
  6. Evaluate with AUC / accuracy and iterate

Syntax

StringIndexer(inputCols=["city", "segment"], outputCols=[...], handleInvalid="keep")
OneHotEncoder(inputCols=[...], outputCols=[...])
VectorAssembler(inputCols=[...], outputCol="raw"); StandardScaler(inputCol="raw", outputCol="features")
train, test = df.randomSplit([0.8, 0.2], seed=42)
BinaryClassificationEvaluator(labelCol="label", metricName="areaUnderROC").evaluate(pred)

Example

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.appName("techtown-spark").getOrCreate()

# 200 customers with simple behaviour features and a churn label (1 = churned)
cities = ["Jaipur", "Pune", "Delhi", "Mumbai"]
segments = ["Retail", "Corporate", "SMB"]
rows = []
for i in range(200):
    orders_90d = (i * 7) % 9
    days_since_last = (i * 13) % 60
    avg_amount = float(1000 + (i * 1733) % 50000)
    churned = 1 if days_since_last > 5 * orders_90d + 10 else 0   # recent, frequent buyers stay
    rows.append((100 + i, cities[i % 4], segments[i % 3], orders_90d, days_since_last, avg_amount, churned))
customers = spark.createDataFrame(rows,
    "customer_id INT, city STRING, segment STRING, orders_90d INT, days_since_last INT, avg_amount DOUBLE, label INT")

from pyspark.ml import Pipeline
from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler, StandardScaler
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import BinaryClassificationEvaluator, MulticlassClassificationEvaluator
from pyspark.ml.functions import vector_to_array

cats = ["city", "segment"]
indexer = StringIndexer(inputCols=cats, outputCols=[c + "_idx" for c in cats], handleInvalid="keep")
encoder = OneHotEncoder(inputCols=[c + "_idx" for c in cats], outputCols=[c + "_vec" for c in cats])
assembler = VectorAssembler(inputCols=["city_vec", "segment_vec", "orders_90d", "days_since_last", "avg_amount"],
                            outputCol="raw_features")
scaler = StandardScaler(inputCol="raw_features", outputCol="features")
lr = LogisticRegression(labelCol="label", featuresCol="features", maxIter=100, regParam=0.01)

train, test = customers.randomSplit([0.75, 0.25], seed=42)
model = Pipeline(stages=[indexer, encoder, assembler, scaler, lr]).fit(train)

pred = model.transform(test)
pred.select("customer_id", "city", "orders_90d", "days_since_last", "label", "prediction",
            F.round(vector_to_array("probability")[1], 3).alias("p_churn")).show(5)

auc = BinaryClassificationEvaluator(labelCol="label", metricName="areaUnderROC").evaluate(pred)
acc = MulticlassClassificationEvaluator(labelCol="label", metricName="accuracy").evaluate(pred)
print(f"train rows={train.count()} test rows={test.count()} | AUC={auc:.3f} | accuracy={acc:.3f}")

# Output:
# +-----------+------+----------+---------------+-----+----------+-------+
# |customer_id|  city|orders_90d|days_since_last|label|prediction|p_churn|
# +-----------+------+----------+---------------+-----+----------+-------+
# |        102| Delhi|         5|             26|    0|       0.0|  0.137|
# |        106| Delhi|         6|             18|    0|       0.0|  0.023|
# |        108|Jaipur|         2|             44|    1|       1.0|  0.961|
# |        109|  Pune|         0|             57|    1|       1.0|  0.999|
# |        113|  Pune|         1|             49|    1|       1.0|  0.997|
# +-----------+------+----------+---------------+-----+----------+-------+
# only showing top 5 rows
# train rows=151 test rows=49 | AUC=1.000 | accuracy=1.000

Key points

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic