DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Advantages of Python as an AI and ML Development Language
  • Trends and Comparison Among Popular Python Machine Learning Libraries
  • How to Use Python for Data Science
  • How to Paraphrase Text in Python Using NLP Libraries

Trending

  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Getting Started With Snowflake Snowpark ML: A Step-by-Step Guide

Getting Started With Snowflake Snowpark ML: A Step-by-Step Guide

This guide discusses setting up the Snowpark ML library, configuring your environment, and implementing a basic ML use case.

By 
Sevinthi Kali Sankar Nagarajan user avatar
Sevinthi Kali Sankar Nagarajan
·
Dec. 30, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
2.8K Views

Join the DZone community and get the full member experience.

Join For Free

Snowflake’s Snowpark brings machine learning (ML) closer to your data by enabling developers and data scientists to use Python for ML workflows directly within the Snowflake Data Cloud. 

Here are some of the advantages of using Snowpark for machine learning:

  1. Process data and build models within Snowflake, reducing data movement and latency.
  2. Scale ML tasks efficiently using Snowflake's elastic compute capabilities.
  3. Centralize data pipelines, transformations, and ML workflows in one environment.
  4. Write code in Python, Java, or Scala for seamless library integration.
  5. Integrate Snowpark with tools like Jupyter and Streamlit for enhanced workflows.

In this tutorial, I'll walk you through setting up the Snowpark ML library, configuring your environment, and implementing a basic ML use case. 

Step 1: Prerequisites

Before getting into Snowpark ML, ensure you have the following:

  • A Snowflake account.
  • SnowSQL CLI or any supported Snowflake IDE (e.g., Snowsight).
  • Python 3.8+ installed locally.
  • Necessary Python packages: snowflake-snowpark-python and scikit-learn.

Install the required packages using pip:

Shell
 
pip install snowflake-snowpark-python scikit-learn


Step 2: Set Up Snowpark ML Library

1. Ensure your Snowflake account is Snowpark-enabled. You can verify or enable it via your Snowflake admin console.

2. Create a Python runtime environment in Snowflake to execute your ML models. 

SQL
 
CREATE STAGE my_python_lib;


3. Upload your required Python packages (like scikit-learn) to the stage. For example, use this command to upload a file:

Shell
 
snowsql -q "PUT file://path/to/your/package.zip @my_python_lib AUTO_COMPRESS=TRUE;"


4. Grant permissions to the Snowpark role to use external libraries:

SQL
 
GRANT USAGE ON STAGE my_python_lib TO ROLE my_role;


Step 3: Configure Snowflake Connection in Python

Set up your Python script to connect to Snowflake:

Python
 
from snowflake.snowpark import Session

# Define your Snowflake connection parameters
connection_parameters = {
    "account": "your_account",
    "user": "your_username",
    "password": "your_password",
    "role": "your_role",
    "warehouse": "your_warehouse",
    "database": "your_database",
    "schema": "your_schema"
}

# Create a Snowpark session
session = Session.builder.configs(connection_parameters).create()
print("Connection successful!")


Step 4: A Simple ML Use Case – Predicting Customer Attrition

Data Preparation

1. Load a sample dataset into Snowflake:

SQL
 
CREATE OR REPLACE TABLE cust_data (
    cust_id INT,
    age INT,
    monthly_exp FLOAT,
    attrition INT
);

INSERT INTO cust_data VALUES
(1, 25, 50.5, 0),
(2, 45, 80.3, 1),
(3, 30, 60.2, 0),
(4, 50, 90.7, 1);


2. Access the data in Snowpark:

Python
 
df = session.table("cust_data")
print(df.collect())


Building an Attrition Prediction Model

1. Extract features and labels: 

Python
 
from snowflake.snowpark.functions import col

features = df.select(col("age"), col("monthly_exp"))
labels = df.select(col("attrition"))


2. Locally train a Logistic Regression model using scikit-learn:

Python
 
from sklearn.linear_model import LogisticRegression
import numpy as np

# Prepare data
X = np.array(features.collect())
y = np.array(labels.collect()).ravel()

# Train model
model = LogisticRegression()
model.fit(X, y)

print("Model trained successfully!")


3. Locally save the model and deploy it to Snowflake as a stage file: 

Shell
 
pickle.dump(model, open("attrition_model.pkl", "wb"))
snowsql -q "PUT file://attrition_model.pkl @my_python_lib AUTO_COMPRESS=TRUE;"


Predict Customer Attrition in Snowflake 

1. Use Snowflake’s UDFs to load and use the model:

Python
 
from snowflake.snowpark.types import PandasDataFrame, PandasSeries
import pickle

# Define a UDF
def predict_attrition(age, monthly_exp):
    model = pickle.load(open("attrition_model.pkl", "rb"))
    return model.predict([[age, monthly_exp]])[0]

# Register UDF
session.udf.register(predict_attrition, return_type=IntType(), input_types=[IntType(), FloatType()])


2. Apply the UDF to predict Attrition: 

Python
 
result = df.select("cust_id", predict_attrition("age", "monthly_exp").alias("attrition_prediction"))
result.show()


Best Practices for Snowflake Snowpark in ML

  1. Use Snowflake's SQL engine for preprocessing to boost performance.
  2. Design efficient UDFs for non-native computations and limit data passed to them.
  3. Version and store models centrally for easy deployment and tracking.
  4. Monitor resource usage with query profiling and optimize warehouse scaling.
  5. Validate pipelines with sample data before running on full datasets.

Conclusion

You’ve successfully set up Snowpark ML, configured your environment, and implemented a basic Attrition Prediction model. Snowpark allows you to scale ML workflows directly within Snowflake, reducing data movement and improving operational efficiency.

Machine learning Python (language) Data Types Library

Opinions expressed by DZone contributors are their own.

Related

  • Advantages of Python as an AI and ML Development Language
  • Trends and Comparison Among Popular Python Machine Learning Libraries
  • How to Use Python for Data Science
  • How to Paraphrase Text in Python Using NLP Libraries

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!