Data Analysis and Churn Prediction Using Snowflake Notebooks
Overview

Acquiring a new telecom subscriber costs far more than retaining an existing one, yet early warning signs of cancellation are often buried across billing, plan renewal, usage, and customer-support tables. Exploratory data analysis turns raw telemetry into concrete behavioral hypotheses, and machine learning operationalizes those signals so retention teams can intervene before a subscriber cancels.
In this Quickstart, you step into the role of a telecom data scientist using Snowflake Notebooks in Workspaces to build an end-to-end churn prediction workflow in a single unified notebook (telco_churn_prediction.ipynb)—without moving data out of Snowflake or installing third-party packages:
- Ingest, Standardize, and Explore (Steps 1–8): Ingest raw Parquet subscriber telemetry from Amazon S3 into Snowflake, reference SQL query results directly as a lazy Snowpark DataFrame, standardize schema naming, profile data quality, visualize key churn triggers with Altair, and materialize the curated base table (
CHURN_PROD.ANALYTICS.CUSTOMER_CHURN_BASE). - Engineer Features, Train, Register, and Explain (Steps 9–15): Engineer behavioral churn ratios in Snowpark (
CHURN_PROD.ANALYTICS.CUSTOMER_CHURN_FEATURES), load the curated feature table with Container RuntimeDataConnector, train a class-balancedRandomForestClassifier, log the model with Snowpark table lineage and built-in SHAP explainability to Snowflake Model Registry, and score plus explain new subscriber cohorts in both Python and SQL.
Prerequisites
- Familiarity with basic SQL and Python
- Familiarity with core machine learning classification concepts (train/test splits, precision, recall, and ROC AUC)
What You Will Learn
- How to configure role, compute pool, warehouse, and Model Registry privileges for Notebooks in Workspaces
- How to ingest semi-structured Parquet files from an external S3 stage using
INFER_SCHEMAandCOPY INTO - How to pass SQL cell results directly into Python as Snowpark DataFrames on Container Runtime (
v3.0) and push aggregations down to a query warehouse - How to visualize class imbalance and behavioral churn drivers inline using Altair
- How to load Snowpark feature tables via Container Runtime
DataConnectorand train a leak-free, class-balancedRandomForestClassifier - How to register a model version in Snowflake Model Registry with Snowpark lineage and built-in SHAP explainability, then invoke
PREDICT,PREDICT_PROBA, andEXPLAINin both Python and SQL
What You Will Need
- A Snowflake account with access to Snowsight, Workspaces, and a user granted
SECURITYADMINandACCOUNTADMINprivileges to run the one-time environment setup script - The companion GitHub repository: sfguide-data-analysis-churn-prediction-in-snowflake-notebooks
What You Will Build
- Curated analytics and feature tables (
CHURN_PROD.ANALYTICS.CUSTOMER_CHURN_BASEandCHURN_PROD.ANALYTICS.CUSTOMER_CHURN_FEATURES) built from3,333telecom subscriber records - Exploratory and model-evaluation Altair visualizations inside Snowflake Notebooks in Workspaces
- A governed model (
CHURN_PROD.ANALYTICS.TELCO_CHURN_MODEL, versionV1) registered in Snowflake Model Registry that scores new subscribers and explains per-subscriber churn drivers on a Snowflake warehouse via Python (mv.run) and SQL (MODEL(...)!PREDICT(...)andMODEL(...)!EXPLAIN(...))
Set Up Environment
Notebooks in Workspaces combine two compute resources:
- A Notebook Service on a Compute Pool (
SYSTEM_COMPUTE_POOL_CPU), which runs the containerized Python kernel (v3.0, Python3.12) for Python,scikit-learn, and Altair execution. - A Query Warehouse (
CHURN_DS_WH), which executes SQL cells, Snowpark DataFrame pushdown transformations, and warehouse-backed Model Registry inference.
Run the Setup Script
- Sign in to Snowsight.
- In the left navigation menu, select Projects » Workspaces (or open a SQL Worksheet), create a new SQL file, paste the setup script below (also available in
scripts/setup.sql), and click Run All:
USE ROLE securityadmin; -- Create role for the quickstart CREATE OR REPLACE ROLE churn_data_scientist; USE ROLE accountadmin; -- Create database and schema CREATE OR REPLACE DATABASE churn_prod; CREATE OR REPLACE SCHEMA churn_prod.analytics; -- Create query warehouse for SQL and Snowpark pushdown CREATE OR REPLACE WAREHOUSE churn_ds_wh WAREHOUSE_SIZE = 'xsmall' WAREHOUSE_TYPE = 'standard' AUTO_SUSPEND = 60 AUTO_RESUME = TRUE INITIALLY_SUSPENDED = TRUE COMMENT = 'Query warehouse for Telco Churn Prediction quickstart'; USE WAREHOUSE churn_ds_wh; -- Grant warehouse privileges GRANT USAGE, OPERATE, MONITOR, MODIFY ON WAREHOUSE churn_ds_wh TO ROLE churn_data_scientist; -- Grant compute pool usage so the role can start a Workspace Notebook service GRANT USAGE ON COMPUTE POOL SYSTEM_COMPUTE_POOL_CPU TO ROLE churn_data_scientist; -- Grant database, schema, stage, and Model Registry privileges GRANT ALL ON DATABASE churn_prod TO ROLE churn_data_scientist; GRANT ALL ON SCHEMA churn_prod.analytics TO ROLE churn_data_scientist; GRANT CREATE STAGE ON SCHEMA churn_prod.analytics TO ROLE churn_data_scientist; GRANT CREATE MODEL ON SCHEMA churn_prod.analytics TO ROLE churn_data_scientist; GRANT ALL ON ALL STAGES IN SCHEMA churn_prod.analytics TO ROLE churn_data_scientist; GRANT ALL ON ALL STAGES IN SCHEMA churn_prod.public TO ROLE churn_data_scientist; -- Grant role to SYSADMIN (role hierarchy best practice) and the current user GRANT ROLE churn_data_scientist TO ROLE sysadmin; SET my_user_var = (SELECT '"' || CURRENT_USER() || '"'); GRANT ROLE churn_data_scientist TO USER identifier($my_user_var); USE ROLE churn_data_scientist; USE WAREHOUSE churn_ds_wh; USE DATABASE churn_prod; USE SCHEMA analytics; SELECT 'Churn prediction environment setup is complete.' AS status;
Confirm that the final statement returns Churn prediction environment setup is complete. before moving to the next section.
Open Notebook in Workspaces
The entire workflow—from cloud Parquet ingestion and exploratory Altair charts through Snowpark feature engineering, RandomForestClassifier training, and Model Registry SHAP scoring—runs in a single Workspace notebook: telco_churn_prediction.ipynb.
Add the Notebook to Your Workspace
- Switch your active Snowsight role (bottom-left profile menu or top context selector) to
CHURN_DATA_SCIENTIST. - Download
telco_churn_prediction.ipynbfrom the companion GitHub repository. - In Snowsight, navigate to Projects » Workspaces and open your default personal workspace (My Workspace).
- In the Files pane on the left, create a folder (for example,
churn_quickstart) and uploadtelco_churn_prediction.ipynbinto that folder.
Note: If your account already has a GitHub
API INTEGRATIONconfigured, you can also clonehttps://github.com/Snowflake-Labs/sfguide-data-analysis-churn-prediction-in-snowflake-notebooksdirectly as a Git-backed Workspace via + » Git workspace.
Connect Your Notebook Service and Query Warehouse
- Click
telco_churn_prediction.ipynbin the Workspace Files pane to open the notebook. - In the top-right corner of the notebook editor, click Connect (or the compute selector) to open Connect your notebook:
- Service: Choose Create a service (or select an existing CPU notebook service if you already have one running), name it
churn_service, select CPU, choose compute poolSYSTEM_COMPUTE_POOL_CPU, and keep Container Runtime3.0(Python3.12). - Query warehouse: Select
CHURN_DS_WH. - Role: Confirm
CHURN_DATA_SCIENTISTis selected.
- Service: Choose Create a service (or select an existing CPU notebook service if you already have one running), name it
- Click Create and connect (initial service startup typically takes 1–2 minutes).
Zero extra package installs required: Container Runtime
3.0pre-installssnowflake-snowpark-python,snowflake-ml-python,scikit-learn,altair,pandas, andnumpy, so you can run every cell immediately without anenvironment.ymlfile orpip installstep.
Ingest and Explore Data
With telco_churn_prediction.ipynb connected to churn_service and CHURN_DS_WH, click Run all in the top-right toolbar (or execute cells top-to-bottom) to run the end-to-end pipeline.
Step 1: Set Session Context and Ingest Parquet from S3
Unlike legacy schema-bound notebooks, .ipynb files in Workspaces live in a file tree rather than inside a single schema. The opening SQL cell explicitly sets the execution context and uses INFER_SCHEMA + COPY INTO ... MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE to load 3,333 subscriber records from s3://sfquickstarts/notebook_demos/churn/telco_churn.parquet into CHURN_PROD.ANALYTICS.TELCO_CHURN_RAW:
USE ROLE CHURN_DATA_SCIENTIST; USE WAREHOUSE CHURN_DS_WH; USE DATABASE CHURN_PROD; USE SCHEMA ANALYTICS; CREATE OR REPLACE FILE FORMAT CHURN_PROD.ANALYTICS.PARQUET_FORMAT TYPE = PARQUET; CREATE OR REPLACE STAGE CHURN_PROD.ANALYTICS.TELCO_EXTERNAL_STAGE URL = 's3://sfquickstarts/notebook_demos/churn/' FILE_FORMAT = CHURN_PROD.ANALYTICS.PARQUET_FORMAT; CREATE OR REPLACE TABLE CHURN_PROD.ANALYTICS.TELCO_CHURN_RAW USING TEMPLATE ( SELECT ARRAY_AGG(OBJECT_CONSTRUCT(*)) FROM TABLE( INFER_SCHEMA( LOCATION => '@CHURN_PROD.ANALYTICS.TELCO_EXTERNAL_STAGE/telco_churn.parquet', FILE_FORMAT => 'CHURN_PROD.ANALYTICS.PARQUET_FORMAT' ) ) ); COPY INTO CHURN_PROD.ANALYTICS.TELCO_CHURN_RAW FROM @CHURN_PROD.ANALYTICS.TELCO_EXTERNAL_STAGE/telco_churn.parquet FILE_FORMAT = (FORMAT_NAME = 'CHURN_PROD.ANALYTICS.PARQUET_FORMAT') MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE PURGE = FALSE; SELECT COUNT(*) AS LOADED_SUBSCRIBERS FROM CHURN_PROD.ANALYTICS.TELCO_CHURN_RAW;
Step 2: Reference SQL Results as a Snowpark DataFrame and Normalize Columns
The second SQL cell queries CHURN_PROD.ANALYTICS.TELCO_CHURN_RAW with its cell result variable named raw_subscribers. On Notebook Container Runtime >= 2.6, SQL cell outputs bind automatically in Python as lazy snowflake.snowpark.DataFrame objects rather than pulling the full table into kernel memory.
Because Parquet schema inference preserves mixed-case source column names ("AccountWeeks", "CustServCalls", "DataUsage"), the next Python cell normalizes all 11 columns into clean uppercase SNAKE_CASE (CHURN, ACCOUNT_WEEKS, CONTRACT_RENEWAL, DATA_PLAN, DATA_USAGE_GB, CUST_SERV_CALLS, DAY_MINS, DAY_CALLS, MONTHLY_CHARGE, OVERAGE_FEE, ROAM_MINS) and runs pushdown null and summary profiling on CHURN_DS_WH.
Step 3: Visualize Class Imbalance and Churn Drivers with Altair
After enabling alt.renderers.enable("mimetype") for Workspace notebook rendering, Snowpark aggregates the subscriber counts in the warehouse before handing compact summary frames to Altair.
First, the target distribution confirms a moderate class imbalance—85.5% retained (2,850 subscribers) vs. 14.5% churned (483 subscribers)—which informs our class-weighted modeling strategy during training:

