Cluster data with a Spark ML Python model
Write a Vulcan Python model that clusters data with Spark MLlib when Spark is available, and falls back to scikit-learn when it isn't.
A fixed rule like "more than 5 issues means high risk" only looks at one column at a time. Clustering groups rows by several features at once, so rows that behave similarly end up in the same group even if no single feature crosses a threshold.
Use this recipe when a Python model needs to run a real machine learning algorithm (KMeans clustering, in this case) and needs to work in two places: a Spark cluster in production, and a local environment where Spark or its MLlib JAR might not be available. The model below scores devices into risk clusters from three engineered features (issues_7d, open_issues_30d, days_since_last_issue), using Spark MLlib when it can and scikit-learn otherwise.
Steps
1. Ship the JAR that MLlib needs
Spark MLlib's estimators (KMeans, LogisticRegression, and others) are backed by JVM classes. Place the JAR under dependencies/java/ at the project root (flat, no nested folders). The Spark stack auto-loads JARs from this folder for both the driver and the executors, so there's nothing to register in config.yaml.
Installing pyspark alone is not enough. PySpark ships the Python API, but MLlib's implementation classes still need to be resolvable on the Spark classpath, and that's what the JAR provides. If the JAR isn't on the classpath, KMeans.fit(...) fails at runtime with a class-loading error even though the Python import succeeded.
2. Try the Spark path first, and fall back safely
Guard every step of the Spark path: check for context.spark, import pyspark.ml inside a try/except, and wrap the whole fit/transform sequence in its own try/except that returns None on any failure.
def _run_spark_kmeans_if_available(context, base_df, feature_cols):
spark = getattr(context, "spark", None)
if spark is None:
return None
try:
from pyspark.ml.clustering import KMeans as SparkKMeans
from pyspark.ml.feature import VectorAssembler
except Exception:
return None
try:
spark_df = spark.createDataFrame(base_df[["snapshot_date", "device_id", "risk_score"] + feature_cols])
assembler = VectorAssembler(inputCols=feature_cols, outputCol="features")
train_df = assembler.transform(spark_df).select("snapshot_date", "device_id", "risk_score", "features")
row_count = train_df.count()
if row_count == 0:
return None
k = int(min(3, row_count))
kmeans = SparkKMeans(k=k, seed=42, featuresCol="features", predictionCol="risk_cluster")
fitted = kmeans.fit(train_df)
out = fitted.transform(train_df).select("snapshot_date", "device_id", "risk_score", "risk_cluster").toPandas()
out["engine_used"] = "spark_ml_kmeans"
return out
except Exception:
return NoneThis model runs in at least two environments: a Spark cluster in production, and possibly a non-Spark engine in local development. Returning None (instead of raising) from this function is what lets the caller fall through cleanly to the scikit-learn path. The broad except Exception: return None is deliberate here: it's what makes "run distributed when possible, degrade gracefully otherwise" work.
Cap the cluster count at the row count of the batch (k = int(min(3, row_count))): KMeans fails if k exceeds the number of points it's clustering, which is a real risk on a small or empty batch.
The .toPandas() call pulls the scored rows onto the Spark driver so both paths return the same pandas shape. That's only safe for bounded output like this per-device snapshot; for large results, return the Spark DataFrame instead.
3. Fall back to scikit-learn
Add a plain scikit-learn path that runs when Spark isn't available, when the MLlib import fails, or when the Spark path raises.
This guarantees the model always produces a valid output table, even in a local or dev environment without a Spark cluster.
4. Record which engine ran, and normalize the schema
Add an engine_used column to the declared schema, and cast every output column to the exact dtype columns declares before the function yields, regardless of which path produced the result.
Silent fallback is only safe if it's observable. Recording engine_used directly in the output table means anyone reading the data can tell which engine actually produced a given row, without checking logs. Vulcan validates whatever is yielded against the columns schema regardless of which internal function produced it, so casting dtypes once, centrally, avoids duplicating that logic in both branches.
Best practices
Guard the Spark ML path with a fallback rather than letting the whole model fail when Spark or MLlib isn't available. This keeps the same model portable between local development and a production Spark cluster.
Record which engine actually ran directly in the output schema. Silent fallback is only safe if it's observable.
Cap cluster or model parameters like
kagainst the actual row count of the batch being processed.Normalize dtypes once, centrally, right before yielding, instead of duplicating casts across every code path that can produce the result.
Seed any stochastic ML algorithm (
seed=42here) so results are reproducible across runs.
Troubleshooting
Model always falls back to scikit-learn, even on the Spark cluster
An exception inside the Spark path is being silently caught
Temporarily narrow the except Exception to log the real error, then restore the broad catch
KMeans fit fails with a cluster-count error
k exceeds the number of rows in a small batch
Confirm the k = int(min(3, row_count)) guard is in place
Output schema mismatch on write
The Spark and scikit-learn branches return different dtypes
Cast dtypes once, centrally, right before yield, not separately in each branch
Model errors instead of skipping on empty input
Missing empty-data guard
Check base_df.empty before running either clustering path
JAR-related class-loading error at runtime
The MLlib JAR isn't on the classpath
Confirm the JAR sits directly under dependencies/java/ (no nested folders), or that spark.jars.packages is set in the Spark gateway config
Related recipes
Build a Python model for AI/ML - the general pattern this recipe specializes for clustering.
References
Python models - the
@modeldecorator, execution context, and dependency handling.Model kinds - supported
kindvalues for Python models.
Last updated
Was this helpful?