3: Model Development

    Connect data science tools directly to data in Snowflake.

    Data science work on Snowflake starts with picking the right connection abstraction.

    The wrong choice does not always produce wrong answers, but it produces queries that materialize a million rows into pandas memory when a pushdown aggregation would have answered in seconds, or it forces engineers to manage credentials in five places when one would do.

    The decision matters more on the Advanced exam than on most projects because every wrong-tool scenario in the question bank is built on the difference between a client-side fetch and a server-side computation.

    Key points

    Four connection surfaces matter for the DSA-C03:

    • The Snowflake Connector for Python
    • The Snowpark for Python client library
    • The Snowpark ML modeling API layered on top of Snowpark
    • The Snowflake Connector for Spark

    Each one is a different layer of abstraction.

    The Python connector is a DB-API driver: it sends SQL strings and returns result sets.

    Snowpark is a DataFrame API that compiles operations into SQL and submits them through a session.

    Snowpark ML wraps scikit-learn, XGBoost, and LightGBM estimators so their fit and predict methods execute as Snowpark plans rather than on the local machine.

    The Spark connector exposes Snowflake as a source and sink for Spark DataFrames so existing Spark applications can read and write without rewriting.

    The Snowflake Connector for Python

    The Connector for Python is the lowest-level path. It implements PEP 249 (DB-API 2.0), so any tool that speaks DB-API (SQLAlchemy, pandas through read_sql, BI clients) can use it. The pandas-aware helpers write_pandas and fetch_pandas_all are the only data-science-relevant additions on top of the standard cursor protocol. Everything else, including arrow result transport, is handled internally by the driver.

    import snowflake.connector
    from snowflake.connector.pandas_tools import write_pandas, pd_writer
    import pandas as pd
    
    con = snowflake.connector.connect(
     user="ds_engineer",
     account="crestwood-prod",
     authenticator="snowflake_jwt",
     private_key_file="/secrets/ds_engineer_rsa.p8",
     warehouse="DS_WH",
     database="CRESTWOOD_ML",
     schema="PROD_DS",
     role="DS_PROD_ROLE",
    )
    
    cur = con.cursor()
    cur.execute("SELECT customer_id, tenure_days, monthly_charges, churn_flag FROM customer_churn_train")
    df = cur.fetch_pandas_all()
    
    # Round-trip a new feature set back into a table
    features = df.assign(charges_per_day=df["monthly_charges"] / df["tenure_days"].clip(lower=1))
    success, n_chunks, n_rows, _ = write_pandas(
     conn=con, df=features, table_name="CUSTOMER_CHURN_FEATURES", auto_create_table=True
    )
    

    fetch_pandas_all materializes the entire result set in client RAM. For wide feature tables this is the most common cause of "my notebook died" tickets. fetch_pandas_batches returns an iterator of DataFrames so the client can stream rows. write_pandas uses internal stages and COPY INTO under the hood; the default is to chunk uploads, which keeps a single network failure from invalidating the whole load.

    💡 Exam Trap: cursor.execute followed by fetch_pandas_all runs the SQL on warehouse compute, then pulls every row to the client. A subsequent pandas groupby().mean() runs locally. The exam often asks why aggregations are slow despite a large warehouse: the answer is that the warehouse never saw the aggregation, because the connector fetched raw rows.

    💡 Exam Trap: write_pandas with auto_create_table=True infers schema from the DataFrame's pandas dtypes. Object columns become VARCHAR, not VARIANT. Nested dictionaries serialize as strings, not as semi-structured OBJECT values. If you need VARIANT typing, create the table explicitly first and call write_pandas against the existing table.

    The Snowpark for Python session

    Snowpark replaces "send SQL, receive rows" with "describe a DataFrame, let the client compile it to SQL."

    The snowflake.snowpark.Session object is the connection handle; every DataFrame operation builds a logical plan that gets pushed to the warehouse on collect, count, show, to_pandas, or any other action.

    Lazy evaluation is the point:

    • filters,
    • joins,
    • and projections compose without round-trips until an action forces execution.
    from snowflake.snowpark import Session
    from snowflake.snowpark.functions import col, when, datediff, current_date
    
    session = Session.builder.configs({
     "account": "crestwood-prod",
     "user": "ds_engineer",
     "authenticator": "snowflake_jwt",
     "private_key_file": "/secrets/ds_engineer_rsa.p8",
     "warehouse": "DS_WH",
     "database": "CRESTWOOD_ML",
     "schema": "PROD_DS",
     "role": "DS_PROD_ROLE",
    }).create()
    
    churn = (
     session.table("CUSTOMER_CHURN_RAW")
     .filter(col("STATUS") == "ACTIVE_OR_CHURNED")
     .with_column("TENURE_DAYS", datediff("day", col("SIGNUP_DATE"), current_date()))
     .with_column("HIGH_RISK", when(col("LAST_LOGIN_DAYS") > 30, 1).otherwise(0))
     .select("CUSTOMER_ID", "TENURE_DAYS", "MONTHLY_CHARGES", "HIGH_RISK", "CHURN_FLAG")
    )
    
    # Persist as a training table; pushdown means no rows transit the client
    churn.write.mode("overwrite").save_as_table("CUSTOMER_CHURN_TRAIN")
    

    Snowpark pandas is a separate API surface inside the same library.

    It implements a pandas-compatible interface where DataFrame operations run on warehouse compute through the Snowpark engine.

    It is the right choice when: an existing pandas notebook needs to scale beyond client memory without being rewritten into the Snowpark DataFrame style.

    Code that calls df.groupby("region")["sales"].sum() in Snowpark pandas executes that aggregation as SQL.

    The Snowpark ML modeling API

    The modeling API lives at snowflake.ml.modeling.*. It exposes classes whose names mirror their scikit-learn equivalents (LinearRegression, LogisticRegression, KMeans) plus wrapped XGBoost (XGBClassifier, XGBRegressor) and LightGBM estimators.

    Each class accepts input_cols, label_cols, and output_cols parameters instead of taking raw arrays. The estimator handles serialization, registration of a stored procedure or UDF, and pushdown of fit and predict to the warehouse.

    The same surface includes snowflake.ml.modeling.preprocessing (defined in chapter 2) and snowflake.ml.modeling.model_selection.GridSearchCV / RandomizedSearchCV for distributed hyperparameter optimization.

    from snowflake.ml.modeling.xgboost import XGBClassifier
    from snowflake.ml.modeling.model_selection import GridSearchCV
    
    train = session.table("CUSTOMER_CHURN_TRAIN")
    feature_cols = ["TENURE_DAYS", "MONTHLY_CHARGES", "HIGH_RISK"]
    
    grid = GridSearchCV(
     estimator=XGBClassifier(),
     param_grid={"n_estimators": [100, 200, 400], "max_depth": [3, 5, 7]},
     cv=5,
     scoring="roc_auc",
     input_cols=feature_cols,
     label_cols=["CHURN_FLAG"],
     output_cols=["CHURN_PRED"],
    )
    grid.fit(train)
    best = grid.to_sklearn().best_estimator_
    

    to_sklearn() extracts the underlying scikit-learn or XGBoost object so it can be used outside Snowflake (for local visualization, third-party SHAP, etc.). The Snowpark ML estimator is still the registered training artifact.

    The Snowflake Connector for Spark

    The Spark connector is a Spark DataSource. It is the right tool when:

    • an existing PySpark or Scala Spark application reads from Snowflake,
    • performs Spark-native transformations (Spark MLlib, custom RDDs, structured streaming joins),
    • and writes results back.

    It is the wrong tool for new Snowflake-native pipelines because Spark transformations execute on a Spark cluster, not on Snowflake compute.

    Push-down query optimization moves filters and projections into Snowflake, but joins between Snowflake tables and non-Snowflake sources do not.

    Connecting from external IDEs and Snowpark languages

    The Snowflake Extension for Visual Studio Code provides SQL execution, Snowpark Python debugging, and stage browsing against an authenticated account. Snowflake Notebooks on the warehouse runtime and the container runtime are first-class development environments that run inside Snowflake (Notebooks were defined in chapter 2).

    Snowpark is available in three languages: Python, Java, and Scala. The DataFrame APIs are equivalent across languages, but the ML modeling API is Python-only.

    Limits and quotas

    📊 Limit: A single write_pandas call uses parallel PUTs to an internal stage; the default parallel=4 setting controls how many file uploads run concurrently per call.

    📊 Limit: The Snowpark session object holds a connection to one role at a time; switching roles requires session.use_role(), which executes USE ROLE server-side and is subject to RBAC.

    📊 Limit: Snowpark ML modeling API estimators require a warehouse with enough memory to fit the model on a single node for non-distributed algorithms. For models that exceed warehouse memory, the Container Runtime exposes distributed training APIs.

    Anti-patterns

    ⚠️ Anti-Pattern: Using the Python connector with fetch_pandas_all to load a multi-million-row table into a notebook, then training scikit-learn on the local DataFrame. The correct path is Snowpark ML against the Snowpark DataFrame so training runs on warehouse compute.

    ⚠️ Anti-Pattern: Mixing a snowflake.connector connection with a snowflake.snowpark.Session against the same account inside one script. Maintain a single Session object; Snowpark exposes a .connection attribute that returns an underlying DB-API connection if a connector-style cursor is needed.

    💡 Exam Trap: The Spark connector is sometimes presented in exam scenarios as a "faster" alternative to Snowpark for ML workloads. It is not. Spark MLlib trains on Spark executors; Snowpark ML trains on the warehouse. Choose Spark only when an existing Spark application must continue running.

    Decision rule

    When to use

    • Choose the Python connector when the task is short SQL execution with small result sets returned to the client.
    • Choose Snowpark when DataFrame-style transformations should push down to warehouse compute.
    • Choose the Snowpark ML modeling API when the deliverable is a trained model that will be logged to the Model Registry.
    • Choose the Spark connector only when integrating with an existing Spark application; never as a default for new pipelines.

    Decision Tree: Choosing the Right Connection Surface

    🎯 Scenario: A team has a 90 GB transaction table in Snowflake and wants to train an XGBoost churn model. An engineer proposes loading the table into a notebook with fetch_pandas_all, training locally with xgboost.XGBClassifier, and uploading predictions. What is wrong, and what should they do instead? The 90 GB will not fit in notebook memory; even if it did, training would run on the notebook host rather than warehouse compute, ignoring the elasticity that Snowflake provides. The correct path is to keep the table in Snowflake, build features as a Snowpark DataFrame, and call snowflake.ml.modeling.xgboost.XGBClassifier.fit against that DataFrame. Training executes on the warehouse, the model artifact is registered, and no rows ever transit the client.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Snowflake - SnowPro Advanced Data Scientist learning hub.