Next, cohort aggregations reveal two clear operational churn signals:
- Unrenewed contracts: Subscribers who did not renew their contract churn at ~
39%–43%, compared to under14%among subscribers who renewed. - Customer support friction: Churn stays near
10%–13%for0–3customer service calls, then jumps sharply above45%+at4+support calls:

At the end of the exploratory section (Step 8), the notebook materializes the standardized 11-column dataset to CHURN_PROD.ANALYTICS.CUSTOMER_CHURN_BASE (3,333 rows) as a reusable curated analytics table before adding model-specific features.
Engineer Features and Train
Continuing in the same notebook session (Steps 9–11), telco_churn_prediction.ipynb transforms the exploratory findings into engineered features and trains a class-balanced classifier.
Step 1: Engineer Behavioral Features in Snowpark
Building directly on CUSTOMER_CHURN_BASE and the EDA findings above, Snowpark computes three domain features inside the warehouse and saves the 14-column modeling table to CHURN_PROD.ANALYTICS.CUSTOMER_CHURN_FEATURES:
HIGH_SUPPORT_CALLS: Binary indicator (1whenCUST_SERV_CALLS >= 4, else0) capturing the support-escalation threshold (267subscribers flagged).AVG_MINS_PER_CALL:DAY_MINS / NULLIF(DAY_CALLS, 0)(defaulting to0.0whenDAY_CALLS = 0) to distinguish long-call daytime patterns from frequent short calls.OVERAGE_SHARE:OVERAGE_FEE / NULLIF(MONTHLY_CHARGE, 0)to measure bill-shock intensity relative to total monthly spend.
Step 2: Load Features with DataConnector and Train a Balanced Random Forest
Inside Container Runtime (v3.0), snowflake.ml.data.data_connector.DataConnector streams the curated Snowpark DataFrame directly into pandas over Arrow. Because decision-tree splits are invariant to monotonic feature scaling, RandomForestClassifier operates directly on raw feature units (MONTHLY_CHARGE in dollars, CUST_SERV_CALLS as call counts)—keeping downstream SHAP explanations immediately interpretable without StandardScaler transformations:
from snowflake.ml.data.data_connector import DataConnector modeling_pdf = DataConnector.from_dataframe( persisted_features_sdf.select([*FEATURE_COLS, TARGET_COL]) ).to_pandas() X = modeling_pdf[FEATURE_COLS] y = modeling_pdf[TARGET_COL].astype(int) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, stratify=y, random_state=42 ) churn_model = RandomForestClassifier( n_estimators=200, max_depth=12, min_samples_leaf=2, class_weight="balanced", random_state=42, n_jobs=-1, ) churn_model.fit(X_train, y_train)
Splitting before fitting (80% train / 20% holdout, stratified on CHURN) and setting class_weight="balanced" handles the 14.5% churn class natively—requiring zero external oversampling packages while keeping holdout evaluation strictly isolated.
Step 3: Evaluate Holdout Metrics and Feature Importances
On the 667-subscriber stratified holdout set, the classifier achieves:
- Accuracy:
0.8861(522true negatives,69true positives,48false positives,28false negatives) - ROC AUC:
0.8623 - Recall (Churn class):
0.7113 - Precision (Churn class):
0.5897 - F1 Score:
0.6449
Pairing the holdout confusion matrix with Random Forest Gini feature importances confirms that DAY_MINS, MONTHLY_CHARGE, CONTRACT_RENEWAL, CUST_SERV_CALLS, and the engineered HIGH_SUPPORT_CALLS flag drive the strongest splits:

