What you will be able to do
- Choose between OSS preprocessors, Snowflake ML preprocessors and Ray map_batches based on data size and execution location
- Chain StandardScaler and OneHotEncoder in a Snowflake ML Pipeline and explain what standardization does to each column
- Bin a continuous column into equal-width intervals and choose between one-hot and integer encodings
- Write derived features with pandas on Snowflake and predict which operations move data to the local pandas engine
Key concept
Pushdown feature engineering — Snowflake ML turns feature transformations into work that runs on the warehouse, next to the data, so the table never has to be copied into client memory before it is scaled, encoded or aggregated.
1.Three places a feature transformation can run
Feature engineering turns raw columns into model inputs. Some columns work as they are. Others get more useful after a transformation: a timestamp becomes a day-of-week feature so the model can see weekly patterns, and event rows get aggregated, differenced or time-shifted. In Snowflake the first decision is not which transformation to use but where it runs, because that decides whether your code can handle the full table.
Snowflake ML offers three execution paths. Open-source preprocessors such as scikit-learn work on a pandas DataFrame held in memory. They are quick for prototyping and are limited to what one node can hold. Snowflake ML preprocessors take a Snowpark DataFrame and push the work down to the warehouse you already use for SQL, which spreads it across warehouse compute. Ray map_batches runs custom batch functions in parallel across a compute pool. It is the option for large or unstructured data that needs logic no built-in preprocessor provides.
| Approach | Scale | Execution environment | Compute resources | Suited to |
|---|---|---|---|---|
| OSS (including scikit-learn) | Small & medium datasets | In memory | Snowpark Container Services (Compute Pool) | Quickly prototyping and experimentation |
| Snowflake ML preprocessors | Large/distributed data | Pushdown to the default warehouse | Warehouse | Production workflows with large datasets |
| Ray map_batches | Large/distributed data | Across nodes in a compute pool | Snowpark Container Services (Compute Pool) | Large data workflows that require custom resource controls |
The Snowflake ML preprocessors are a subset of scikit-learn's preprocessors, so the class names will look familiar. They cover the common cases and run against tables of any size. A scikit-learn prototype that worked on four sample rows usually moves to production by swapping the imports and passing a Snowpark DataFrame in place of a pandas one.
Checkpoint 1 of 4· Match them up
Match each feature engineering approach in Snowflake ML to where its work runs and what it is best suited for
Tap a term, then the definition that fits it.
Each approach is defined by where it runs. OSS tools hold the data in client memory. Snowflake ML preprocessors push the computation down to the warehouse, so the table never has to be loaded into the client. Ray spreads custom functions across the nodes of a Container Runtime compute pool.
“Execution Environment | In memory | Pushdown to the default warehouse that you’re using to run SQL queries | Across nodes in a compute pool”Source: docs.snowflake.com
2.Scaling and normalizing numeric columns in a Pipeline
Raw numeric columns often sit on very different scales. In the sample customer table, AGE runs from 23 to 54 and INCOME from 95,000 to 135,000, so a raw comparison of the two is really a comparison of their units. Standardization removes the units: subtract the column's mean, then divide by its standard deviation. The Ray example writes this arithmetic out by hand:
def preprocess_batch(batch: pd.DataFrame) -> pd.DataFrame:
batch['AGE_SCALED'] = (batch['age'] - batch['age'].mean()) / batch['age'].std()
return batchAfter this step, every scaled value says how many standard deviations a row sits from its column's mean, so age and income contribute on comparable terms. The mean and standard deviation are calculated from every row in the column. A few extreme values therefore move the mean and inflate the deviation, and that squeezes the ordinary rows into a narrow band. Check the column's distribution before you assume standardization is neutral.
StandardScaler from snowflake.ml.modeling.preprocessing does the same work at warehouse scale. Each transformer names its input_cols and output_cols, so AGE_SCALED is written next to AGE instead of replacing it. A Pipeline chains the named steps, and one fit_transform call on a Snowpark DataFrame runs the whole chain inside Snowflake.
df = session.table('CUSTOMER_DATA')
# Define Snowflake ML preprocessors
scaler = StandardScaler(input_cols=['AGE', 'INCOME'], output_cols=['AGE_SCALED', 'INCOME_SCALED'])
encoder = OneHotEncoder(input_cols=['CITY'], output_cols=['CITY_ENCODED'])
pipeline = Pipeline(steps=[
('scaling', scaler),
('encoding', encoder)
])
# Fit and transform data in Snowflake (distributed)
result = pipeline.fit_transform(df)
result.show()Normalization has to give the same result at serving time as it did in training. In the Feature Store, a real-time feature view can compute a z-score at read time from a mean and standard deviation that are stored upstream. Every model that reads the feature then uses the same statistics, instead of each one recomputing them over whatever rows it happens to have.
Checkpoint 2 of 4· Check yourself
A data scientist moves a working scikit-learn prototype to production. They change the imports to snowflake.ml.modeling.preprocessing and snowflake.ml.modeling.pipeline, and build df with session.table('CUSTOMER_DATA'). They chain a StandardScaler and a OneHotEncoder in a Pipeline. What happens when they call pipeline.fit_transform(df)?
Snowflake ML preprocessors take a Snowpark DataFrame and push the whole Pipeline down to the warehouse, which spreads the work across warehouse compute. Only the OSS scikit-learn path fits in memory on a pandas DataFrame, and Ray is a separate path for custom batch logic.
“Snowflake ML preprocessors handle distributed transformations directly within Snowflake. These preprocessors are pushed down to scale across warehouses.”Source: docs.snowflake.com
3.One-hot encoding, label encoding and binning into intervals
Models need numbers, so a category such as CITY with values SF, NY and LA has to be encoded first. One-hot encoding gives each category its own indicator, so no value counts as larger than another. In the pipeline above, OneHotEncoder(input_cols=['CITY'], output_cols=['CITY_ENCODED']) does this as one more pipeline step after the scaler. Label encoding maps each category to a single integer code instead. It produces one compact column, but it suggests an order among the categories, which is only correct when the categories really have one.
Binning goes the other way: it turns a continuous value into a small set of interval labels. SQL can do this directly. WIDTH_BUCKET(expr, min_value, max_value, num_buckets) splits the range into equal-width intervals and returns the bucket number each value falls into. With a range of 200,000 to 600,000 and four buckets, every bucket covers 100,000.
Values outside the range are not discarded. A value below min_value returns 0, and a value at or above max_value returns num_buckets + 1. A model trained on buckets 1 to 4 will therefore see 0 or 5 whenever production data drifts outside the training range. Choose the range from the data you expect to serve, or handle the two overflow buckets on purpose.
Checkpoint 3 of 4· Fill the gap
CITY holds SF, NY and LA, and no city should count as larger than another. Which preprocessor belongs in the blank so that each city gets its own indicator?
# Define Snowflake ML preprocessors
scaler = StandardScaler(input_cols=['AGE', 'INCOME'], output_cols=['AGE_SCALED', 'INCOME_SCALED'])
encoder = ? (input_cols=['CITY'], output_cols=['CITY_ENCODED'])One-hot encoding gives each category its own indicator, so the model cannot read an order into SF, NY and LA. A label or ordinal encoder gives each city a single integer code, which implies an order the cities do not have. A discretizer bins continuous values into intervals and does not encode categories.
Source: docs.snowflake.com4.Derived features with pandas on Snowflake
pandas on Snowflake lets you write feature logic in ordinary pandas syntax while large tables are processed in Snowflake. It ships as the Snowpark pandas API, built on modin. Switching to it means changing two import lines. On large data the pandas calls are transpiled to SQL and run natively in Snowflake, which is the reason to use it over to_pandas. If the logic only needs pandas syntax, copying the whole table to the client, as covered in Python Connector and moving data to and from pandas, only costs time and memory.
import modin.pandas as pd
import snowflake.snowpark.modin.pluginDerived features such as a customer's average spend come from per-entity aggregates joined back to the training rows, the pattern taught in GROUP BY aggregation. In pandas on Snowflake, pd.read_snowflake('SNOWFALL') returns a DataFrame and df.groupby("LOCATION").mean()["SNOWFALL"] returns one average per location. read_snowflake also takes a SQL query, so SELECT LOCATION, AVG(SNOWFALL) ... GROUP BY LOCATION gives the same aggregate. Use SQL when the feature is easiest to state as a query and pandas when it reads better as a chain of calls.
Hybrid execution picks the engine for you. It is on by default from Snowpark Python 1.40.0. An inline 11-row DataFrame runs on the local pandas backend, while a 10-million-row table read from Snowflake runs in Snowflake. When a filter and a groupby cut that table down to 7 rows, the result moves to pandas. get_backend() reports which engine a DataFrame is on, and its type stays modin.pandas.DataFrame either way, so downstream code keeps working.
Data moves to the local engine on a limited set of operations, and that matters for feature code. df.apply, df.plot, df.iterrows, df.itertuples, series.items, and reductions whose output is guaranteed to be smaller all migrate data to pandas. Nothing moves it back automatically, except operations such as pd.concat that combine several DataFrames. A row-wise apply over a large table is the step to rewrite as vectorized column arithmetic.
Checkpoint 4 of 4· Check yourself
Your feature code reads a large table with pd.read_snowflake, and a row-wise df.apply then moves the DataFrame to the local pandas engine. Next you run a heavy groupby aggregation on the same DataFrame. Where does that aggregation run?
Data moves from Snowflake to pandas on operations such as df.apply, but nothing moves it back automatically. The only exception is an operation such as pd.concat that combines several DataFrames. The type stays modin.pandas.DataFrame, so the call still works, but it runs locally. That is why a row-wise apply over a large table should be rewritten as vectorized column arithmetic.
“does not automatically move a DataFrame from the pandas engine back to Snowflake, except in cases where an operation like pd.concat acts on multiple DataFrames”Source: docs.snowflake.com
Sources5
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“For small to medium datasets and quick prototyping, use familiar Python ML libraries that run locally or on single nodes within Container Runtime.”
↩︎ Three places a feature transformation can run“The Snowflake ML preprocessors are a subset of the preprocessors available in scikit-learn, but they cover the most common use cases.”
↩︎ Three places a feature transformation can run“Use Snowflake ML preprocessors for large datasets and production workloads.”
↩︎ Scaling and normalizing numeric columns in a Pipeline“encoder = OneHotEncoder(input_cols=['CITY'], output_cols=['CITY_ENCODED'])”
↩︎ One-hot encoding, label encoding and binning into intervals“These preprocessors are pushed down to scale across warehouses.”
↩︎ Key concept“These preprocessors are pushed down to scale across warehouses.”
↩︎ Exam trap 1“Execution Environment | In memory | Pushdown to the default warehouse that you’re using to run SQL queries | Across nodes in a compute pool”
↩︎ Checkpoint“Snowflake ML preprocessors handle distributed transformations directly within Snowflake. These preprocessors are pushed down to scale across warehouses.”
↩︎ Checkpoint - 2.
“you might derive a day-of-week feature from a timestamp to allow the model to detect weekly patterns”
↩︎ Three places a feature transformation can run“Other common feature transformations involve aggregating, differentiating, or time-shifting data.”
↩︎ Three places a feature transformation can run - 3.https://docs.snowflake.com/en/developer-guide/snowflake-ml/feature-store/advanced-feature-engineeringOfficial docs
“computing a z-score from a stored mean and standard deviation”
↩︎ Scaling and normalizing numeric columns in a Pipeline - 4.
“Constructs equi-width histograms, in which the histogram range is divided into intervals of identical size”
↩︎ One-hot encoding, label encoding and binning into intervals“0 if the expression is less than min_value. num_buckets + 1 if the expression is greater than or equal to max_value.”
↩︎ One-hot encoding, label encoding and binning into intervals - 5.
“it runs workloads natively in Snowflake through transpilation to SQL”
↩︎ Derived features with pandas on Snowflake“Starting with Snowpark Python version 1.40.0, hybrid execution is enabled by default when using pandas on Snowflake.”
↩︎ Derived features with pandas on Snowflake“These operations include df.apply, df.plot, df.iterrows, df.itertuples, series.items, and reduction operations where the size of the data is guaranteed to be smaller.”
↩︎ Derived features with pandas on Snowflake“You can also pass in a SQL query directly and get back a pandas on Snowflake DataFrame”
↩︎ Derived features with pandas on Snowflake“Hybrid execution does not automatically move a DataFrame from the pandas engine back to Snowflake”
↩︎ Exam trap 2“These operations include df.apply, df.plot, df.iterrows, df.itertuples, series.items”
↩︎ Prediction“does not automatically move a DataFrame from the pandas engine back to Snowflake, except in cases where an operation like pd.concat acts on multiple DataFrames”
↩︎ Checkpoint