<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ramon Sieira Martínez on Medium]]></title>
        <description><![CDATA[Stories by Ramon Sieira Martínez on Medium]]></description>
        <link>https://medium.com/@rasieira1998?source=rss-987b967557ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NwrWMXM9cP72GggGB3xF7g.png</url>
            <title>Stories by Ramon Sieira Martínez on Medium</title>
            <link>https://medium.com/@rasieira1998?source=rss-987b967557ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:26:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rasieira1998/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Apache Spark to Check if a DataFrame is Empty: The Epic Battle of the Unnecessarily Epic]]></title>
            <link>https://medium.com/@rasieira1998/using-apache-spark-to-check-if-a-dataframe-is-empty-the-epic-battle-of-the-unnecessarily-epic-f62a087e83ff?source=rss-987b967557ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62a087e83ff</guid>
            <category><![CDATA[empty]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ramon Sieira Martínez]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 16:20:02 GMT</pubDate>
            <atom:updated>2025-06-08T16:20:02.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*4VfLrbreKtEC0470.png" /></figure><p>For this brief article, I decided to flip a coin and try to discover the best method (if one truly exists) to determine whether a Spark DataFrame is empty.</p><h3>🚀 Our Setup</h3><p>For this exploration, I’m using <strong>PySpark 3.5.1</strong> in a small Google Colab notebook. Here’s how we set it all up:</p><h4>1️⃣Imports and Setup</h4><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col, lit, rand, concat_ws, map_from_arrays, array<br>from pyspark.sql.types import IntegerType, DoubleType<br>import time<br>import plotly.express as px<br>import pandas as pd<br><br>spark = SparkSession.builder \<br>    .appName(&quot;Benchmark isEmpty methods&quot;) \<br>    .getOrCreate()</pre><h4>2️⃣ Function to Create a Mixed-Type DataFrame for Testing</h4><pre>def create_df(size):<br>    base_df = spark.range(size)<br>    df = base_df \<br>        .withColumn(&quot;str_col1&quot;, concat_ws(&quot;-&quot;, lit(&quot;val&quot;), col(&quot;id&quot;) % 100)) \<br>        .withColumn(&quot;str_col2&quot;, concat_ws(&quot;:&quot;, lit(&quot;key&quot;), col(&quot;id&quot;) % 50)) \<br>        .withColumn(&quot;int_col1&quot;, (col(&quot;id&quot;) % 100).cast(IntegerType())) \<br>        .withColumn(&quot;int_col2&quot;, (col(&quot;id&quot;) % 10).cast(IntegerType())) \<br>        .withColumn(&quot;dbl_col1&quot;, (col(&quot;id&quot;) * rand()).cast(DoubleType())) \<br>        .withColumn(&quot;dbl_col2&quot;, (col(&quot;id&quot;) * 0.5).cast(DoubleType())) \<br>        .withColumn(&quot;map_col1&quot;, map_from_arrays(array(lit(&quot;a&quot;), lit(&quot;b&quot;)), array(col(&quot;id&quot;) % 5, col(&quot;id&quot;) % 10))) \<br>        .withColumn(&quot;map_col2&quot;, map_from_arrays(array(lit(&quot;x&quot;), lit(&quot;y&quot;)), array(col(&quot;id&quot;) % 3, col(&quot;id&quot;) % 4))) \<br>        .drop(&quot;id&quot;)<br>    for i in range(12):<br>            df = df.withColumn(f&quot;extra_str_{i}&quot;, concat_ws(&quot;_&quot;, lit(&quot;col&quot;), lit(i), (rand() * 1000).cast(IntegerType())))<br>        return df</pre><h3>🥊 Methods to Check if a DataFrame is Empty</h3><p>Here are the different approaches we’re benchmarking:</p><pre>def method_count(df):<br>    return df.count() == 0<br>def method_rdd_isEmpty(df):<br>    return df.rdd.isEmpty()<br>def method_take(df):<br>    return len(df.take(1)) == 0<br>def method_limit_count(df):<br>    return df.limit(1).count() == 0<br>def method_df_isEmpty(df):<br>    return df.isEmpty()<br>def method_first(df):<br>    return df.first() is None</pre><h4>Benchmarking</h4><pre>def benchmark(df, name, func):<br>    start = time.time()<br>    result = func(df)<br>    duration = time.time() - start<br>    return duration</pre><pre>sizes = [0, 1_000, 1_000_000]<br>methods = [<br>    (&quot;count()==0&quot;, method_count),<br>    (&quot;rdd.isEmpty()&quot;, method_rdd_isEmpty),<br>    (&quot;take(1)&quot;, method_take),<br>    (&quot;limit(1).count()==0&quot;, method_limit_count),<br>    (&quot;df.isEmpty()&quot;, method_df_isEmpty),<br>    (&quot;first() is None&quot;, method_first)<br>]<br>results = []<br>for size in sizes:<br>    print(f&quot;Creating DataFrame with {size} rows...&quot;)<br>    df = create_df(size)<br>    for name, fn in methods:<br>        print(f&quot;Running {name} for {size} rows...&quot;)<br>        duration = benchmark(df, name, fn)<br>        results.append({<br>            &quot;Method&quot;: name,<br>            &quot;Size&quot;: size,<br>            &quot;Time(s)&quot;: duration<br>        })</pre><h4>Visualizing the Results</h4><pre>df_results = pd.DataFrame(results)<br><br>fig = px.line(df_results, x=&quot;Size&quot;, y=&quot;Time(s)&quot;, color=&quot;Method&quot;,<br>               markers=True,<br>               title=&quot;Comparison of methods to check if DataFrame is empty&quot;,<br>               labels={&quot;Size&quot;: &quot;Number of rows&quot;, &quot;Time(s)&quot;: &quot;Time (seconds)&quot;},<br>               log_x=True, log_y=True)<br>fig.show()</pre><h3>🧐 First Observations</h3><p>In the following chart, it seems clear that the isEmpty() method is the outright winner in terms of speed… but can we do even better?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41JmhXDc5l-wqpAP77ruew.png" /><figcaption>Executed with Adaptive Query Execution enabled (default True) in Spark.</figcaption></figure><h3>🧪 What if We Play with AQE (Adaptive Query Execution)?</h3><p>Inspired by an excellent article from my colleague Angel Alvarez 😊 (<a href="https://medium.com/towards-data-engineering/apache-spark-wtf-i-love-it-when-a-plan-comes-together-part-iii-296a44d323dd">link here</a>), I tried disabling AQE to see if it would improve the timings</p><pre>spark = SparkSession.builder \<br>    .appName(&quot;Benchmark isEmpty methods&quot;) \<br>    .config(&quot;spark.sql.adaptive.enabled&quot;, &quot;true&quot;) \<br>    .getOrCreate()</pre><p>Surprisingly, enabling AQE did improve execution times in some methods… but isEmpty() still retained the pole position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tw17ogHxsXp9zBz9EGeEyQ.png" /><figcaption>AQE = False</figcaption></figure><h3>🔬 Another Test with a Different DataFrame Creation Strategy</h3><blockquote>I also tested a more convoluted DataFrame creation pattern, adapting Angel’s example from Scala to PySpark (<a href="https://github.com/SauronShepherd/i-love-it-when-a-plan-comes-together/blob/main/src/main/scala/Test1.scala"><strong>https://github.com/SauronShepherd/i-love-it-when-a-plan-comes-together/blob/main/src/main/scala/Test1.scala</strong></a>):</blockquote><pre>def create_df(size):<br>    df = spark.range(size)<br>    for i in range(1, 26):<br>        df = df.withColumn(f&quot;col{i}&quot;, lit(None)).cache()<br>        df = df.filter(df[f&quot;col{i}&quot;].isNotNull())<br>    return df</pre><p>Results with AQE on and off:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WpKmynOhMK957m7EJ43Kg.png" /><figcaption>AQE = True</figcaption></figure><p>And now, rdd.isEmpty() turned out to be the fastest! 😱</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v805jvWRZWpjBKJJPUVjdA.png" /><figcaption>AQE = False</figcaption></figure><p>Now, rdd.isEmpty() turns out to be the worst-performing method (I have increased the number of rows in the DataFrame and performed several runs). The rest of the methods show fairly similar performance. 😱</p><h3>⚠️ Conclusion: Don’t Rely on Assumptions!</h3><p>The final lesson is clear:<br> ✅ Spark is incredibly powerful, but performance can vary dramatically depending on the context.<br> ⚠️ In my experience AQE = True is a problem, not a solution ...<br> ✅ Always test different methods in your actual workflow before deciding on the “best” one!</p><p>I hope this little experiment inspires you to measure and compare in your own environment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62a087e83ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto Machine Learning and the Use of AutoGluon: Solving the Titanic Competition with…]]></title>
            <link>https://medium.com/sdg-group/auto-machine-learning-and-the-use-of-autogluon-solving-the-titanic-competition-with-1b8991f46ed0?source=rss-987b967557ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8991f46ed0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[autogluon]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[automl]]></category>
            <dc:creator><![CDATA[Ramon Sieira Martínez]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 11:01:41 GMT</pubDate>
            <atom:updated>2024-11-22T11:25:50.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pe6EYMFjJH4W1u21sSmhEw.png" /></figure><h3>Auto Machine Learning and the Use of AutoGluon: Solving the Titanic Competition with Interpretability</h3><p>Auto Machine Learning (AutoML) represents a paradigm that aims to democratize machine learning models by automating critical tasks such as model selection, hyperparameter optimization, and data preprocessing. Among the various available tools, <strong>AutoGluon</strong>, developed by Amazon, stands out for its ease of use and advanced capabilities. This article presents the advantages and disadvantages of AutoML, a practical case using AutoGluon to solve the classic Titanic competition on Kaggle, and uses the <strong>SHAP</strong> library for result interpretability.</p><h3>Introduction to AutoGluon</h3><h4>Why Choose It?</h4><p><strong>AutoGluon </strong>is an AutoML library designed for users with various levels of experience. Its main goal is to provide a solution that automatically optimizes results in common machine learning tasks such as:</p><ol><li><strong>Tabular classification and regression.</strong></li><li><strong>Time series prediction.</strong></li><li><strong>Text processing.</strong></li><li><strong>Image-related tasks (classification, detection).</strong></li></ol><h4>Advanced Capabilities of AutoGluon</h4><ol><li><strong>Automatic Model Ensembling:</strong> AutoGluon trains multiple models and combines the best ones through a weighted ensemble, improving robustness and generalization.</li><li><strong>Hyperparameter Optimization:</strong> It uses sophisticated techniques like Bayesian optimization to efficiently and quickly explore the hyperparameter space.</li><li><strong>Stacking:</strong> It allows stacking base models to capture complex relationships in the data and maximize predictive performance.</li><li><strong>Adaptability:</strong> It adjusts to system resources (CPU/GPU) to scale from local environments to cloud servers.</li><li><strong>Support for Heterogeneous Data:</strong> It can work with datasets that combine text, categorical, and numerical variables, automatically preprocessing the columns.</li></ol><h4>Configurable Parameters in AutoGluon</h4><p><strong>AutoGluon </strong>allows the adjustment of several parameters to customize training:</p><ul><li><strong>time_limit</strong>: Defines the maximum time in seconds to train the models. Example: time_limit=600 to train for 10 minutes.</li><li><strong>presets</strong>: Configures predefined strategies, such as &quot;best_quality&quot; (best performance) or &quot;fast_train&quot; (quick training).</li><li><strong>hyperparameters</strong>: Allows custom hyperparameters for the models to be specified. Example:</li></ul><pre>hyperparameters = {<br>      &#39;GBM&#39;: {&#39;num_boost_round&#39;: 100},<br>      &#39;NN&#39;: {&#39;num_epochs&#39;: 10}<br>  }<br>  predictor = TabularPredictor(label=&#39;Survived&#39;).fit(train_data=df_train, hyperparameters=hyperparameters)</pre><ul><li><strong>eval_metric</strong>: Defines the metric to evaluate the models. Example: eval_metric=&#39;accuracy&#39;.</li><li><strong>verbosity</strong>: Controls the level of detail in the logs. It can be 0 (silent) or higher for more information.</li><li><strong>excluded_model_types</strong>: Excludes certain models from the ensemble, such as excluded_model_types=[&#39;KNN&#39;].</li></ul><h3>Pros and Cons of AutoGluon</h3><h4>Pros</h4><ol><li><strong>Time-saving:</strong> It drastically reduces the time needed to iterate over models and configurations.</li><li><strong>Simplicity:</strong> Offers an intuitive API, making it accessible even to those with basic knowledge of machine learning.</li><li><strong>Competitive results:</strong> Its model combination and ensemble strategies make it highly competitive in tabular tasks.</li><li><strong>Detailed documentation:</strong> Includes examples and resources to get started quickly.</li></ol><h4>Cons</h4><ol><li><strong>Limited control:</strong> Automation means that certain aspects of the process, such as preprocessing, are not easily customizable.</li><li><strong>Resource consumption:</strong> Depending on the dataset, training can be computationally intensive.</li><li><strong>Model overfitting:</strong> Although <strong>AutoGluon </strong>facilitates model preparation, there are times when overfitting to the use case can occur, so care must be taken when partitioning and generating model validation.</li></ol><h3>Practical Case: Titanic Competition on Kaggle</h3><h4>Setting up the environment</h4><p>First, install AutoGluon and SHAP:</p><pre>pip install autogluon shap</pre><h4>Preparing the dataset</h4><p>Download the Titanic dataset from Kaggle and load the data:</p><pre>import pandas as pd<br># Load data<br>df_train = pd.read_csv(&#39;train.csv&#39;)<br>df_test = pd.read_csv(&#39;test.csv&#39;)</pre><h4>Exploration and Preprocessing</h4><p><strong>AutoGluon </strong>handles preprocessing automatically, but let’s ensure the columns are ready:</p><pre># Prepare target<br>df_train = df_train.drop(columns=[&#39;Name&#39;, &#39;Ticket&#39;, &#39;Cabin&#39;])<br>df_test = df_test.drop(columns=[&#39;Name&#39;, &#39;Ticket&#39;, &#39;Cabin&#39;])<br># Impute missing values<br>df_train.fillna(df_train.median(), inplace=True)<br>df_test.fillna(df_test.median(), inplace=True)</pre><h4>Training with AutoGluon</h4><p>AutoGluon requires specifying the target (Survived):</p><pre>from autogluon.tabular import TabularPredictor<br># Train predictor<br>predictor = TabularPredictor(label=&#39;Survived&#39;).fit(train_data=df_train, time_limit=300)<br># Make predictions<br>predictions = predictor.predict(df_test)</pre><h4>Evaluating the model</h4><p>You can check the leaderboard of the ensemble and its performance:</p><pre>leaderboard = predictor.leaderboard(df_train)<br>print(leaderboard)</pre><h3>Interpretability with SHAP</h3><p>Although <strong>AutoGluon </strong>optimizes the model, SHAP helps understand how variables affect predictions:</p><pre>import shap<br># Get the best-performing model<br>best_model = predictor.get_model_best()<br># Create explanations<br>explainer = shap.Explainer(best_model.predict, df_train.drop(columns=[&#39;Survived&#39;]))<br>shap_values = explainer(df_train.drop(columns=[&#39;Survived&#39;]))<br># Visualize explanations<br>shap.summary_plot(shap_values, df_train.drop(columns=[&#39;Survived&#39;]))</pre><h3>Final Thoughts</h3><p><strong>AutoGluon </strong>simplifies the model training and optimization process, delivering competitive results with minimal effort. Integrating tools like <strong>SHAP </strong>enhances interpretability, a crucial aspect of real-world projects. However, the use of AutoML does not replace machine learning knowledge. Understanding how and why a model works is essential to making informed and responsible decisions. <strong>AutoGluon </strong>is a powerful tool for those seeking efficiency without compromising quality.</p><h3>References</h3><ol><li><strong>AutoGluon — Official Documentation:</strong> <a href="https://auto.gluon.ai/stable/index.html">AutoGluon</a></li><li><strong>SHAP — Official Documentation:</strong> <a href="https://shap.readthedocs.io/en/latest/">SHAP</a></li><li><strong>Kaggle — Titanic Competition:</strong> <a href="https://www.kaggle.com/competitions/titanic">Titanic</a></li></ol><h3>Who we are</h3><p><strong>Ramón Sieira</strong> is an ML/AI Engineer and Senior AI/ML Consultant participating in the Data Science practice unit at SDG Group España. He has experience in different sectors such as banking, insurance, and energy, defining and implementing different use cases in AWS and Azure ecosystems. <a href="http://www.linkedin.com/in/rasieira">www.linkedin.com/in/rasieira</a></p><p><strong>Ángel Mora</strong> is an ML architect and specialist lead participating in the architecture and methodology area of the Data Science practice unit at SDG Group España. He has experience in different sectors such as pharmaceuticals, insurance, telecommunications, and utilities sectors, managing different technologies in the Azure and AWS ecosystems. <a href="https://www.linkedin.com/in/angelmoras/">https://www.linkedin.com/in/angelmoras/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8991f46ed0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sdg-group/auto-machine-learning-and-the-use-of-autogluon-solving-the-titanic-competition-with-1b8991f46ed0">Auto Machine Learning and the Use of AutoGluon: Solving the Titanic Competition with…</a> was originally published in <a href="https://medium.com/sdg-group">SDG Group</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Time Series: Predictions with Snowflake Cortex ML Functions and Prophet]]></title>
            <link>https://medium.com/sdg-group/mastering-time-series-predictions-with-snowflake-cortex-ml-functions-and-prophet-b61326db44ad?source=rss-987b967557ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b61326db44ad</guid>
            <category><![CDATA[prophet]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-model]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Ramon Sieira Martínez]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 10:35:06 GMT</pubDate>
            <atom:updated>2024-11-24T11:09:29.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pe6EYMFjJH4W1u21sSmhEw.png" /></figure><p>In today’s world, where predictive algorithms are increasingly integrated into various frameworks, evaluating their strengths and weaknesses is essential. Despite the growing use of these tools, there are few comparisons between standalone algorithms and more integrated solutions. In this scope, this article explores the use of Snowflake Cortex ML Functions and the Prophet library in Python for time series forecasting with seasonal patterns, highlighting the benefits of each approach and their impact on forecasting accuracy in different scenarios.</p><p>Thus, <strong>Section 1 (Data Preparation)</strong> covers the process of preparing time-series data using SQL queries.<strong> Section 2 (Creating Training and Testing Datasets)</strong> explains the division of the dataset into training and testing sets. <strong>Section 3 (Model Training)</strong> uses two approaches based on <strong>Snowflake Cortex ML Functions and Prophet and Python</strong>. <strong>Section 4 (Comparison of Both Approaches)</strong> compares the results obtained based on metrics such as MAE (Mean Absolute Error), MAPE (Mean Absolute Percentage Error), and RMSE (Root Mean Squared Error). Finally, in <strong>Section 5 we will find conclusions and future work.</strong></p><h3>1 . Data Preparation. Grouping and Aggregating Data</h3><p>In this step, an SQL query is executed to obtain the average of the values in the Y column grouped by hour from the date column DS. Here’s an explanation of each part:</p><ol><li><strong>DATE_TRUNC(‘HOUR’, DS)</strong>: This function takes the DS column, which contains date and time values, and rounds or truncates those values to the hour level. This means that any part of the date less than an hour (such as minutes or seconds) is removed, leaving only the hour of the day.</li><li><strong>AVG(Y) AS Y</strong>: Calculates the average of the values in the Y column for each hour grouped.</li><li><strong>FROM TIME_SERIES_SDG_EXAMPLES.PUBLIC.EXAMPLE</strong>: Specifies the table from which the data is being retrieved. In this case, the EXAMPLE table is located in the PUBLIC schema of the TIME_SERIES_SDG_EXAMPLES database.</li><li><strong>GROUP BY DATE_TRUNC(‘HOUR’, DS)</strong>: Groups the data by hour (the date truncated to the hour). This ensures that the average AVG(Y) is calculated for each distinct hour rather than for each individual record.</li></ol><pre>SELECT <br> DATE_TRUNC(&#39;HOUR&#39;, DS), <br> AVG(Y) AS Y <br>FROM <br> TIME_SERIES_SDG_EXAMPLES.PUBLIC.EXAMPLE<br>GROUP BY <br> DATE_TRUNC(&#39;HOUR&#39;, DS);</pre><p>This SQL query is creating or replacing a view called EXAMPLE_HOURLY that contains hourly aggregated data from the EXAMPLE table. Here’s an explanation of each part:</p><ul><li><strong>CREATE OR REPLACE VIEW EXAMPLE_HOURLY</strong>: A view named EXAMPLE_HOURLY is being created. If the view already existed, it is replaced with the new definition. A view is a saved query that can be treated like a table, making it easier to access the results without having to execute the query each time.</li><li><strong>SELECT DATE_TRUNC(‘HOUR’, DS) AS DS</strong>: The DS column is selected, and truncated to the hour level. By truncating the date, the minutes and seconds are removed, leaving only the part corresponding to the hour.</li><li><strong>AVG(Y) AS Y</strong>: The average of the values in the Y column is calculated for each truncated hour.</li><li><strong>FROM TIME_SERIES_SDG_EXAMPLES.PUBLIC.EXAMPLE</strong>: The data comes from the EXAMPLE table in the TIME_SERIES_SDG_EXAMPLES database.</li><li><strong>GROUP BY DATE_TRUNC(‘HOUR’, DS)</strong>: The data is grouped by the truncated hour so that the average is calculated over all records corresponding to the same hour.</li><li><strong>ORDER BY DATE_TRUNC(‘HOUR’, DS)</strong>: The result is ordered by hour, ensuring that the hours appear in chronological order.</li></ul><pre>CREATE OR REPLACE VIEW EXAMPLE_HOURLY AS <br>SELECT <br> DATE_TRUNC(&#39;HOUR&#39;, DS) AS DS, <br> AVG(Y) AS Y <br>FROM <br> TIME_SERIES_SDG_EXAMPLES.PUBLIC.EXAMPLE<br>GROUP BY <br> DATE_TRUNC(&#39;HOUR&#39;, DS) <br>ORDER BY <br> DATE_TRUNC(&#39;HOUR&#39;, DS);</pre><h3>2. Creating Training and Testing Data Sets</h3><p>This SQL query calculates the total number of records in the EXAMPLE_HOURLY view and divides those records into two sets: one for training and another for testing. Here’s an explanation of each part:</p><ul><li><strong>COUNT(*) AS TOTAL</strong>: Counts the total number of records in the EXAMPLE_HOURLY view and assigns it to the alias TOTAL.</li><li><strong>ROUND(COUNT(*) * 0.8) AS TRAIN</strong>: Calculates 80% of the total number of records and rounds it to the nearest integer, assigning it to the alias TRAIN. This value will represent the size of the training dataset.</li><li><strong>ROUND(COUNT(*) * 0.2) AS TEST</strong>: Calculates 20% of the total number of records, also rounded, and assigns it to the alias TEST. This will be the size of the testing dataset.</li><li><strong>FROM EXAMPLE_HOURLY</strong>: Indicates that the data comes from the EXAMPLE_HOURLY view, which contains the hourly aggregated data.</li></ul><pre>SELECT <br> COUNT(*) AS TOTAL, <br> ROUND(COUNT(*) * 0.8) AS TRAIN, <br> ROUND(COUNT(*) * 0.2) AS TEST <br>FROM <br> EXAMPLE_HOURLY;</pre><p>For model training, we create a view with the first X records (where X is the 80% of the total data):</p><pre>CREATE OR REPLACE VIEW EXAMPLE_TRAIN AS <br>SELECT * <br>FROM EXAMPLE_HOURLY<br>ORDER BY DS<br>LIMIT X;</pre><h3>3. Model Training</h3><p>For model training, we will follow two different approaches. In the first one, we will use <strong>Snowflake Cortex ML Functions</strong>, while for the second approach, we will make an approximation using <strong>Python’s Prophet</strong> library. Finally, we will compare both alternatives for model training.</p><h4>Building a Forecasting Model with Snowflake</h4><p>Next, we use Snowflake’s forecasting engine to create and train a forecasting model with the training data set obtained from the previous step.</p><p>This SQL script is creating and executing a <strong>forecasting model</strong> in Snowflake using the <strong>Machine Learning (ML)</strong> package. Here’s an explanation of each part:</p><p><strong>Creating or Replacing the Forecast Model</strong>:</p><ul><li>It creates a forecasting model called model1 or replaces it if it already exists.</li><li>The input data for the model comes from the EXAMPLE_TRAIN view, which contains the data used to train the model.</li><li>The timestamp column is specified as DS, and the target column (the one to be predicted) is Y.</li></ul><p><strong>Executing the Forecast Model</strong>:</p><ul><li>A block of code begins to execute multiple SQL statements.</li><li>It calls the model1 to perform the forecast for X time periods, which can represent days, hours, or any other time unit being used in the model.</li><li>The ID of the last executed query is stored in the variable x, allowing access to the forecast results.</li></ul><p><strong>Creating and Replacing a Table with Forecast Results:</strong></p><ul><li>It creates or replaces a table called EXAMPLE_FORECAST in the PUBLIC schema of the TIME_SERIES_SDG_EXAMPLES database.</li><li>It uses the RESULT_SCAN function to obtain the results of the forecast based on the stored ID in x, allowing access to the results generated by the forecasting model.</li></ul><pre>CREATE OR REPLACE SNOWFLAKE.ML.FORECAST model1 (<br> INPUT_DATA =&gt; SYSTEM$REFERENCE(&#39;VIEW&#39;, &#39;EXAMPLE_TRAIN&#39;),<br> TIMESTAMP_COLNAME =&gt; &#39;DS&#39;,<br> TARGET_COLNAME =&gt; &#39;Y&#39;<br>);<br>BEGIN<br> -- Execute the forecasting model for X time periods<br> CALL model1!FORECAST(FORECASTING_PERIODS =&gt; X);<br> LET x := SQLID;<br> <br> -- Create or replace a table with the forecast results<br> CREATE OR REPLACE TABLE TIME_SERIES_SDG_EXAMPLES.PUBLIC.EXAMPLE_FORECAST AS <br> SELECT * <br> FROM TABLE(RESULT_SCAN(:x));<br>END;</pre><p>In the image below, we can observe 2 series with 2 different colors. In <strong>blue</strong>, we have the <strong>real data</strong> used for testing, and finally, in <strong>yellow</strong>, we have the predicted Y, which is the <strong>prediction</strong> calculated by the time-series model generated with Snowflake ML Forecast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*O583848u9qA2ZcJODGPkxA.png" /></figure><h4>Building a Forecasting Model with Prophet and Python</h4><p>Next, we will implement a forecasting model with <strong>Prophet </strong>in Python expecting to improve results. Below is the code for training a Prophet model with the data from Snowflake.</p><p>This Python script uses the <strong>Snowflake Snowpark</strong> library and the <strong>Prophet</strong> library to perform time series forecasting in a Snowflake environment. Here’s a breakdown of each part of the code:</p><p><strong>1. Import Libraries</strong></p><ul><li><strong>snowflake.snowpark</strong>: This is the Snowpark library for working with Snowflake data in a more flexible way, allowing Python code to be executed directly on Snowflake.</li><li><strong>Prophet</strong>: This library is used for forecasting time series data.</li><li><strong>pandas</strong>: A powerful data manipulation library used to handle data in a DataFrame format.</li></ul><p><strong>2. Define the Main Function</strong></p><ul><li>The main function takes a session object, which is the Snowpark session used to interact with the Snowflake database.</li></ul><p><strong>3. Fetch Data from Snowflake</strong></p><ul><li><strong>source_table_name</strong>: This variable stores the name of the table in Snowflake that contains the training data for the forecast.</li><li><strong>Fetch data</strong>: The script retrieves data from the specified Snowflake table using the session.table() method.</li><li><strong>Convert to Pandas DataFrame</strong>: The Snowpark DataFrame is converted to a Pandas DataFrame using toPandas().</li><li><strong>Sort the DataFrame</strong>: The data is sorted by the DS column, which contains the timestamps.</li></ul><p><strong>4. Create and Fit the Prophet Model</strong></p><ul><li><strong>Model Initialization</strong>: A Prophet model instance is created.</li><li><strong>Column Renaming</strong>: The script renames the columns to match the expected format for Prophet (ds for timestamps and y for the target variable).</li><li><strong>Fit the Model</strong>: The model is trained using the fit() method on the DataFrame containing the time series data.</li></ul><p><strong>5. Making Predictions</strong></p><ul><li><strong>Future Dates</strong>: A DataFrame is created containing future dates for which predictions will be made. The script specifies that X periods into the future should be predicted with a frequency of 1 hour.</li><li><strong>Generate Forecast</strong>: Predictions are generated using the predict() method, and only relevant columns (ds, yhat, yhat_lower, yhat_upper) are retained for further processing.</li><li><strong>Rename Columns</strong>: The forecast columns are renamed to TS for timestamps, FORECAST for predicted values, LOWER_BOUND for the lower bound of the prediction interval, and UPPER_BOUND for the upper bound.</li></ul><p><strong>6. Convert and Save Forecast Data</strong></p><ul><li><strong>Convert to Snowpark DataFrame</strong>: The forecast results (in Pandas DataFrame format) are converted back to a Snowpark DataFrame.</li><li><strong>Save to Snowflake</strong>: The script writes the predictions to a new table in Snowflake, replacing any existing data in that table.</li></ul><p><strong>7. Return Forecast DataFrame</strong></p><ul><li>The function returns the Snowpark DataFrame containing the forecast results.</li></ul><pre>import snowflake.snowpark as snowpark<br>from snowflake.snowpark.functions import col<br>from prophet import Prophet<br>import pandas as pd<br>def main(session: snowpark.Session): <br> # Table name in Snowflake<br> source_table_name = &#39;TIME_SERIES_SDG_EXAMPLES.PUBLIC.EXAMPLE_TRAIN&#39;<br> <br> # Fetch data from Snowflake table<br> dataframe = session.table(source_table_name)<br> # Convert Snowflake DataFrame to Pandas<br> df = dataframe.toPandas()<br> df = df.sort_values(by=&#39;DS&#39;)<br> <br> # Create a Prophet model<br> model = Prophet()<br> # Rename columns to &#39;ds&#39; (DS) and &#39;y&#39; (Y) as per the data<br> df = df.rename(columns={&#39;DS&#39;: &#39;ds&#39;, &#39;Y&#39;: &#39;y&#39;})<br> <br> # Fit the model into our data<br> model.fit(df)<br> # Create a DataFrame with future dates to make predictions<br> future_dates = model.make_future_dataframe(periods=X, freq=&#39;1h&#39;, include_history=True)<br> # Make predictions<br> forecast = model.predict(future_dates)<br> forecast = forecast[[&#39;ds&#39;, &#39;yhat&#39;, &#39;yhat_lower&#39;, &#39;yhat_upper&#39;]]<br> forecast = forecast.rename(columns={&#39;ds&#39;: &#39;TS&#39;, &#39;yhat&#39;: &#39;FORECAST&#39;, &#39;yhat_lower&#39;: &#39;LOWER_BOUND&#39;, &#39;yhat_upper&#39;: &#39;UPPER_BOUND&#39;})<br> <br> # Convert the Pandas DataFrame of predictions to a Snowpark DataFrame<br> forecast_snowpark = session.createDataFrame(forecast)<br> <br> # Save predictions to a table in Snowflake<br> forecast_snowpark.write.mode(&quot;overwrite&quot;).save_as_table(&quot;TIME_SERIES_SDG_EXAMPLES.PUBLIC.EXAMPLE_PROPHET&quot;)<br> <br> return forecast_snowpark</pre><p>In the image below, we can observe 2 series with 2 different colors. In <strong>blue</strong>, we have the <strong>real data</strong> used for testing, and finally, in <strong>yellow</strong>, we have the predicted Y, which is the <strong>prediction</strong> calculated by the time-series model generated with Prophet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*fl8VgMwWhJw-67p5DUj7iw.png" /></figure><h3>4. Comparing Both Alternatives</h3><p>Next, we will utilize multiple time series to evaluate both approaches by comparing the actual values against the predictions generated by the model using various metrics. We will use MAE or the mean absolute error, MAPE or the mean absolute percentage error, and RMSE or the root mean square deviation.</p><p>In general:</p><p>· <strong>Mean Absolute Error (MAE):</strong> Measures the average magnitude of errors between predicted and actual values, without considering their direction. It provides an overall idea of the prediction accuracy.</p><p>· <strong>Mean Absolute Percentage Error (MAPE):</strong> Represents the error as a percentage of the actual values, providing a normalized error measure.</p><p>· <strong>Root Mean Square Error (RMSE):</strong> This is a measure of the square root of the average squared differences between the predicted and actual values. It is sensitive to large errors, making it useful for identifying significant deviations.</p><p>Thus, the following table shows the results obtained for both alternatives in the three metrics selected. As it can be seen, <strong>in all three metrics Python’s Prophet library presents better results than the Snowflake Cortex ML Functions.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*_Vq0S1rjPfZH9YHburMZbQ.png" /></figure><p>In general, when comparing the actual values, in this case, the test values, against the predictions from Snowflake ML Forecast, we obtain a <strong>Mean Absolute Percentage Error (MAPE)</strong> of <strong>0.055</strong>, a <strong>Root Mean Squared Error (RMSE)</strong> of <strong>152.39</strong> and a <strong>Mean Absolute Error (MAE) </strong>of<strong> 110.429</strong>. Compared to the SQL-only solution, Prophet offers two key improvements: we fill in past data and achieve a <strong>Mean Absolute Percentage Error (MAPE)</strong> of <strong>0.047</strong>, a <strong>Root Mean Squared Error (RMSE)</strong> of <strong>131.01</strong>, and a <strong>Mean Absolute Error (MAE) </strong>of <strong>98.35</strong>.</p><p>Based on these metrics, Prophet outperforms the Snowflake Cortex ML Functions across all three metrics on this use case scenario:</p><p>· Lower MAPE indicates that <strong>Prophet had fewer percentage errors overall</strong>, suggesting better-normalized accuracy.</p><p>· Lower RMSE and MAE values for <strong>Prophet show that its predictions were closer to the actual data, </strong>with fewer significant errors and a smaller average deviation.</p><p>As can be seen in the previous photos, Prophet allows us to add a forecast based on the training data, unlike Snowflake, which is only capable of filling in past values if we have exogenous variables and not just the value to be predicted.</p><p>It is important to highlight that no hyperparameter tuning has been performed in any of the models in this analysis. While Snowflake Cortex allows for some configuration (<a href="http://It is important to highlight that no hyperparameter tuning has been performed in any of the models in this analysis. While Snowflake Cortex allows for some configuration (https://docs.snowflake.com/en/sql-reference/classes/forecast/commands/createforecast), it is more limited compared to Prophet (https://facebook.github.io/prophet/docs/diagnostics.html), which offers greater tuning capabilities, making it a more powerful tool for complex predictive models.">https://docs.snowflake.com/en/sql-reference/classes/forecast/commands/createforecast</a>), it is more limited compared to Prophet (<a href="http://It is important to highlight that no hyperparameter tuning has been performed in any of the models in this analysis. While Snowflake Cortex allows for some configuration (https://docs.snowflake.com/en/sql-reference/classes/forecast/commands/createforecast), it is more limited compared to Prophet (https://facebook.github.io/prophet/docs/diagnostics.html), which offers greater tuning capabilities, making it a more powerful tool for complex predictive models.">https://facebook.github.io/prophet/docs/diagnostics.html</a>), which offers greater tuning capabilities, making it a more powerful tool for complex predictive models.</p><h3>5 . Conclusions and Future Work</h3><p>In conclusion, we found that Snowflake Cortex ML Functions is easier to use than Prophet, as it allows for the development of a machine learning model using only SQL. Regarding computation times, all notebooks in this article were run on the same Snowflake cluster (X-Small), yielding significantly different times. Snowflake Cortex ML Functions take approximately 6 minutes, while Prophet does not exceed 1 minute. <strong>Although Prophet may be more complex to train, especially if there is no prior experience with the model, it offers faster training times and better results than Snowflake Cortex ML Functions.</strong></p><p>In the future, it would be interesting to explore several improvements. Tuning hyperparameters could optimize model performance. Testing other time series models, such as ARIMA and LSTM, would provide very interesting comparisons. Additionally, integrating external data could enhance the model’s capabilities, either directly with Snowflake Cortex ML Functions or with Prophet. These directions are promising for future research.</p><p>Note: At the time of writing this article, there were no details on future changes to the new available algorithms. The analysis is based on the information and tools available at the time of editing.</p><p><strong>If you enjoyed this article and want to stay updated with new posts, don’t forget to click “Follow.” In the future, we will likely evaluate BigQuery with Vertex AI against Prophet. Stay tuned!</strong></p><p><strong>Who we are</strong></p><ul><li><strong>Ramón Sieira </strong>is an ML/AI Engineer and Senior AI/ML Consultant participating in the Data Science practice unit at SDG Group España. He has experience in different sectors such as banking, insurance, and energy, defining and implementing different use cases in AWS and Azure ecosystems. <a href="http://www.linkedin.com/in/rasieira">www.linkedin.com/in/rasieira</a></li><li><strong>Ángel Mora</strong> is an ML architect and specialist lead participating in the architecture and methodology area of the Data Science practice unit at SDG Group España. He has experience in different sectors such as pharmaceuticals, insurance, telecommunications, and utilities sectors, managing different technologies in the Azure and AWS ecosystems. <a href="https://www.linkedin.com/in/angelmoras/">https://www.linkedin.com/in/angelmoras/</a></li><li><strong>Rubén Martínez</strong> is a Data Scientist and specialist lead participating in the Business Science and Solution Design area of the Data Science Practice Unit at SDG Group España. He has experience in multiple sectors such as banking, insurance, retail, and utilities, defining and implementing different ML methodologies and algorithms. He also has relevant experience in data management and as a manufacturing process engineer. <a href="https://www.linkedin.com/in/rubenmartinezcovelo/">https://www.linkedin.com/in/rubenmartinezcovelo/</a></li><li><strong>Carlos Ortega</strong> is a seasoned Data Scientist and lead specialist with more than 30 years of experience, focusing primarily on consulting within the banking, telecommunications, and energy sectors at SDG Group Spain, within the Business Science and solution design area of the Data Science practice unit. His expertise is centered on implementing machine learning solutions and algorithms across these key industries. Additionally, Carlos is currently specializing in the pharmaceutical sector. <a href="https://www.linkedin.com/in/carlosortegafernandez/">https://www.linkedin.com/in/carlosortegafernandez/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b61326db44ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sdg-group/mastering-time-series-predictions-with-snowflake-cortex-ml-functions-and-prophet-b61326db44ad">Mastering Time Series: Predictions with Snowflake Cortex ML Functions and Prophet</a> was originally published in <a href="https://medium.com/sdg-group">SDG Group</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>