Register and Score Model
Step 1: Log the Model with Lineage and Built-In SHAP Explainability
Next (Steps 12–15), telco_churn_prediction.ipynb logs churn_model and its holdout metrics to Snowflake Model Registry as CHURN_PROD.ANALYTICS.TELCO_CHURN_MODEL (version V1) with target_platforms=["WAREHOUSE"]:
from snowflake.ml.model import task from snowflake.ml.registry import Registry reg = Registry(session=session, database_name="CHURN_PROD", schema_name="ANALYTICS") background_sdf = persisted_features_sdf.select(FEATURE_COLS).limit(100) mv = reg.log_model( model=churn_model, model_name="TELCO_CHURN_MODEL", version_name="V1", target_platforms=["WAREHOUSE"], sample_input_data=background_sdf, metrics=eval_metrics, task=task.Task.TABULAR_BINARY_CLASSIFICATION, comment="Class-balanced RandomForestClassifier for telecom subscriber churn prediction with built-in SHAP explainability", options={"enable_explainability": True, "relax_version": True}, )
Passing a Snowpark DataFrame (background_sdf) as sample_input_data automatically records Snowflake ML Lineage from CUSTOMER_CHURN_FEATURES to TELCO_CHURN_MODEL, and setting enable_explainability=True auto-generates a warehouse-backed EXPLAIN function alongside PREDICT and PREDICT_PROBA.
Step 2: Score and Explain New Subscribers in Python and SQL
Global feature importances tell us what matters across the whole customer base, while per-subscriber SHAP attributions tell a retention specialist why a specific customer is flagged—so someone churning due to bill overages gets a plan-rightsizing offer rather than a support callback.
The notebook writes three representative subscriber personas to CHURN_PROD.ANALYTICS.SAMPLE_NEW_SUBSCRIBERS, runs mv.run(..., function_name="explain") in Python to visualize each subscriber's top 5 positive and negative churn drivers in Altair, and runs combined batch scoring + SHAP attribution directly in SQL on CHURN_DS_WH:

