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
- Raw table with a label column
- Split into train and test with randomSplit(seed)
- Is the column categorical? Yes: StringIndexer, then OneHotEncoder. No: Keep numeric; scale if the model needs it.
- VectorAssembler builds one features column
- Fit the pipeline on train, transform test
- 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
- StringIndexer orders categories by frequency: the most frequent gets index 0
- One-hot encode nominal categories so the model does not assume an order
- handleInvalid='keep' stops unseen categories from failing at scoring time
- Fit indexers and scalers inside the pipeline on training data only
- Use randomSplit with a seed for repeatable train/test sets
- Evaluate with AUC for imbalanced binary labels, not only accuracy