<?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 Gilberto Gutierrez on Medium]]></title>
        <description><![CDATA[Stories by Gilberto Gutierrez on Medium]]></description>
        <link>https://medium.com/@gilbertogutierrez?source=rss-8b1ff6972c3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*51e2-CkSwgg3FObtjNyZeA.jpeg</url>
            <title>Stories by Gilberto Gutierrez on Medium</title>
            <link>https://medium.com/@gilbertogutierrez?source=rss-8b1ff6972c3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:26:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gilbertogutierrez/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[The Future of Data Interaction: A Look at Google’s Evolving Family of AI Agents]]></title>
            <link>https://medium.com/google-cloud/the-future-of-data-interaction-a-look-at-googles-evolving-family-of-ai-agents-21eff03bd12b?source=rss-8b1ff6972c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/21eff03bd12b</guid>
            <category><![CDATA[data-science-agent]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[colab]]></category>
            <dc:creator><![CDATA[Gilberto Gutierrez]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 17:11:14 GMT</pubDate>
            <atom:updated>2025-06-28T03:06:03.716Z</atom:updated>
            <content:encoded><![CDATA[<p>The promise of a data-driven organization has always been clear, but the reality for the people on the ground — the engineers, analysts, and scientists — has often been a series of complex, time-consuming tasks. Building a data pipeline, asking a simple business question, or preparing data for a model all require specialized skills and significant manual effort. This is the fundamental challenge that Google’s new <strong>Applied AI</strong> strategy aims to solve.</p><p>This is the vision Google Cloud is bringing to life with its new family of <strong>generative AI-powered agents</strong>. At <a href="https://cloud.google.com/blog/topics/google-cloud-next/google-cloud-next-2025-wrap-up"><strong>Google Cloud Next </strong></a>’25, the company outlined a strategy focused on creating specialized agents for every data persona — from data engineers to analysts. As stated by Yasmeen Ahmad, Google’s Managing Director of Data Analytics, “<a href="https://www.techtarget.com/searchdatamanagement/news/366622068/Google-enters-new-era-of-AI-for-data-with-launch-of-agents">you need tailored, domain-specific agents that can help with specific tasks that data teams are doing and accelerate their work.</a>”</p><p>This family of agents includes:</p><ul><li>The <a href="https://cloud.google.com/blog/products/data-analytics/a-closer-look-at-bigquery-data-engineering-agent"><strong>Data Engineering Agent</strong></a> to help build and manage data pipelines.</li><li>The <a href="https://cloud.google.com/blog/products/business-intelligence/conversational-analytics-in-looker-is-now-in-preview"><strong>Looker Conversational Analytics Agent</strong></a> to bring natural language queries to business intelligence.</li><li>The <a href="https://cloud.google.com/blog/products/data-analytics/exploring-new-bigquery-data-canvas-ai-assistant-features"><strong>Data Canvas Assistant</strong></a> for AI-powered assistance directly in BigQuery.</li><li>And the focus of our post today: the <a href="https://developers.googleblog.com/en/data-science-agent-in-colab-with-gemini/"><strong>Data Science Agent</strong></a>.</li></ul><p>In this post, I’m going to introduce you to the first of these new teammates that I’ve had a chance to work with. I’ll show you how the Data Science Agent transforms a typical data analysis project from a multi-hour coding session into a fluid, conversational workflow.</p><p><strong>What is the Data Science Agent?</strong></p><p>At its core, the Data Science Agent is an AI assistant that lives within a notebook environment like Google Colab. You provide it with a high-level goal and a dataset, and it generates a complete Colab notebook — with Python code, natural language explanations, and visualizations — to accomplish your task.</p><p>What makes it truly powerful is its “agentic” workflow, powered by Google’s Gemini models. It doesn’t just translate your prompt into a static block of code. Instead, it:</p><ol><li><strong>Decomposes &amp; Plans:</strong> It takes your strategic goal and creates a logical, step-by-step plan, just like a senior data analyst would scope a project.</li><li><strong>Executes &amp; Reasons:</strong> It writes and runs code for each step. Crucially, it uses the output of that code (the results, charts, or even errors) as feedback to intelligently inform the next step.</li><li><strong>Self-Corrects:</strong> Because it uses this feedback loop, it can autonomously handle tasks like installing missing dependencies or correcting minor code errors without my intervention.</li></ol><p>While currently available in the consumer version of <a href="https://colab.google/"><strong>Google Colab</strong></a>, the plan to integrate the Data Science Agent into <a href="https://cloud.google.com/colab/docs/introduction"><strong>Colab Enterprise</strong></a> and <a href="https://cloud.google.com/bigquery/docs/notebooks-introduction"><strong>BigQuery Studio</strong></a> signals that this new mode of interaction is becoming a core part of the enterprise data stack.</p><p><strong>A Practical Example: From a CSV Upload to a Full Forecast</strong></p><p>To demonstrate this new paradigm, I’ll use a real-world marketing dataset and walk you through the exact conversational workflow I used to go from a simple question to a comparative forecast.</p><p><strong>My Goal:</strong> Forecast future ad impressions (impr_to_forecast) from my campaign data and determine if I should include a covariate to improve the model’s accuracy.</p><p><strong>Phase 1: Getting Started and Exploring the Data</strong></p><p>My interaction began not with complex data connection strings, but with a simple file upload. I started by uploading my csv file directly in the agent’s interface.</p><p><strong>My Initial Prompts:</strong> My first instructions to the agent were focused on understanding the data.</p><p>Prompt:<em> Load the data from “/content/AAP_SA360_Actual_Data.csv” into a Pandas DataFrame.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J40hczGSXD8dBdVM" /><figcaption>Data science agent is embedded in Google Colab</figcaption></figure><p>After I prompted the agent to load the data, it immediately generated the necessary Python code and displayed the first few rows of my DataFrame, confirming the file was loaded correctly.</p><p>Prompt:<em> Run a detailed EDA of my dataset and give me a summary of what you find.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/0*LpQ0pbh2JAPxbAIH" /><figcaption>Agent’s plan for the EDA</figcaption></figure><p><strong>The Agent’s Action:</strong> After loading the data, the agent analyzed my high-level request for an EDA and generated a comprehensive, multi-step plan for my review. This is a core feature of its agentic design — it scopes out the project before executing. The plan it presented was a complete roadmap for a thorough data exploration, including steps to load and inspect the data, calculate descriptive statistics, check for and visualize missing values, generate histograms and box plots for outlier detection, and create a correlation heatmap to understand relationships between all numerical variables. It effectively turned my one-sentence request into a full-fledged analysis plan, ready for my approval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*6JnUlogKZIF01GyN" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S7OQo2CoQWTMPSpz" /></figure><p><strong>The Agent’s Action:</strong> Upon my approval, the agent executed its EDA plan, populating the notebook with a rich set of insights. First, it generated a <strong>descriptive statistics</strong> table, giving me an immediate numerical summary of all my key metrics. It then tackled data quality by creating <strong>bar charts</strong> showing the exact count and percentage of missing values per column, which instantly visualized the data’s completeness and highlighted the columns that would need attention before modeling.</p><p>Following that, the agent automatically generated a grid of <strong>histograms</strong> to visualize the distribution of each numerical variable, revealing that many metrics were highly skewed — an important finding. To understand how these variables interact, it then created a <strong>correlation matrix heatmap</strong>. This gave me a powerful, bird’s-eye view of the entire dataset, immediately revealing strong positive correlations between cost, impr_to_forecast, and clicks_to_forecast.</p><p>To investigate the strongest of these relationships further, the agent produced a <strong>scatter plot</strong> specifically comparing impr_to_forecast and clicks_to_forecast. The resulting chart showed a clear, positive linear trend, visually confirming that as impressions rise, so do clicks. In just a few moments, the agent had performed a comprehensive EDA—from statistical summaries to targeted visualizations—that would have otherwise taken significant manual coding and analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*knD0ZsO2Gbs-ZAbD" /><figcaption>The Agent’s key findings for the EDA</figcaption></figure><p><strong>Phase 2: Building and Comparing Forecast Models</strong></p><p>With my initial exploration complete, I moved on to the core forecasting task. My goal was to build two models — one simple, one more complex — and see which performed better.</p><p><strong>My Modeling Prompts (A Continuous Conversation):</strong></p><p><strong>1. Building the Baseline Model:</strong></p><p>Prompt:<em> Let’s try our first forecasting model using prophet, I want to forecast impr_to_forecast with no covariates, create a new dataframe from “/content/AAP_SA360_Actual_Data.csv”, group the data by date and impr_to_forecast for the last 12 months of data (except for the last 30 days) and use that for training, give me the evaluation metrics (MAPE and MAE) comparing the last 30 days of available data vs the predicted values</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*VRJLCLgAOyAIMTUx" /><figcaption>Agent’s plan for the model</figcaption></figure><p><strong>The Agent’s Action:</strong> This single, high-level prompt set in motion a complete modeling workflow. The agent’s generated notebook was populated with the following sequence of actions, all without any manual coding from my end:</p><ol><li><strong>Library Import:</strong> It automatically added the necessary import statements for the Prophet library.</li><li><strong>Data Splitting:</strong> It correctly interpreted the date logic, splitting the prepared data into a training set (the last 12 months, excluding the most recent 30 days) and a test set (the final 30 days) to be used for evaluation.</li><li><strong>Model Training:</strong> The agent instantiated a Prophet model and trained it on the training dataset.</li><li><strong>Forecasting:</strong> It then created a future dataframe for the next 30 days and used the trained model to generate predictions.</li><li><strong>Evaluation:</strong> Finally, it calculated the <strong>Mean Absolute Percentage Error (MAPE)</strong> and <strong>Mean Absolute Error (MAE)</strong> by comparing the model’s predictions against the actual historical data from the test set. The resulting metrics were clearly displayed in the notebook’s output, giving me an immediate, quantitative measure of my baseline model’s performance.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xzlqhzNTvVlMQFtx" /><figcaption>The Agent’s key findings for the baseline model</figcaption></figure><p><strong>The Result:</strong> The agent’s key findings were remarkable. It confirmed the data was split correctly and reported a MAPE of 19.53% and an MAE of 4,418,171.99. While a good start, a nearly 20% average error suggested there was room for improvement, just as the agent noted in its insights.</p><p><strong>2. Visualizing the First Model:<br></strong>Prompt:<em> Now plot the last 10 days of historical data vs the predicted values in a time series chart, I want to see how close the predictions are</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D9c0G79L37x1gG_s" /><figcaption>Model’s accuracy is not great like our agent correctly pointed out</figcaption></figure><p><strong>3. Building the Advanced Model:</strong></p><p>Prompt:<em> Let’s see if we can improve the model, train a new model using prophet but this time include webvisits_to_forecast as a covariate. Use the same training and evaluation set and show the MAPE and MAE metrics</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*F5ShKk6hdn1o74aP5XjaOg.png" /><figcaption>Agent’s plan for the optimized model</figcaption></figure><p><strong>The Agent’s Action:</strong> This is where the agent’s contextual understanding really shone. It recognized that my request was not to start over, but to build upon our previous work. It generated a new, more sophisticated <strong>plan</strong> that included the crucial new steps for building a model with a covariate:</p><ol><li>First, it planned to <strong>prepare the data</strong> again, this time ensuring the DataFrame was structured correctly to include the webvisits_to_forecast column alongside the timestamp and target variable.</li><li>Crucially, it understood to use the <strong>exact same training and evaluation split</strong> as the previous model, ensuring a fair, apples-to-apples comparison of the results.</li><li>Its plan then outlined how it would train a new Prophet model, this time using the .add_regressor() method to incorporate the webvisits_to_forecast data.</li><li>Finally, it would generate new predictions and <strong>evaluate the new model</strong> using the same MAPE and MAE metrics for a direct comparison.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HDIlCUbqZkYLl94m" /><figcaption>The Agent’s key findings for the optimized model</figcaption></figure><p><strong>The Result:</strong> The improvement was immediate and substantial. The agent’s findings showed the new model, with the webvisits_to_forecast covariate, achieved a much lower MAE of 1,321,349.23 and a MAPE of just 6.18% — a massive improvement over our baseline!”</p><p><strong>4. Visualizing the Second Model:</strong></p><p>Prompt: <em>Now plot the last 10 days of historical data vs the predicted values using this new model in a time series chart, I want to see how close the predictions are.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tg5IBSoy7kjNCdpb" /><figcaption>The plot for the last 10 days visually confirms that the predicted values are much closer to the actual values with the covariate included.</figcaption></figure><p>The entire iterative workflow was completed without me writing any code, allowing me to focus solely on the analytical path and the model’s performance.</p><h3>The Future of Data Interaction is Collaborative</h3><p>This entire workflow highlights the core of Google’s Applied AI strategy. The interaction shifted from me being a <em>coder</em> to being a <em>director</em>. I set the strategic direction with my questions, and the agent handled the technical execution. This fluid, conversational partnership allowed me to move from a raw dataset to a predictive model in a fraction of the time it would normally take.</p><p>This is more than just a productivity boost; it’s a powerful glimpse into the future of data work. As Yasmeen Ahmad noted, we will eventually look back and say, “I can’t believe we used to do that.” As this family of agents becomes more deeply integrated into our daily tools, they will continue to automate the routine, freeing us to focus on what matters most: asking bigger questions and driving strategic decisions. I highly encourage you to try the Data Science Agent for yourself and experience this new way of interacting with data.</p><h3>Further Readings</h3><ul><li><strong>Try the Agent:</strong> Try the<a href="https://labs.google.com/code/dsa"> Data Science Agent in Google Labs</a> using the<a href="https://colab.google/"> Google Colab consumer version</a>.</li><li><strong>Official Announcements &amp; Industry News:</strong></li><li><a href="https://cloud.google.com/blog/products/data-analytics/data-analytics-innovations-at-next25">Data Analytics innovations at Google Cloud Next ‘25</a></li><li><a href="https://developers.googleblog.com/en/fully-reimagined-ai-first-google-colab/">A fully reimagined, AI-first Google Colab</a></li><li><a href="https://developers.googleblog.com/en/data-science-agent-in-colab-with-gemini/">Announcing the Data Science Agent in Colab with Gemini</a></li><li><a href="https://cloud.google.com/blog/products/data-analytics/ai-assisted-bigquery-data-preparation-now-ga">AI-assisted BigQuery data preparation now GA</a></li><li><a href="https://cloud.google.com/blog/products/data-analytics/exploring-new-bigquery-data-canvas-ai-assistant-features">Exploring new BigQuery data canvas and AI assistant features</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21eff03bd12b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/the-future-of-data-interaction-a-look-at-googles-evolving-family-of-ai-agents-21eff03bd12b">The Future of Data Interaction: A Look at Google’s Evolving Family of AI Agents</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From BQML Insights to Governed Quality: Predictive DQ with Dataplex AutoDQ]]></title>
            <link>https://medium.com/google-cloud/from-bqml-insights-to-governed-quality-predictive-dq-with-dataplex-autodq-59420deda750?source=rss-8b1ff6972c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/59420deda750</guid>
            <category><![CDATA[dataplex]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bqml]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[data-quality]]></category>
            <dc:creator><![CDATA[Gilberto Gutierrez]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 12:34:42 GMT</pubDate>
            <atom:updated>2025-06-19T03:27:37.614Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous <a href="https://medium.com/google-cloud/supercharge-your-data-quality-anomaly-detection-with-bigqueryml-22a46e573cb5">blog</a>, we explored the power of BigQuery ML, specifically using ARIMA_PLUS models and ML.DETECT_ANOMALIES, to uncover hidden anomalies and gain predictive insights into our data quality. We saw how BQML can identify deviations from learned patterns that traditional, static rules might miss.</p><p>But a crucial question follows: <strong>Now that we can detect these sophisticated, predictive anomalies with BQML, how do we effectively operationalize, govern, and scale these checks within a comprehensive data quality framework? How do we ensure these powerful insights translate into automated actions and alerts?</strong></p><p>This is where <strong>Google Cloud’s Dataplex AutoDQ</strong> steps in.</p><p>In this post, I’ll bridge the gap between standalone BQML anomaly detection and a fully governed data quality solution. I’ll demonstrate how to embed the predictive capabilities of your BigQuery ML models directly into<a href="https://cloud.google.com/dataplex/docs/auto-data-quality-overview"> Dataplex AutoDQ</a>. This approach allows you to leverage BQML’s intelligence for identifying complex issues, all while benefiting from Dataplex’s robust framework for scheduling, management, and alerting.</p><p>While Dataplex also supports essential rule-based and profile-based data quality checks (and I’ll provide links for deeper dives into those topics at the end of the blog), my focus today is squarely on <strong>supercharging AutoDQ with BQML’s predictive power.</strong></p><p>To make this tangible, I’ll walk through a practical example: detecting anomalous spikes or dips in daily Bitcoin transaction counts from public datasets, showcasing how this BQML-driven predictive check is configured and managed within Dataplex.</p><p><strong>Understanding Predictive Data Quality with Dataplex and BQML</strong></p><p><strong>What is Dataplex AutoDQ?</strong></p><p>Dataplex AutoDQ is a managed data quality service within Google Cloud’s Dataplex. It helps you define, execute, monitor, and manage data quality checks across your data lake and data warehouse. It supports various rule types, from predefined checks to powerful custom SQL assertions, enabling a centralized approach to data quality governance.</p><p><strong>Briefly: Rule-Based &amp; Profile-Based DQ in Dataplex</strong></p><p>Dataplex AutoDQ allows for standard rule-based validations (e.g., checking for uniqueness, non-nulls, regex patterns) and can also generate rule recommendations based on data profiling (e.g., identifying if the percentage of unique values in a column changes unexpectedly). These form the foundation of a solid DQ strategy.</p><p><strong>What is “Predictive Data Quality” in this Context?</strong></p><p>Predictive Data Quality, as I’ll implement it, involves using machine learning models — specifically BigQuery ML time-series models (ARIMA_PLUS) — to learn historical patterns, trends, and seasonality within your data. The BQML model then <em>predicts</em> an expected range for new data points. Data points falling significantly outside this dynamically learned range are flagged as anomalies. This approach is powerful because it adapts to your data’s evolving behavior and can detect “unknown unknowns” that predefined static rules or simple statistical thresholds might miss.</p><p><strong>The Integration: BQML Models within Dataplex AutoDQ Custom SQL Rules</strong></p><p>The magic happens by leveraging Dataplex AutoDQ’s<a href="https://cloud.google.com/dataplex/docs/use-auto-data-quality#example-custom-rules"> Custom SQL Rule</a> capability. We can embed a BigQuery ML<a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-detect-anomalies"> ML.DETECT_ANOMALIES</a> function call within this custom SQL. This means Dataplex orchestrates the data quality scan, and as part of that scan, it executes the SQL rule, which in turn calls the pre-trained BQML model to perform the anomaly detection on the latest data. This synergy allows you to operationalize sophisticated ML-driven checks within a governed environment.</p><p><strong>Why is this Combination Powerful?</strong></p><ul><li><strong>Predictive Power of BQML:</strong> Utilizes sophisticated time-series models to understand complex data patterns beyond human-defined rules.</li><li><strong>Governance &amp; Orchestration of Dataplex:</strong> Provides a centralized platform for managing, scheduling, and monitoring these advanced DQ checks alongside all other DQ rules.</li><li><strong>Automated Alerting:</strong> Leverages Dataplex’s integration with Cloud Logging and alerting infrastructure.</li><li><strong>Holistic DQ View:</strong> These predictive checks run as part of your overall Dataplex DQ strategy, offering a comprehensive view of data health.</li></ul><p><strong>Practical Application: Detecting Anomalies in Daily Bitcoin Transaction Volume</strong></p><p><strong>Scenario:</strong> My goal is to monitor the daily number of Bitcoin transactions using the BigQuery public dataset. I want Dataplex to alert me if a particular day’s transaction count is anomalously high or low compared to the recently learned trend and any weekly patterns. This could indicate significant market events, network congestion, or even issues with a data pipeline if I were ingesting this data myself.</p><p><strong>The Data:</strong> I’ll use the<a href="https://console.cloud.google.com/marketplace/product/bitcoin/crypto-bitcoin"> bigquery-public-data.crypto_bitcoin</a> dataset. I’m interested in the block_timestamp to derive a daily count of transactions.</p><p><strong>Tools:</strong></p><ul><li><strong>BigQuery:</strong> For data storage, preparation, and BQML model training.</li><li><strong>Dataplex:</strong> For AutoDQ scan configuration, execution, and alerting.</li></ul><p><strong>Step 1: Prepare Data &amp; Train BQML Anomaly Detection Model (in BigQuery)</strong></p><p><strong>Data Preparation (Daily Transaction Counts):</strong> First, I’ll create a table that aggregates the total number of Bitcoin transactions per day. This will be my time-series data for the model.</p><p><strong>A Note on Price vs. Transaction Count:</strong> A common instinct is to monitor an asset’s price for anomalies. However, the standard BigQuery Bitcoin public dataset contains <strong>on-chain data</strong> (blocks, transactions) and not <strong>off-chain market prices</strong> (which are determined on exchanges). While you absolutely could use this BQML + Dataplex pattern to monitor prices, you would first need to ingest daily price data from an external API into your own BigQuery table. To ensure this tutorial is fully reproducible for everyone using only public datasets, I will focus on <strong>transaction count</strong> — a powerful, readily available metric that reflects the network’s fundamental activity.</p><pre>CREATE OR REPLACE TABLE `your_project.your_dataset.daily_bitcoin_transactions` AS<br>SELECT<br>EXTRACT(DATE FROM block_timestamp) AS transaction_date,<br>COUNT(*) AS total_transactions<br>FROM<br>`bigquery-public-data.crypto_bitcoin.transactions`<br>-- Optional: Add a WHERE clause to limit the historical range if needed for performance,<br>-- e.g., WHERE EXTRACT(DATE FROM block_timestamp) &gt;= DATE_SUB(CURRENT_DATE(), INTERVAL 3 YEAR)<br>GROUP BY<br>transaction_date<br>HAVING<br>COUNT(*) &gt; 0 -- Ensure days with transactions are included<br>ORDER BY<br>transaction_date;</pre><p><strong>Train the BQML ARIMA_PLUS Model:</strong> Next, I’ll train an<a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-time-series"> ARIMA_PLUS</a> model on this historical daily transaction data. This model will learn the typical patterns, including any trends or weekly seasonality.</p><pre>CREATE OR REPLACE MODEL `your_project.your_dataset.bitcoin_daily_tx_anomaly_model`<br>OPTIONS(<br>MODEL_TYPE=&#39;ARIMA_PLUS&#39;,<br>TIME_SERIES_TIMESTAMP_COL=&#39;transaction_date_ts&#39;, -- Alias for the timestamp column<br>TIME_SERIES_DATA_COL=&#39;total_transactions&#39;,<br>AUTO_ARIMA=TRUE,<br>DATA_FREQUENCY=&#39;DAILY&#39;,<br>DECOMPOSE_TIME_SERIES=TRUE,<br>CLEAN_SPIKES_AND_DIPS=FALSE, -- I want to detect these as anomalies<br>ADJUST_STEP_CHANGES=FALSE<br>) AS<br>SELECT<br>CAST(transaction_date AS TIMESTAMP) AS transaction_date_ts, -- BQML expects a TIMESTAMP<br>total_transactions<br>FROM<br>`your_project.your_dataset.daily_bitcoin_transactions`<br>WHERE<br>transaction_date &lt; DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY); -- Example: Use data older than last 30 days for training</pre><p>My bitcoin_daily_tx_anomaly_model is now trained to identify what constitutes an ‘unusual’ number of daily transactions.</p><p><strong>Step 2: Configure Dataplex AutoDQ Custom SQL Rule</strong></p><p>Now, I’ll configure a Dataplex Data Quality scan. This scan will target the table where my daily Bitcoin transaction counts are stored.</p><ul><li>I’ll define a “Custom SQL Rule.” This rule will use my BQML model to check the latest data. Dataplex will flag a rule failure if my SQL query returns any rows (which, in this case, will be the detected anomalies).</li></ul><pre>-- This SQL will be used as the custom SQL rule in Dataplex. <br>-- It returns rows for any daily transaction counts identified as anomalous.<br>SELECT<br>  predictions.transaction_date_ts AS anomaly_date,<br>  predictions.total_transactions AS actual_transactions,<br>  predictions.anomaly_probability,<br>  predictions.lower_bound,<br>  predictions.upper_bound<br>FROM<br>  ML.DETECT_ANOMALIES(<br>    MODEL `your-project-id.your_dataset.bitcoin_daily_tx_anomaly_model`,<br>    STRUCT(<br>        0.05 AS anomaly_prob_threshold -- Adjust as needed<br>    ),<br>    (<br>-- This subquery should select the NEW data Dataplex is currently scanning. <br>-- In a real Dataplex setup for incremental scans, you might use Dataplex-provided variables <br>-- or date logic to select only the latest data slice. For example:<br>      SELECT<br>        CAST(transaction_date AS TIMESTAMP) AS transaction_date_ts,<br>        total_transactions<br>      FROM<br>        `your-project-id.your_dataset.daily_bitcoin_transactions`<br>      WHERE<br>        transaction_date &gt;= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY) AND transaction_date &lt; CURRENT_DATE() -- Example: Check yesterday&#39;s data<br>    )<br>  ) AS predictions<br>WHERE<br>  predictions.is_anomaly = TRUE -- No semicolon at the end since AutoDQ doesn&#39;t like it ;)</pre><ul><li>In Dataplex, I’ll configure this SQL as a custom check. I’ll set the rule to <strong>fail if this query returns one or more rows</strong>.</li><li>I’ll assign this rule to the Volume dimension, as this check validates the expected number of records over time, which aligns perfectly with Dataplex&#39;s predefined dimension concepts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2s-igMQe1dVS16lMVp3xtA.png" /></figure><p><strong>Step 3: Running the Scan and Interpreting Results in Dataplex</strong></p><p>When the Dataplex DQ scan runs, if my BQML model (via the custom SQL) identifies any days with an anomalous number of transactions, Dataplex will flag the rule as failed. The Dataplex UI will show the results, and you can configure Dataplex to <strong>export the detailed results of every scan to a BigQuery table</strong>. This results table is the key to creating a powerful feedback loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCwi8jRiN4ltoMDYKzPiPQ.png" /></figure><p><strong>Step 4: Analyzing and Visualizing the Results</strong></p><p>Detecting an anomaly is the first step; understanding and communicating it is next. While the Dataplex UI provides scan results, the real power comes from analyzing the exported results in BigQuery.</p><p>Using your business intelligence (BI) tool of choice (like Looker Studio, Power BI, Tableau, etc.) connected to these BigQuery result tables, you can build powerful visualizations:</p><ul><li><strong>Anomaly Deep Dive:</strong> The most important chart is a time-series plot of your metric (in this case, total_transactions over time). On this chart, you can overlay the anomalous points identified by your Dataplex rule. Highlighting these specific points in a different color makes it immediately obvious when and where a potential issue occurred. For extra context, you can also plot the lower_bound and upper_bound from the BQML model as a shaded “confidence band” around the normal data.</li><li><strong>Data Quality Trend:</strong> By aggregating the results from all your Dataplex rules (not just the predictive one), you can create a high-level “Data Quality Score” for each day (e.g., % of rules passed). Plotting this score over time reveals whether your overall data quality is improving or degrading, which is a crucial metric for data governance.</li></ul><p>Visualizing these results moves you from just <em>detecting</em> issues to truly <em>monitoring</em> and <em>managing</em> the health of your data over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXmsbKUStAQqsW9oxZe47w.png" /></figure><p>Feel free to grab my template from <a href="https://lookerstudio.google.com/reporting/e7f47c37-d2cc-40bd-9a17-c57577a1ac8b/page/RpZOF">here</a>. You just need to create a copy and reconnect it to your DQ results table in BigQuery.</p><p><strong>Step 5: Alerting with Dataplex</strong></p><p>Dataplex integrates with Cloud Logging. You can<a href="https://cloud.google.com/dataplex/docs/alerts-notifications"> configure log-based alerts</a> in Cloud Monitoring. If the “Bitcoin Transaction Anomaly” rule fails, an alert can be triggered, notifying the relevant teams via Email, Slack, PagerDuty, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZODa5kT3SNc_pCFQdONX2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dq3xxymEqDmrk9S71Oi_9Q.png" /></figure><p><strong>Why This Approach is “Predictive”</strong></p><p>This method is “predictive” because it’s not reliant on fixed thresholds. The ARIMA_PLUS model learns the underlying <em>pattern</em> of daily Bitcoin transactions, which might include complex trends and weekly seasonality. An “anomaly” is a statistically significant deviation from this <em>learned, dynamic pattern</em>.</p><p><strong>Key Considerations &amp; Best Practices</strong></p><p><strong>BQML Model Management:</strong></p><ul><li><strong>Retraining:</strong> Periodically retrain the model to adapt to major shifts in market behavior.</li><li><strong>Training Window:</strong> Carefully select the training window to capture relevant patterns.</li></ul><p><strong>Dataplex Scan Configuration:</strong></p><ul><li><strong>Incremental Scans:</strong> For evolving datasets, configure incremental scans in Dataplex to efficiently check only new data.</li></ul><p><strong>Threshold Tuning:</strong> The anomaly_prob_threshold in ML.DETECT_ANOMALIES is crucial. Test and adjust based on desired sensitivity.</p><p><strong>Cost Management:</strong> Be mindful of costs for BQML model training/prediction, Dataplex DQ scan execution, and data storage.</p><p><strong>Beyond Time-Series: Other BQML Models:</strong></p><ul><li>This pattern is incredibly flexible. While I used ARIMA_PLUS for time-series, you could embed other types of<a href="https://cloud.google.com/bigquery/docs/anomaly-detection-overview"> BigQuery ML models</a> into Dataplex custom rules. For example, you could train a<a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-glm"> LOGISTIC_REGRESSION</a> model to predict if a given transaction is likely fraudulent based on its features. Your Dataplex rule could then use ML.PREDICT to flag new transactions that the model identifies as having a high probability of being fraudulent. This extends predictive DQ beyond time-series into row-level validation.</li><li><strong>Complementary Strategy:</strong> Use this predictive approach alongside foundational rule-based and profile-based checks in Dataplex for a holistic DQ strategy.</li></ul><p><strong>Conclusion</strong></p><p>Moving beyond traditional data quality methods is essential for truly robust data governance. By combining the intelligent pattern recognition of BigQuery ML models with the orchestration, management, and alerting capabilities of Dataplex AutoDQ, I can build powerful <em>predictive</em> data quality checks.</p><p>This approach, as demonstrated with the Bitcoin daily transaction example, allows us to detect subtle, unexpected anomalies that static rules would miss. It operationalizes my BQML insights, providing earlier warnings and deeper trust in my critical data assets. I encourage you to start exploring predictive DQ by embedding BQML in Dataplex to proactively safeguard your data pipelines and analytics.</p><h3>Further Readings</h3><ul><li><strong>[1] Google Cloud: Dataplex Auto Data Quality Overview:</strong><a href="https://cloud.google.com/dataplex/docs/auto-data-quality-overview"> https://cloud.google.com/dataplex/docs/auto-data-quality-overview</a></li><li><strong>[2] Google Cloud: Using Custom SQL Rules in Dataplex DQ:</strong><a href="https://cloud.google.com/dataplex/docs/use-auto-data-quality#example-custom-rules"> https://cloud.google.com/dataplex/docs/use-auto-data-quality#define-custom-sql-rules</a></li><li><strong>[3] Google Cloud: BigQuery ML ML.DETECT_ANOMALIES function:</strong><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-detect-anomalies"> https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-detect-anomalies</a></li><li><strong>[4] Google Cloud: BigQuery ML Supported Models:</strong><a href="https://cloud.google.com/bigquery/docs/anomaly-detection-overview"> https://cloud.google.com/bigquery/docs/bqml-introduction#models</a></li><li><strong>[5] BigQuery Public Dataset: Bitcoin:</strong><a href="https://console.cloud.google.com/marketplace/product/bitcoin/crypto-bitcoin"> https://console.cloud.google.com/marketplace/product/bitcoin/crypto-bitcoin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59420deda750" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/from-bqml-insights-to-governed-quality-predictive-dq-with-dataplex-autodq-59420deda750">From BQML Insights to Governed Quality: Predictive DQ with Dataplex AutoDQ</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Data Quality: Anomaly Detection with BigQueryML]]></title>
            <link>https://medium.com/google-cloud/supercharge-your-data-quality-anomaly-detection-with-bigqueryml-22a46e573cb5?source=rss-8b1ff6972c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/22a46e573cb5</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[bigquery-ml]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Gilberto Gutierrez]]></dc:creator>
            <pubDate>Mon, 05 May 2025 20:37:36 GMT</pubDate>
            <atom:updated>2025-05-06T03:25:03.627Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of data-driven decisions, undetected data quality issues can silently sabotage your analytics, lead to flawed insights, and erode trust in your data. How often have critical datasets experienced unexpected drops in row counts, a sudden surge in NULLs, or bizarre metric fluctuations that went unnoticed until it was too late?</p><p>Fortunately, Google BigQuery ML offers a powerful, scalable way to move from reactive data fire-fighting to proactive data quality monitoring. By first training a machine learning model and then leveraging the <strong>ML.DETECT_ANOMALIES</strong> function, you can supercharge your data quality checks and catch these issues early.</p><p>In this post, we’ll explore how to use BigQueryML’s anomaly detection capabilities for robust data quality monitoring. We’ll cover what it involves, why it’s particularly effective for data quality, and walk through practical SQL examples to get you started.</p><h3>Understanding ML.DETECT_ANOMALIES for Data Quality</h3><p><strong>What it is:</strong></p><p>BigQuery ML’s <strong>ML.DETECT_ANOMALIES</strong> function is a powerful tool for identifying outliers or unexpected patterns in your data.</p><p>You first need to create and train a model of a supported type — such as <strong>ARIMA_PLUS</strong> or <strong>ARIMA_PLUS_XREG</strong> for time-series data, or K-means, PCA, or Autoencoder models for other types of anomaly detection tasks. Once the model is trained, <strong>ML.DETECT_ANOMALIES</strong> uses this model to identify data points that deviate significantly from the patterns it has learned.</p><p>For time-series data quality checks, like monitoring daily row counts or key metrics over time, you’ll typically train an <strong>ARIMA_PLUS</strong> model on your historical data. The <strong>ML.DETECT_ANOMALIES</strong> function then uses this model to flag anomalies.</p><p>A key option during the training of an <strong>ARIMA_PLUS</strong> model for anomaly detection purposes is <strong>DECOMPOSE_TIME_SERIES=TRUE</strong>. This allows <strong>ML.DETECT_ANOMALIES</strong> to effectively identify anomalies within the historical data the model was trained on, as well as on new, unseen data.</p><p><strong>Why it’s useful for Data Quality Monitoring:</strong></p><p><strong>Model-Driven &amp; Proactive Detection:</strong> Instead of relying solely on manual checks or static threshold rules, <strong>ML.DETECT_ANOMALIES</strong> leverages a machine learning model trained on your data’s historical patterns. This allows for more nuanced and proactive detection of issues like:</p><ul><li>Sudden, significant drops or spikes in table row counts.</li><li>Unexpected increases in NULL value percentages in critical columns.</li><li>Unusual shifts or outliers in key business metrics (e.g., average transaction value, daily active users).</li><li>Changes in the distribution or frequency of categorical values.</li></ul><p><strong>Efficiency &amp; Scalability:</strong> Leverage BigQuery’s massive parallel processing power to monitor petabyte-scale datasets efficiently. No need to move data or manage separate anomaly detection infrastructure.</p><p><strong>SQL-Based Workflow:</strong> Define your model training and anomaly detection steps using familiar SQL, integrating seamlessly into your existing BigQuery data pipelines and ELT processes.</p><p><strong>Customizable Sensitivity:</strong> During the anomaly detection step, you can fine-tune sensitivity using parameters like <strong>anomaly_prob_threshold</strong> to balance catching more anomalies versus reducing false positives.</p><p><strong>Rich Output:</strong> The function returns clear indicators like <strong>is_anomaly</strong> (TRUE/FALSE), <strong>anomaly_probability</strong>, and often <strong>expected_value</strong> or <strong>lower_bound</strong>/<strong>upper_bound</strong>, making it easier to understand and act on the detected anomalies.</p><h3>Practical Application: Monitoring Data Quality with ML.DETECT_ANOMALIES</h3><p>Let’s walk through an example of monitoring the daily row count of a critical table. Unexpected large drops could indicate an ETL failure, while sudden large spikes might suggest data duplication or an upstream issue. This now involves a two-step process: training a model and then detecting anomalies.</p><p><strong>Example: Detecting Anomalies in Daily Table Row Counts</strong></p><p><strong>Step 1: Train an ARIMA_PLUS Model on Historical Row Counts</strong></p><p><strong>Preparing the Training Data:</strong></p><ul><li>First, we need a historical time series of row counts for the table we want to monitor. We can generate this by querying <strong>INFORMATION_SCHEMA.PARTITIONS</strong> (for partitioned tables) or by regularly recording row counts into a dedicated metadata table.</li><li>For this example, let’s assume we have a table <strong>your_project.your_dataset.my_table_daily_counts_history</strong> with <strong>time_series_timestamp_col</strong> (TIMESTAMP) and <strong>time_series_data_col</strong> (INT64 representing the row count).<br> SQL</li></ul><pre>- Sample data preparation (if not already existing)<br>CREATE OR REPLACE TABLE `your_project.your_dataset.my_table_daily_counts_history` AS<br>SELECT<br>CAST(PARSE_DATE(&#39;%Y%m%d&#39;, partition_id) AS TIMESTAMP) AS time_series_timestamp_col, - Adjust if your partition_id is different<br>total_rows AS time_series_data_col<br>FROM<br>`your_project.your_dataset.your_partitioned_table.INFORMATION_SCHEMA.PARTITIONS`<br>WHERE<br>partition_id IS NOT NULL AND CAST(PARSE_DATE(&#39;%Y%m%d&#39;, partition_id) AS DATE) &lt; CURRENT_DATE() - Use historical data for training<br>ORDER BY<br>time_series_timestamp_col;</pre><p><strong>Create and Train the Model:</strong></p><ul><li>Now, we create an <strong>ARIMA_PLUS</strong> model. The <strong>DECOMPOSE_TIME_SERIES = TRUE</strong> option is important as it helps in identifying anomalies later by analyzing the decomposed components of the time series (trend, seasonality, residuals).</li></ul><pre>CREATE OR REPLACE MODEL `your_project.your_dataset.dq_row_count_anomaly_model`<br>OPTIONS(<br>MODEL_TYPE=&#39;ARIMA_PLUS&#39;,<br>TIME_SERIES_TIMESTAMP_COL=&#39;time_series_timestamp_col&#39;,<br>TIME_SERIES_DATA_COL=&#39;time_series_data_col&#39;,<br>AUTO_ARIMA=TRUE,<br>DATA_FREQUENCY=&#39;AUTO_FREQUENCY&#39;, - Or specify &#39;DAILY&#39;, &#39;HOURLY&#39;, etc.<br>DECOMPOSE_TIME_SERIES=TRUE,<br>CLEAN_SPIKES_AND_DIPS=FALSE, - For DQ, we often want to detect these, not clean them from the model training<br>ADJUST_STEP_CHANGES=FALSE<br>) AS<br>SELECT<br>time_series_timestamp_col,<br>time_series_data_col<br>FROM<br>`your_project.your_dataset.my_table_daily_counts_history`;</pre><p><strong>Step 2: Detect Anomalies using the Trained Model</strong></p><p><strong>Detecting Anomalies on Historical (Training) Data or New Data:</strong></p><ul><li>Once the model is trained, you can use <strong>ML.DETECT_ANOMALIES</strong>. If you pass the same historical data (or no data, relying on the model’s training data if <strong>DECOMPOSE_TIME_SERIES</strong> was true), it can find anomalies within that period. More commonly for ongoing DQ, you’d pass new data to this function.</li><li>Let’s assume we want to check the most recent day’s row count, which is in a table (or could be a query) called <strong>your_project.your_dataset.my_table_daily_counts_today</strong> with the same column names (<strong>time_series_timestamp_col</strong>, <strong>time_series_data_col</strong>).</li></ul><pre>- Example: Detecting anomalies in new (e.g., data for today)<br>SELECT<br>*<br>FROM<br>ML.DETECT_ANOMALIES(<br>MODEL `your_project.your_dataset.dq_row_count_anomaly_model`,<br>TABLE `your_project.your_dataset.my_table_daily_counts_today`, - Or use a (SELECT … FROM … WHERE date = CURRENT_DATE())<br>STRUCT(0.05 AS anomaly_prob_threshold) - Detects anomalies outside the 95% confidence interval<br>)<br>WHERE<br>is_anomaly = TRUE; - Only show the anomalous recordss</pre><ul><li>If you wanted to re-evaluate the training data for anomalies (useful for understanding the model and past issues):</li></ul><pre>- Example: Detecting anomalies in the original training data<br>- This relies on DECOMPOSE_TIME_SERIES=TRUE during model creation.<br>SELECT<br>*<br>FROM<br>ML.DETECT_ANOMALIES(<br>MODEL `your_project.your_dataset.dq_row_count_anomaly_model`,<br>STRUCT(0.05 AS anomaly_prob_threshold)<br> - No input table/query means it evaluates anomalies over its training data<br>)<br>WHERE<br>is_anomaly = TRUE;</pre><p><strong>Explanation of Parameters in ML.DETECT_ANOMALIES:</strong></p><ul><li><strong>MODEL your_project.your_dataset.dq_row_count_anomaly_model</strong>: Specifies the pre-trained BQML model to use.</li><li><strong>TABLE your_project.your_dataset.my_table_daily_counts_today</strong> (or a query): This is the <em>input data</em> you want to check for anomalies. Its schema must match what the model expects (e.g., time_series_timestamp_col, time_series_data_col).</li><li><strong>STRUCT(anomaly_prob_threshold AS value)</strong>: Defines the significance level. A value of 0.05 means data points with less than a 5% probability of occurring normally (or outside the 95% confidence interval generated by the model) are flagged as anomalies.</li></ul><p><strong>Interpreting the Output:</strong> The query will return rows from your input data that are flagged as anomalies. Key output columns include:</p><ul><li><strong>is_anomaly</strong> (BOOL): <strong>TRUE</strong> if the data point is an anomaly.</li><li><strong>anomaly_probability</strong> (FLOAT64): The probability that the data point is an anomaly.</li><li>The original data columns from your input (e.g., <strong>time_series_timestamp_col</strong>, <strong>time_series_data_col</strong>).</li><li><strong>lower_bound</strong>, <strong>upper_bound</strong> (FLOAT64): The expected range for the data point based on the model.</li><li><strong>expected_value</strong> (FLOAT64): The value predicted by the model.</li></ul><p><em>(Visual Mention: You could then visualize your actual data alongside </em><strong><em>lower_bound</em></strong><em> and </em><strong><em>upper_bound</em></strong><em> over time in a tool like Looker Studio, highlighting the points where </em><strong><em>is_anomaly = TRUE</em></strong><em>. This would clearly show the unexpected deviations. I will show you how in my next blog post)</em></p><h3>Key Considerations and Best Practices</h3><p><strong>Model Training Matters:</strong></p><ul><li><strong>DECOMPOSE_TIME_SERIES=TRUE</strong>: During <strong>ARIMA_PLUS</strong> model creation, this is essential if you want <strong>ML.DETECT_ANOMALIES</strong> to properly identify anomalies within the historical training data or if your data has trends/seasonality.</li><li><strong>CLEAN_SPIKES_AND_DIPS and ADJUST_STEP_CHANGES</strong>: For data quality anomaly detection, you typically set these to <strong>FALSE</strong> during model training because you <em>want</em> to detect these events as anomalies, not have the model automatically clean or adjust for them during its learning phase.</li><li><strong>Sufficient Historical Data for Training:</strong> <strong>ARIMA_PLUS</strong> models need enough historical data to learn patterns, trends, and seasonality.</li></ul><p><strong>Parameter Tuning in ML.DETECT_ANOMALIES:</strong></p><ul><li><strong>anomaly_prob_threshold</strong>: This is the most direct way to control sensitivity when calling <strong>ML.DETECT_ANOMALIES</strong>.</li><li><strong>Data Granularity and Regularity:</strong> Ensure your time series data is at a consistent granularity (e.g., hourly, daily) and that timestamps are regular for best model training results.</li><li><strong>Iterative Refinement &amp; Domain Knowledge:</strong> Anomaly detection isn’t always “set it and forget it.” Expect to iterate. Use your domain knowledge to interpret results and adjust parameters or model training as needed.</li></ul><p><strong>Operationalizing Your Checks:</strong></p><ul><li><strong>Scheduling:</strong> Schedule both model re-training (periodically, as needed) and the <strong>ML.DETECT_ANOMALIES</strong> queries (e.g., daily after ETL).</li><li><strong>Alerting:</strong> Integrate the output with alerting mechanisms (e.g., saving anomaly results to a table for BI tool monitoring, or using Dataplex AutoDQ which I will cover in my next blog post).</li><li><strong>Logging Results:</strong> Store the results of your anomaly detection runs to track effectiveness.</li></ul><p><strong>Cost Consideration:</strong> Model training (<strong>CREATE MODEL</strong>) and anomaly detection (<strong>ML.DETECT_ANOMALIES</strong>) both incur BigQuery processing costs. Plan accordingly.</p><h3>Choosing the Right BQML Model for Data Quality Anomaly Detection</h3><p>While this post focuses on using <strong>ARIMA_PLUS</strong> with <strong>ML.DETECT_ANOMALIES</strong> for time-series based data quality checks (like monitoring row counts or metrics over time), BigQuery ML supports other model types that can be used with <strong>ML.DETECT_ANOMALIES</strong> for different kinds of data quality scenarios:</p><p><strong>ARIMA_PLUS / ARIMA_PLUS_XREG:</strong></p><ul><li><strong>Best for:</strong> Time-series data where you’re looking for unusual deviations from historical trends, seasonality, or forecasted values. Examples: sudden spikes/dips in daily transaction counts, unexpected changes in average error rates over time.</li><li><strong>Considerations:</strong> Requires a time-series dataset for training. <strong>ARIMA_PLUS_XREG</strong> allows incorporating external regressors which might be relevant for more complex DQ checks influenced by known external factors.</li></ul><p><strong>K-Means (MODEL_TYPE=’KMEANS’)</strong></p><ul><li><strong>Best for:</strong> Detecting anomalies in multi-dimensional numerical data that isn’t necessarily time-series. It can identify data points that are far from any learned cluster centroids, potentially indicating anomalous combinations of feature values.</li><li><strong>Considerations:</strong> Requires you to choose the number of clusters (<strong>num_clusters</strong> option). Feature scaling is often important.</li></ul><p><strong>PCA (MODEL_TYPE=’PCA’)</strong></p><ul><li><strong>Best for:</strong> Anomaly detection based on reconstruction error in high-dimensional numerical data. Points that are poorly reconstructed from the principal components might be anomalous.</li><li><strong>Considerations:</strong> You need to choose the number of principal components.</li></ul><p><strong>Autoencoder (MODEL_TYPE=’AUTOENCODER’)</strong></p><ul><li><strong>Best for:</strong> Similar to PCA, using reconstruction error, but with neural networks, potentially capturing more complex non-linear relationships. Good for finding records that don’t conform to the general structure learned by the autoencoder.</li><li><strong>Considerations:</strong> More complex to train and tune (e.g., hidden units, activation functions).</li></ul><p><strong>For the common data quality use case of monitoring a specific metric over time, ARIMA_PLUS paired with ML.DETECT_ANOMALIES is a very effective and SQL-friendly approach.</strong> This blog post has focused on this pattern.</p><h3>Conclusion</h3><p>Maintaining high data quality is non-negotiable in today’s analytical landscape. BigQuery ML’s <strong>CREATE MODEL</strong> and <strong>ML.DETECT_ANOMALIES</strong> functions provide a scalable, SQL-native solution to move beyond manual checks and simplistic rule-based systems.</p><p>By training models on your data’s historical patterns and integrating anomaly detection into your workflows, you can proactively identify data issues, reduce the time to detection, and ultimately build greater trust and reliability in your data assets.</p><p>Whether you’re monitoring table volumes, tracking critical data metrics, or ensuring data consistency, BigQuery ML offers the tools to supercharge your data quality strategy. I encourage you to experiment with these capabilities and tailor them to your specific data quality challenges.</p><h3>Further Readings</h3><ul><li><strong>[1] Google Cloud Documentation: The ML.DETECT_ANOMALIES function:</strong><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-detect-anomalies"> https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-detect-anomalies</a></li><li><strong>[2] Google Cloud Documentation: Anomaly detection overview in BigQuery:</strong><a href="https://cloud.google.com/bigquery/docs/anomaly-detection-overview"> https://cloud.google.com/bigquery/docs/anomaly-detection-overview</a></li><li><strong>[3] Google Cloud Documentation: CREATE MODEL statement for ARIMA_PLUS models:</strong><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-time-series"> https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-time-series</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22a46e573cb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/supercharge-your-data-quality-anomaly-detection-with-bigqueryml-22a46e573cb5">Supercharge Your Data Quality: Anomaly Detection with BigQueryML</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Time Series and Hierarchical Time Series Forecasting Made Easy Using BigQueryML]]></title>
            <link>https://medium.com/google-cloud/multi-time-series-and-hierarchical-time-series-forecasting-made-easy-using-bigqueryml-3bbbb218bc56?source=rss-8b1ff6972c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bbbb218bc56</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[bigquery-ml]]></category>
            <dc:creator><![CDATA[Gilberto Gutierrez]]></dc:creator>
            <pubDate>Wed, 15 May 2024 16:54:43 GMT</pubDate>
            <atom:updated>2024-05-16T05:16:38.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Not long ago I wrote a <a href="https://medium.com/google-cloud/bigquery-demystifying-arima-plus-vs-arima-plus-xreg-for-time-series-forecasting-08a068c0b20c">blog post</a> that delves into the time series models supported in BigQuery and how to select the best one for your use case. In this new article, I’ll walk you through 2 different approaches that are useful when you want to forecast multiple time series using a single query alongside guidance with examples on how to choose the most convenient one depending on your needs.</p><p><strong>1. Multi-Time Series Forecasting</strong></p><p><strong>What it is:</strong> The process of simultaneously generating forecasts for multiple time series (sets of data points ordered in time). Instead of building individual models for each series, BQ lets you create a set of time series models to forecast multiple time series using a single query. Additionally, all time series models are fitted simultaneously.</p><p><strong>Why it’s useful:</strong></p><ul><li><strong>Efficiency:</strong> Saves time and resources by consolidating modeling efforts.</li><li><strong>Flexibility:</strong> Offers univariate time series forecasting (ARIMA_PLUS) with planned expansion to include multivariate capabilities (ARIMA_PLUS_XREG).</li><li><strong>Scalability:</strong> Ideal for scenarios with a large number of time series. You can forecast up to 100,000,000 time series simultaneously by using the <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-time-series#time_series_id_col">time_series_id_col</a> option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sr164asnSUpx_E5i" /><figcaption>Large-scale Time Series Architecture in BigQuery</figcaption></figure><p><strong>Example:</strong></p><p>Imagine we wanted to forecast the number of impressions for a specific website by deviceSegment, accountType and account. Instead of building separate models for each time series, we can use BigQuery ML’s ARIMA_PLUS to train a single model on all of them:</p><pre>CREATE OR REPLACE MODEL<br> `mydataset.mymodel` OPTIONS (model_type = &#39;ARIMA_PLUS&#39;,<br>   time_series_timestamp_col = &#39;date&#39;,<br>   time_series_data_col = &#39;total_impressions&#39;,<br>   time_series_id_col = [&#39;deviceSegment&#39;,<br>   &#39;accountType&#39;,<br>   &#39;account&#39;],<br>   auto_arima = TRUE,<br>   clean_spikes_and_dips = FALSE,<br>   adjust_step_changes = FALSE,<br>   data_frequency = &#39;AUTO_FREQUENCY&#39;,<br>   auto_arima_max_order = 2,<br>   decompose_time_series = TRUE) AS<br>SELECT<br> deviceSegment,<br> accountType,<br> account,<br> date AS date,<br> SUM(impr_to_forecast) AS total_impressions<br>FROM<br> `myproject.mydataset.mytable`<br>WHERE<br> date BETWEEN DATE(&#39;2023-06-07&#39;)<br> AND DATE(&#39;2024-02-29&#39;)<br>GROUP BY<br> deviceSegment,<br> accountType,<br> account,<br> date;</pre><p>Since we created a multi-time series model, we can examine the <strong>evaluation results</strong> for <a href="https://cloud.google.com/bigquery/docs/arima-speed-up-tutorial#step_four_evaluate_forecasting_accuracy_for_each_time_series">each time series</a> or by <a href="https://cloud.google.com/bigquery/docs/arima-speed-up-tutorial#step_five_evaluate_the_overall_forecasting_accuracy_for_all_the_time_series">all the time series</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DoVmMtxKiyIOtYZ8" /><figcaption>Evaluation Results For Each Time Series</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*qxkf4K5zC7ORIG1t" /><figcaption>Evaluation Results For All Time Series</figcaption></figure><p>The result is a comprehensive set of forecasts, one for each time series, generated with a single <a href="https://cloud.google.com/bigquery/docs/arima-multiple-time-series-forecasting-tutorial#optional_step_nine_use_your_model_to_forecast_multiple_time_series_simultaneously">query</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dC2jco2dtts2w01t" /><figcaption>Multi-Time Series Forecasting Output</figcaption></figure><p>Multi-time series forecasting offers efficiency and scalability. However, to take your forecasting to the next level and unlock insights from hierarchical structures in your data, you can leverage hierarchical forecasting with automatic reconciliation.</p><p><strong>2. Hierarchical Forecasting</strong></p><p><strong>What it is:</strong> A forecasting approach where time series are organized into a hierarchical structure (like a tree). The hierarchy can reflect relationships based on product categories, geographical regions, or other relevant groupings. Forecasts are generated at different levels of the hierarchy, allowing for a balance between granular and aggregate predictions.</p><p><strong>Why it’s useful:</strong></p><ul><li><strong>Reconciliation:</strong> Ensures that forecasts at different levels of the hierarchy are consistent (e.g., the sum of product-level forecasts should match the category-level forecast).</li><li><strong>Flexibility:</strong> BQ incorporates the <a href="https://otexts.com/fpp2/bottom-up.html">bottom-up reconciliation approach</a> in univariate time series forecasting (ARIMA_PLUS). Multivariate forecasting (ARIMA_PLUS_XREG) is coming soon.</li><li><strong>Improved accuracy:</strong> Often leads to more accurate forecasts than treating each series independently.</li></ul><p><strong>Example:</strong></p><p>BigQuery ML’s ARIMA_PLUS allows us to build on our previous exercise and create hierarchical forecasts. By treating deviceSegment, accountType, and account as a hierarchical structure, we can generate forecasts at each level and seamlessly aggregate them:</p><pre>CREATE OR REPLACE MODEL<br> `mydataset.mymodel` OPTIONS (model_type = &#39;ARIMA_PLUS&#39;,<br>   time_series_timestamp_col = &#39;date&#39;,<br>   time_series_data_col = &#39;total_impressions&#39;,<br>   time_series_id_col = [&#39;deviceSegment&#39;,<br>   &#39;accountType&#39;,<br>   &#39;account&#39;],<br>   hierarchical_time_series_cols = [ &#39;accountType&#39;,<br>   &#39;deviceSegment&#39;],<br>   auto_arima = TRUE,<br>   clean_spikes_and_dips = FALSE,<br>   adjust_step_changes = FALSE,<br>   data_frequency = &#39;AUTO_FREQUENCY&#39;,<br>   auto_arima_max_order = 2,<br>   decompose_time_series = TRUE) AS<br>SELECT<br> deviceSegment,<br> accountType,<br> account,<br> date AS date,<br> SUM(impr_to_forecast) AS total_impressions<br>FROM<br> `myproject.mydataset.mytable`<br>WHERE<br> date BETWEEN DATE(&#39;2023-06-07&#39;)<br> AND DATE(&#39;2024-02-29&#39;)<br>GROUP BY<br> deviceSegment,<br> accountType,<br> account,<br> date;</pre><p><strong>The </strong><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-time-series#hierarchical_time_series_cols"><strong>hierarchical_time_series_cols</strong></a><strong> parameter</strong> indicates that we are creating a hierarchical forecast based on a set of columns. Each of these columns are rolled up and aggregated. From our previous query, <strong>deviceSegment </strong>is rolled up to show forecasts for each <strong>accountType </strong>and <strong>account. </strong>Separately, both <strong>accountType </strong>and <strong>deviceSegment </strong>are also rolled up to show forecasts for each <strong>account</strong>.The column order is important because it defines the structure of the hierarchy (columns specified in the <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-time-series#time_series_id_col">time_series_id_col</a> option), in our case, account -&gt; accountType -&gt; deviceSegment.</p><pre>SELECT<br> *<br>FROM<br> ML.FORECAST( MODEL `mydataset.mymodel`,<br>   STRUCT(7 AS horizon,<br>     0.8 AS confidence_level))<br>ORDER BY<br> account,<br> accountType,<br> deviceSegment,<br> forecast_timestamp;</pre><p>Notice how the aggregated forecast is displayed at an account level first (deviceSegment=NULL, accountType=NULL, account=AAP Funded Shopping) followed by accountType level (deviceSegment=NULL, accountType=Bing Ads, account=AAP Funded Shopping) and finally by deviceSegment level (deviceSegment=Desktop, accountType=Bing Ads, account=AAP Funded Shopping):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1XqSj-0HOZOLiCzU" /><figcaption>Hierarchical Forecasting Output in BigQuery</figcaption></figure><p>The bottom-up reconciliation will allow us to have all the levels correctly rolled up to their parent levels (deviceSegment rolls up to the accountType level and accountType rolls up to account level)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x1ArEEHiiIrHgFqq" /><figcaption>Hierarchical Forecasting Output in Google Sheets</figcaption></figure><p><strong>Which One to Choose</strong></p><ul><li><strong>Multi-Time Series Forecasting:</strong> Ideal when you have a large number of time series and want an efficient and scalable solution.</li><li><strong>Hierarchical Forecasting:</strong> Suitable when your time series have a natural hierarchical structure, and you need to ensure consistency across different levels of the hierarchy.</li></ul><p><strong>In Conclusion</strong></p><p>BigQuery ML empowers you to efficiently forecast numerous time series, whether they are independent or hierarchically structured. By leveraging the tools and techniques discussed in this post, you can unlock valuable insights from your data, enhance your forecasting accuracy, and ultimately make more informed decisions for your business.</p><p><strong>Further Readings</strong></p><p>[1] Google, <a href="https://cloud.google.com/bigquery/docs/arima-multiple-time-series-forecasting-tutorial">Multiple time-series forecasting with a single query for NYC Citi Bike trips</a></p><p>[2] Google, <a href="https://cloud.google.com/bigquery/docs/arima-speed-up-tutorial">Scalable forecasting with millions of time-series in BigQuery</a></p><p>[3] Google, <a href="https://cloud.google.com/bigquery/docs/arima-time-series-forecasting-with-hierarchical-time-series">Hierarchical time series forecasting</a></p><p>[4] Rob J Hyndman and George Athanasopoulos, <a href="https://otexts.com/fpp2/hts.html">Hierarchical time series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bbbb218bc56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/multi-time-series-and-hierarchical-time-series-forecasting-made-easy-using-bigqueryml-3bbbb218bc56">Multi-Time Series and Hierarchical Time Series Forecasting Made Easy Using BigQueryML</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BigQuery: Demystifying ARIMA_PLUS vs ARIMA_PLUS_XREG for Time Series Forecasting]]></title>
            <link>https://medium.com/google-cloud/bigquery-demystifying-arima-plus-vs-arima-plus-xreg-for-time-series-forecasting-08a068c0b20c?source=rss-8b1ff6972c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/08a068c0b20c</guid>
            <category><![CDATA[bigquery-ml]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Gilberto Gutierrez]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 16:20:53 GMT</pubDate>
            <atom:updated>2024-05-29T16:19:14.140Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was asked to do a time series forecasting POC for one of my customers in the Retail Industry that was exploring Google Cloud tools, and as many of you have probably seen, BigQuery provides powerful tools for time series analysis, and two of its forecasting functions can sometimes cause confusion: ARIMA_PLUS and ARIMA_PLUS_XREG. Both utilize ARIMA (Autoregressive Integrated Moving Average) models, but with a key difference in handling explanatory variables. It is critical to understand when to use one vs the other and before I show you how to know which one is better for your use case, let’s delve into what makes these 2 models distinct and how to choose the right one for your forecasting needs.</p><p><strong>ARIMA_PLUS: A Self-Contained Forecasting Machine for Univariate Use Cases</strong></p><p>ARIMA_PLUS is a versatile function that builds forecasts based solely on the historical data you provide. It follows a three-step process:</p><ol><li><strong>Model Identification:</strong> It analyzes the time series to identify patterns and seasonality.</li><li><strong>Model Fitting:</strong> Based on the identified patterns, it estimates the parameters of an ARIMA model (p,d,q values).</li><li><strong>Forecasting:</strong> It leverages the fitted model to predict future values.</li></ol><p>ARIMA_PLUS is a solid choice when you want to forecast a time series without the influence of external factors. It’s particularly useful for:</p><ul><li><strong>Short-term forecasting:</strong> When you need to predict values for the immediate future based solely on past trends.</li><li><strong>Data with minimal external influences:</strong> When the time series you’re analyzing isn’t significantly affected by external variables.</li></ul><p><strong>ARIMA_PLUS_XREG: When External Variables Come into Play for Multivariate Use Cases</strong></p><p>ARIMA_PLUS_XREG introduces the power of explanatory variables into the forecasting mix. It incorporates these additional data points alongside the historical time series to build a more comprehensive model.</p><p>Here’s how it works:</p><ol><li><strong>Model Identification:</strong> Similar to ARIMA_PLUS, it analyzes the time series and explanatory variables.</li><li><strong>Model Fitting:</strong> It estimates the parameters of an ARIMA model that considers both the time series and the explanatory variables.</li><li><strong>Forecasting:</strong> It uses the fitted model to generate forecasts that take into account the impact of the explanatory variables.</li></ol><p>ARIMA_PLUS_XREG shines when you have relevant external data that can influence your forecasts.</p><p><strong>Keeping it simple, if you have variables you suspect have a correlation with your target metric, start with ARIMA_PLUS_XREG and then compare it with ARIMA_PLUS to see which one performs better.</strong></p><p>One way to find if there’s correlation between the variables in your dataset is by using <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/statistical_aggregate_functions#corr">pearson correlation</a> (like I did) in BQ to understand their behavior across your categorical columns. Pearson correlation is ideal for continuous data with a suspected linear relationship. In my use case, one of the target metrics was total impressions a web site gets at a given date and the results looked as follows.</p><p>At a timeseries_identifier (concatenation of all the categorical columns) level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kd341g6UB5iaL3umn9Pbsw.png" /><figcaption>Correlation by Timeseries Identifier</figcaption></figure><p>At a timeseries level (day):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmINwi1xVvTSSU7O_CkV3A.png" /><figcaption>Correlation by Day</figcaption></figure><p>Since we now know impressions, clicks and web visits show from moderate to high correlation in the majority of our observations (this kind of analysis is also helpful to spot any outliers in our data), we can proceed by including them in our XREG model.</p><pre>CREATE OR REPLACE MODEL<br>  `mydataset.Model_Impressions_XREG` OPTIONS (model_type = &#39;ARIMA_PLUS_XREG&#39;,<br>    time_series_timestamp_col = &#39;date&#39;,<br>    time_series_data_col = &#39;total_impressions&#39;,<br>    auto_arima = TRUE,<br>    clean_spikes_and_dips = FALSE,<br>    adjust_step_changes = FALSE,<br>    data_frequency = &#39;AUTO_FREQUENCY&#39;) AS<br>SELECT<br>  date AS date,<br>  SUM(impr_to_forecast) AS total_impressions,<br>  SUM(clicks_to_forecast) AS total_clicks,<br>  SUM(webvisits_to_forecast) AS total_webvisits<br>FROM<br>  `mydataset.mydata`<br>WHERE<br>  date BETWEEN DATE(&#39;2023-06-07&#39;)<br>  AND DATE(&#39;2024-02-29&#39;)<br>GROUP BY<br>  date;</pre><p><strong>One super important thing to keep in mind after you train the model,</strong> when using ARIMA_PLUS_XREG model for getting evaluation metrics and for getting predictions, <strong>make sure you provide the external regressors as well</strong>, which as you might’ve already guessed by now, those are going to be unknown for future data and therefore, you’ll have to use ARIMA_PLUS to predict the external variables first and use those as input for the ARIMA_PLUS_XREG model.</p><p>Note how I’m including 2 other ARIMA_PLUS models (trained with the same data and time periods as the ARIMA_PLUS_XREG model) to get the external regressors and include those outputs as inputs for our just trained model:</p><pre>SELECT<br>  *<br>FROM<br>  ML.evaluate(MODEL `mydataset.Model_Impressions_XREG`,<br>    (<br>    SELECT<br>      date,<br>      SUM(total_impressions) AS total_impressions,<br>      SUM(total_clicks) AS total_clicks,<br>      SUM(total_webvisits) AS total_webvisits<br>    FROM (<br>      SELECT<br>        date,<br>        SUM(impr_to_forecast) AS total_impressions,<br>        NULL AS total_clicks,<br>        NULL AS total_webvisits<br>      FROM<br>        `mydataset.mydata`<br>      WHERE<br>        date &gt; DATE(&#39;2024-02-29&#39;)<br>        AND date &lt;= DATE(DATE_ADD(&#39;2024-02-29&#39;, INTERVAL 20 day))<br>      GROUP BY<br>        date<br>      UNION ALL<br>      SELECT<br>        date,<br>        NULL AS total_impressions,<br>        SUM(total_clicks) AS total_clicks,<br>        SUM(total_webvisits) AS total_webvisits<br>      FROM (<br>        SELECT<br>          EXTRACT(DATE<br>          FROM<br>            forecast_timestamp) AS date,<br>          CAST(forecast_value AS int64) AS total_clicks,<br>          NULL AS total_webvisits<br>        FROM<br>          ML.FORECAST(MODEL `mydataset.Model_Clicks`,<br>            STRUCT(20 AS horizon,<br>              0.8 AS confidence_level))<br>        UNION ALL<br>        SELECT<br>          EXTRACT(DATE<br>          FROM<br>            forecast_timestamp) AS date,<br>          NULL AS total_clicks,<br>          CAST(forecast_value AS int64) AS total_webvisits<br>        FROM<br>          ML.FORECAST(MODEL `mydataset.Model_WebVisits`,<br>            STRUCT(20 AS horizon,<br>              0.8 AS confidence_level)))<br>      GROUP BY<br>        date )<br>    GROUP BY<br>      date),<br>    STRUCT( TRUE AS perform_aggregation,<br>      20 AS horizon));</pre><p>In my case, this is what it looks like when getting evaluation metrics (comparing model’s results with factual data from March):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbGLldDmqduEoYQBqSKczw.png" /><figcaption>ARIMA_PLUS_XREG evaluation metrics</figcaption></figure><p>I compared the previous results with an ARIMA_PLUS model for the same target metric (impressions) and this is what I got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L25qkkgYZaxyRbA6EiAkKg.png" /><figcaption>ARIMA_PLUS evaluation metrics</figcaption></figure><p>We can see that the mean_absolute_percentage_error is lower in the ARIMA_PLUS_XREG model and therefore we’ll get better predictions out of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPIGOLCPGfUw0sB-PY3VgQ.png" /><figcaption>ARIMA_PLUS prediction results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rczk2wN4yj71etgQKxTdHQ.png" /><figcaption>ARIMA_PLUS_XREG prediction results</figcaption></figure><p><strong>In Conclusion</strong></p><p>BigQuery’s ARIMA forecasting functions provide flexibility for various time series analysis needs. By understanding the strengths of ARIMA_PLUS and ARIMA_PLUS_XREG, you can select the right tool to generate accurate and insightful forecasts, empowering better decision-making for your business.</p><p><strong>Remember:</strong> Data exploration is key! Before diving into forecasting, visualize your time series and identify potential explanatory variables. This initial step will guide you towards the most suitable BigQuery function for your specific use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08a068c0b20c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/bigquery-demystifying-arima-plus-vs-arima-plus-xreg-for-time-series-forecasting-08a068c0b20c">BigQuery: Demystifying ARIMA_PLUS vs ARIMA_PLUS_XREG for Time Series Forecasting</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>