SELECT s.SUBSCRIBER_PROFILE, MODEL(CHURN_PROD.ANALYTICS.TELCO_CHURN_MODEL, V1)!PREDICT( s.ACCOUNT_WEEKS, s.CONTRACT_RENEWAL, s.DATA_PLAN, s.DATA_USAGE_GB, s.CUST_SERV_CALLS, s.DAY_MINS, s.DAY_CALLS, s.MONTHLY_CHARGE, s.OVERAGE_FEE, s.ROAM_MINS, s.HIGH_SUPPORT_CALLS, s.AVG_MINS_PER_CALL, s.OVERAGE_SHARE ):output_feature_0::INT AS PREDICTED_CHURN, ROUND( MODEL(CHURN_PROD.ANALYTICS.TELCO_CHURN_MODEL, V1)!PREDICT_PROBA( s.ACCOUNT_WEEKS, s.CONTRACT_RENEWAL, s.DATA_PLAN, s.DATA_USAGE_GB, s.CUST_SERV_CALLS, s.DAY_MINS, s.DAY_CALLS, s.MONTHLY_CHARGE, s.OVERAGE_FEE, s.ROAM_MINS, s.HIGH_SUPPORT_CALLS, s.AVG_MINS_PER_CALL, s.OVERAGE_SHARE ):output_feature_1::FLOAT * 100, 1 ) AS CHURN_PROBABILITY_PCT, ROUND(e.CONTRACT_RENEWAL_EXPLANATION, 3) AS SHAP_CONTRACT_RENEWAL, ROUND(e.CUST_SERV_CALLS_EXPLANATION, 3) AS SHAP_SUPPORT_CALLS, ROUND(e.DAY_MINS_EXPLANATION, 3) AS SHAP_DAY_MINS, ROUND(e.MONTHLY_CHARGE_EXPLANATION, 3) AS SHAP_MONTHLY_CHARGE FROM CHURN_PROD.ANALYTICS.SAMPLE_NEW_SUBSCRIBERS s, TABLE( MODEL(CHURN_PROD.ANALYTICS.TELCO_CHURN_MODEL, V1)!EXPLAIN( s.ACCOUNT_WEEKS, s.CONTRACT_RENEWAL, s.DATA_PLAN, s.DATA_USAGE_GB, s.CUST_SERV_CALLS, s.DAY_MINS, s.DAY_CALLS, s.MONTHLY_CHARGE, s.OVERAGE_FEE, s.ROAM_MINS, s.HIGH_SUPPORT_CALLS, s.AVG_MINS_PER_CALL, s.OVERAGE_SHARE ) ) e ORDER BY CHURN_PROBABILITY_PCT DESC;
Both Python and SQL return identical churn classifications, calibrated probabilities, and per-feature SHAP log-odds/probability contributions:
| Subscriber Profile | Predicted Churn | Churn Probability (%) | SHAP: Contract Renewal | SHAP: Support Calls | SHAP: Day Mins | SHAP: Monthly Charge |
|---|---|---|---|---|---|---|
| High Daytime Usage & Overage | 1 | 98.1 | +0.169 | -0.007 | +0.160 | +0.174 |
| Unrenewed + 5 Support Calls | 1 | 55.4 | +0.193 | +0.081 | -0.003 | -0.071 |
| Loyal Bundled Plan User | 0 | 11.8 | -0.024 | -0.032 | -0.017 | +0.082 |
Clean Up
To remove all compute, storage, and RBAC objects created during this Quickstart, open a SQL file in Workspaces (or a SQL Worksheet) and execute the statements below (also available in scripts/teardown.sql):
USE ROLE accountadmin; -- Drop the personal Workspace Notebook service if created during the quickstart SET churn_service_fqn = (SELECT '"USER$' || CURRENT_USER() || '".PUBLIC.CHURN_SERVICE'); DROP SERVICE IF EXISTS identifier($churn_service_fqn); -- Drop database and warehouse DROP DATABASE IF EXISTS churn_prod; DROP WAREHOUSE IF EXISTS churn_ds_wh; USE ROLE securityadmin; DROP ROLE IF EXISTS churn_data_scientist;
Conclusion and Resources
Congratulations! You have built, evaluated, registered, and scored an end-to-end subscriber churn prediction pipeline using Snowflake Notebooks in Workspaces and Snowflake Model Registry.
What You Learned
- How to provision least-privilege role, warehouse, compute pool, and Model Registry grants for Notebooks in Workspaces
- How to ingest external Parquet telemetry into Snowflake and reference SQL cells directly as Snowpark DataFrames
- How to combine Snowpark pushdown aggregations with Altair visualizations to uncover churn drivers
- How to load features via Container Runtime
DataConnector, train a leak-free, class-balancedscikit-learnclassifier, and log it to Snowflake Model Registry with built-in SHAP explainability for governed Python and SQL inference
Related Resources
This content is provided as is, and is not maintained on an ongoing basis. It may be out of date with current Snowflake instances