<?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 Shobhit Singh on Medium]]></title>
        <description><![CDATA[Stories by Shobhit Singh on Medium]]></description>
        <link>https://medium.com/@shobs?source=rss-8e877be7bd56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*a0WUm8NzbUJ-fE3O</url>
            <title>Stories by Shobhit Singh on Medium</title>
            <link>https://medium.com/@shobs?source=rss-8e877be7bd56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:43:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shobs/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[Enable BigQuery Agents in Gemini Enterprise via End User Credentials]]></title>
            <link>https://medium.com/google-cloud/enable-bigquery-agents-in-gemini-enterprise-via-end-user-credentials-079b1dc24406?source=rss-8e877be7bd56------2</link>
            <guid isPermaLink="false">https://medium.com/p/079b1dc24406</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[gemini-enterprise]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Shobhit Singh]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 15:25:25 GMT</pubDate>
            <atom:updated>2026-03-31T02:31:42.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fine-grained access to your Data Analytics Agents</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcNDQe1kXbat55iwUEe3Fw.png" /></figure><blockquote>BigQuery offers open-source Agentic Tools designed to power Data Analytics AI agents within the Agent Development Kit (ADK). A key enhancement is the ability to accept access tokens from external sources. Complementing this, Google’s Gemini Enterprise serves as a comprehensive platform for agent management, providing custom OAuth configurations for each registered agent. By integrating these capabilities, organizations can deploy Data Analytics Agents within Gemini Enterprise that strictly adhere to each user’s specific data access privileges.</blockquote><h3>Introduction</h3><p>Gemini Enterprise allows you to connect to your custom agent via Agent Engine, enabling the agents built by your organization that follow your company policies to serve Gemini Enterprise users. In this blog post we combine the power of the BigQuery agentic tools in Agent Development Kit (ADK) with Gemini Enterprise, allowing organizations to unlock natural language data analytics with fine-grained access control at scale. By deploying custom BigQuery agents to Vertex AI Agent Engine and registering them within the Gemini Enterprise ecosystem, users can interact with their datasets using simple conversational queries. This post provides a detailed walkthrough on setting up this end-to-end integration, from OAuth authorization to the final agent registration.</p><h3>Why End-User Credentials and Gemini Enterprise?</h3><p>This integration solves a critical problem for enterprise data applications: <strong>governance and granular access control</strong>.</p><p>When an agent is deployed to Vertex AI Agent Engine using the default method, it typically operates under a single service account. This means every user who interacts with the agent has the exact same permissions, potentially granting broad, unauthorized access to sensitive data, such as BigQuery tables that should only be visible to specific end-users.</p><p>The combined ADK and Gemini Enterprise approach offers a solution that delivers true <strong>End-User Credential (EUC) authentication</strong>:</p><ul><li><strong>Enforce Least Privilege and Trust: </strong>The agent acts <em>on behalf of the end-user</em>, accessing resources — like running BigQuery queries — only with the permissions granted to that specific user. This creates an unambiguous audit trail and enforces the security principle of least privilege, which is essential for enterprise compliance and trust.</li><li><strong>Eliminate Custom OAuth Handlers: </strong>Vertex AI Agent Engine does not natively support the complexity of the 3-Legged OAuth dance for EUC, which would otherwise force agent developers to write custom code. Gemini Enterprise eliminates this developer burden by providing built-in 3-Legged OAuth connectors, managing the entire authorization lifecycle and securely passing the user’s access token to your ADK agent.</li></ul><p>Gemini Enterprise represents a central hub of Agents for users in organizations. where custom agents built by your organization and hosted on Vertex AI Agent Engine can be registered. By using this pattern, you gain a highly secure and scalable way to deliver natural language data analytics, ensuring that your agent respects every user’s existing data permissions.</p><h3>Step-by-Step Guide</h3><h4>1. Initialize Gemini Enterprise</h4><p>Before deploying your agent, you must enable Gemini Enterprise in your Google Cloud project. Follow the <a href="https://docs.cloud.google.com/gemini/enterprise/docs/quickstart-gemini-enterprise#before-you-begin">official quickstart guide</a> to ensure all prerequisites are met. Once enabled, proceed to <a href="https://docs.cloud.google.com/gemini/enterprise/docs/quickstart-gemini-enterprise#create-app">create a Gemini Enterprise API application</a>.</p><h4>2. Configure OAuth Credentials</h4><p>To allow Gemini Enterprise to act on behalf of the user, you need to set up an OAuth 2.0 client. Follow <a href="https://docs.cloud.google.com/gemini/enterprise/docs/register-and-manage-an-adk-agent#obtain_authorization_details">this guide</a> to obtain a Client ID and Client Secret for a “Web” application type. Make sure to record the Authorization URI, Token URI, Client ID, and Client Secret.</p><h4>3. Setup Environment Variables</h4><p>Open your terminal or <a href="https://shell.cloud.google.com/">Cloud Shell</a> and set your project details and credentials. Choose a <a href="https://docs.cloud.google.com/vertex-ai/docs/general/locations#available-regions">location</a> supported by Vertex AI. Prepare your local environment and authenticate the gcloud CLI:</p><pre>export GOOGLE_CLOUD_PROJECT={your-project}<br>export GOOGLE_CLOUD_LOCATION={your-location}<br>export OAUTH_CLIENT_ID={your-client-id}<br>export OAUTH_CLIENT_SECRET={your-client-secret}<br>export OAUTH_TOKEN_URI={your-token-uri}<br>export OAUTH_AUTH_URI={your-auth-uri}<br>export AUTH_ID={your-gemini-enterprise-auth-id} # e.g. ge-bq-agent-auth-id</pre><pre>gcloud auth login<br>gcloud auth application-default login<br>gcloud config set project $GOOGLE_CLOUD_PROJECT</pre><h4>4. Register Authorization Resource</h4><p>Now, register an authorization resource in Gemini Enterprise. This resource acts as the bridge for passing access tokens from Gemini Enterprise to the ADK agent after user consent. Refer to <a href="https://docs.cloud.google.com/gemini/enterprise/docs/register-and-manage-an-adk-agent#add-authorization-resource">this documentation</a> for details.</p><pre>curl -X POST \<br>  -H &quot;Authorization: Bearer $(gcloud auth print-access-token)&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;X-Goog-User-Project: $GOOGLE_CLOUD_PROJECT&quot; \<br>  &quot;https://global-discoveryengine.googleapis.com/v1alpha/projects/$GOOGLE_CLOUD_PROJECT/locations/global/authorizations?authorizationId=$AUTH_ID&quot; \<br>  -d @- &lt;&lt;EOF<br>{<br>  &quot;name&quot;: &quot;projects/$GOOGLE_CLOUD_PROJECT/locations/global/authorizations/$AUTH_ID&quot;,<br>  &quot;serverSideOauth2&quot;: {<br>    &quot;clientId&quot;: &quot;$OAUTH_CLIENT_ID&quot;,<br>    &quot;clientSecret&quot;: &quot;$OAUTH_CLIENT_SECRET&quot;,<br>    &quot;authorizationUri&quot;: &quot;$OAUTH_AUTH_URI?client_id=$OAUTH_CLIENT_ID&amp;redirect_uri=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fstatic%2Foauth%2Foauth.html&amp;scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform&amp;include_granted_scopes=true&amp;response_type=code&amp;access_type=offline&amp;prompt=consent&quot;,<br>    &quot;tokenUri&quot;: &quot;$OAUTH_TOKEN_URI&quot;<br>  }<br>}<br>EOF</pre><p>Capture the authorization resource path from the response (of the form <em>projects/{project-number}/locations/global/authorizations/{AUTH_ID}</em>) and save it:</p><pre>export GE_AUTH_RESOURCE={your-ge-auth-resource}</pre><h4>5. Prepare the BigQuery Agent</h4><p>Clone the ADK repository and navigate to the BigQuery sample agent. We will then install dependencies and configure the environment files.</p><pre>git clone - filter=blob:none - sparse https://github.com/google/adk-python.git<br>cd adk-python<br>git sparse-checkout set contributing/samples/bigquery</pre><pre>cd contributing/samples<br>python -m venv venv<br>source venv/bin/activate<br>pip install google-adk&gt;=1.25.0</pre><p>Create the <em>.env</em> file and update the agent code to use the actual <em>AUTH_ID</em> we created above.</p><pre># Set the environment for the ADK agent<br>cat &lt;&lt; EOF &gt; bigquery/.env<br>GOOGLE_GENAI_USE_VERTEXAI=TRUE<br>GOOGLE_CLOUD_PROJECT=$GOOGLE_CLOUD_PROJECT<br>GOOGLE_CLOUD_LOCATION=$GOOGLE_CLOUD_LOCATION<br>EOF</pre><pre># Replace the AUTH_ID placeholder in agent.py<br>sed -e &quot;s:AUTH_ID:$AUTH_ID:&quot; bigquery/agent.py -i</pre><p>In <em>agent.py</em>, ensure you have set the following credential type to trigger the BigQuery tools instantiation with externally passed access tokens (in this case from Gemini Enterprise) as documented in the <a href="https://github.com/google/adk-python/tree/main/contributing/samples/bigquery#with-agent-engine-and-gemini-enterprise">sample agent instructions</a>:</p><pre>CREDENTIALS_TYPE = AuthCredentialTypes.HTTP</pre><h4>6. Deploy to Vertex AI Agent Engine</h4><p>Ensure the <a href="https://docs.cloud.google.com/sdk/docs/install-sdk">Google Cloud CLI</a> is initialized. Authenticate and deploy the agent using the ADK CLI following <a href="https://google.github.io/adk-docs/deploy/agent-engine/deploy/#deploy-agent">these instructions</a>.</p><pre>adk deploy agent_engine \<br>  --display_name=&quot;My BigQuery Agent for Gemini Enterprise&quot; \<br>  bigquery</pre><p>Upon successful deployment, note the reasoning engine path (of the form <em>projects/{project-number}/locations/{location}/reasoningEngines/{id}</em>). You can also find this in the <a href="https://console.cloud.google.com/vertex-ai/agents/agent-engines">Agent Engine Console</a> under “Resource name”.</p><pre>export REASONING_ENGINE_PATH={your-reasoning-engine-path}</pre><h4>7. Register Agent in Gemini Enterprise</h4><p>Retrieve your Gemini Enterprise app ID from the <a href="https://console.cloud.google.com/gemini-enterprise/apps">Gemini Enterprise Console</a> and use it to register your deployed reasoning engine. Let’s follow <a href="https://docs.cloud.google.com/gemini/enterprise/docs/register-and-manage-an-adk-agent#register_adk_agent-drest">this guide</a> to do the registration. If you’d rather prefer to do the same using Cloud Console UI, follow <a href="https://docs.cloud.google.com/gemini/enterprise/docs/register-and-manage-an-adk-agent#register_adk_agent-console">this guide</a> instead.</p><pre>export GE_APP_ID={your-ge-app-id}</pre><pre>curl -X POST \<br>  -H &quot;Authorization: Bearer $(gcloud auth print-access-token)&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;X-Goog-User-Project: $GOOGLE_CLOUD_PROJECT&quot; \<br>  &quot;https://global-discoveryengine.googleapis.com/v1alpha/projects/$GOOGLE_CLOUD_PROJECT/locations/global/collections/default_collection/engines/$GE_APP_ID/assistants/default_assistant/agents&quot; \<br>  -d @- &lt;&lt;EOF<br>{<br>  &quot;displayName&quot;: &quot;My BigQuery agent (Agent Engine/ADK)&quot;,<br>  &quot;description&quot;: &quot;My BigQuery agent (Agent Engine/ADK)&quot;,<br>  &quot;adk_agent_definition&quot;: {<br>    &quot;provisioned_reasoning_engine&quot;: {<br>      &quot;reasoning_engine&quot;: &quot;$REASONING_ENGINE_PATH&quot;<br>    }<br>  },<br>  &quot;authorization_config&quot;: {<br>    &quot;tool_authorizations&quot;: [<br>      &quot;$GE_AUTH_RESOURCE&quot;<br>    ]<br>  }<br>}<br>EOF</pre><h3>Conclusion and Testing</h3><p>Your agent is now live! Navigate to your Gemini Enterprise app in the <a href="https://console.cloud.google.com/gemini-enterprise/apps">Cloud Console</a>, select “Agents”, and click “Preview”. You will find “My BigQuery agent (Agent Engine/ADK)” ready for interaction.</p><p>On your first interaction, you will be prompted for authorization via the resource you created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ry1IEUDe6GGcxMstbIaaEg.png" /></figure><p>Once granted, Gemini Enterprise will seamlessly pass valid access tokens to your ADK agent in the conversations hereon, enabling secure natural language analytics powered by your own credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgmDnNHCeSZV8qin3Wr9Gw.gif" /></figure><p>There you have it. Enjoy your BigQuery data analysis journey in Gemini Enterprise using your own access privileges!</p><h3>Related</h3><p><a href="https://medium.com/google-cloud/jumpstart-production-grade-bigquery-agent-with-agent-starter-pack-503a34fd921c">Jumpstart production grade BigQuery Agent with Agent starter pack | by Shobhit Singh | Google Cloud — Community | Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=079b1dc24406" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/enable-bigquery-agents-in-gemini-enterprise-via-end-user-credentials-079b1dc24406">Enable BigQuery Agents in Gemini Enterprise via End User Credentials</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[Jumpstart production grade BigQuery Agent with Agent starter pack]]></title>
            <link>https://medium.com/google-cloud/jumpstart-production-grade-bigquery-agent-with-agent-starter-pack-503a34fd921c?source=rss-8e877be7bd56------2</link>
            <guid isPermaLink="false">https://medium.com/p/503a34fd921c</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Shobhit Singh]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 02:44:15 GMT</pubDate>
            <atom:updated>2026-01-14T12:24:33.343Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building Data Analytics Agent made easy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFHXDmyinl0SF9ZN_bO36A.png" /></figure><blockquote>BigQuery has built open source Agentic AI Tools for powering Data Analytics AI agents. Google’s Agent Starter Pack simplifies creating a production-ready agent and deploying it to production. They can be combined to quickly turn up a data analytics agent in production.</blockquote><h3>Introduction</h3><p>This post walks through how to quickly set up, build, locally test and deploy a data analytics agent to Vertex AI <a href="https://docs.cloud.google.com/agent-builder/agent-engine/overview">Agent Engine</a> (AE). This AI agent can interact with BigQuery (BQ) in natural language, utilizing the <a href="https://googlecloudplatform.github.io/agent-starter-pack/guide/why_starter_pack.html">Agent Starter Pack</a> (ASP) and the <a href="https://google.github.io/adk-docs/">Agent Development Kit</a> (ADK).</p><blockquote><strong>ADK</strong>: A model-agnostic, deployment-agnostic framework for developing and deploying AI agents.</blockquote><blockquote><strong>ASP</strong>: Simplifies the journey from prototype to a robust, reliable, production-ready agent.</blockquote><blockquote><strong>AE</strong>: a set of services that enables developers to deploy, manage, and scale AI agents in production.</blockquote><p>In this exercise we leverage a pre-existing BigQuery agent sample from the ADK repo to create an agent project. We would test this agent locally and then deploy to the cloud. The final result is a BigQuery Data Analytics agent ready for use.</p><h3>Prerequisites</h3><p>To follow this guide, you will need:</p><ol><li>A Linux machine/cloud shell</li><li>APIs enabled in your Google Cloud Project (GCP)<br>– BigQuery — for BigQuery analytics<br>– Vertex AI — for deploying agent to Agent Engine<br>– Cloud Storage — for staging the agent for deploying to Agent Engine</li><li>Gemini API Key</li></ol><h3>Step-by-Step Guide</h3><p>Follow these steps to set up and run your BigQuery Agent locally.</p><h4>Get Agent Starter Pack</h4><p>Set up your machine with agent-starter-pack <a href="https://googlecloudplatform.github.io/agent-starter-pack/guide/installation">https://googlecloudplatform.github.io/agent-starter-pack/guide/installation</a>. I chose to get a zero setup <a href="https://shell.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Feliasecchig%2Fasp-open-in-cloud-shell&amp;cloudshell_print=open-in-cs">Cloud Shell</a> to save on steps.</p><h4>Create the Agent project from the sample agent</h4><p>Use the agent-starter-pack create command to generate a new agent project based on the ADK’s <a href="https://github.com/google/adk-python/tree/main/contributing/samples/bigquery">BigQuery sample agent</a>.</p><pre>uvx agent-starter-pack create my-bq-agent -a https://github.com/google/adk-python/tree/main/contributing/samples/bigquery</pre><p>I picked all default options on the prompts, which means Vertex AI Agent Engine as the production environment for the deployed agent.</p><pre>=== Google Cloud Agent Starter Pack 🚀===<br>Welcome to the Agent Starter Pack!<br>This tool will help you create an end-to-end production-ready AI agent in Google Cloud!<br><br>Fetching remote template: https://github.com/google/adk-python/tree/main/contributing/samples/bigquery<br><br>&gt; Please select a deployment target:<br>1. Vertex AI Agent Engine - Vertex AI Managed platform for scalable agent deployments<br>2. Cloud Run - GCP Serverless container execution<br><br>Enter the number of your deployment target choice (1): <br><br>&gt; Please select a CI/CD runner:<br>1. Simple - Minimal - no CI/CD or Terraform, add later with &#39;enhance&#39;<br>2. Google Cloud Build - Fully managed CI/CD, deeply integrated with GCP for fast, consistent builds and deployments.<br>3. GitHub Actions - GitHub Actions: CI/CD with secure workload identity federation directly in GitHub.<br><br>Enter the number of your CI/CD runner choice (1): <br><br>Enter desired GCP region (Gemini uses global endpoint by default) (us-central1): <br>&gt; Verifying GCP credentials...<br><br>&gt; You are logged in with account: &#39;default&#39;<br>&gt; You are using project: &#39;Unknown&#39;<br>&gt; Do you want to continue? (The CLI will check if Vertex AI is enabled in this project) [Y/skip/edit] (Y): <br>&gt; Testing Vertex AI connection...<br>&gt; ⚠️  Unexpected response from metadata server: service account info is missing &#39;email&#39; field.<br>&gt; Continuing with template processing...<br>ℹ️  Adding &#39;app&#39; object to bigquery/agent.py for backward compatibility<br><br>&gt; Success! Your agent project is ready.<br><br>📖 Project README: cat my-bq-agent/README.md<br>   Online Development Guide: https://goo.gle/asp-dev<br><br>💡 Once ready for production, run: uvx agent-starter-pack enhance<br><br>🚀 To get started, run the following command:<br>   cd my-bq-agent &amp;&amp; make install &amp;&amp; make playground</pre><h4>Set the environment</h4><p>Create a <em>.env</em> file to configure the ADK agent to use the Gemini API for LLM integration and set the Gemini API Key (replace <em>YOUR_GEMINI_API_KEY</em> with your own key).</p><pre>cat &lt;&lt; EOF &gt; my-bq-agent/.env<br>GOOGLE_GENAI_USE_VERTEXAI=FALSE<br>GOOGLE_API_KEY=YOUR_GEMINI_API_KEY<br>EOF</pre><p>Also, for the BigQuery Agent to work in ADC mode:</p><pre>gcloud auth application-default login</pre><h4>Install Dependencies and Launch the Local Playground</h4><p>Now execute the command suggested by agent-starter-pack in the agent project creation step to install dependencies and start the local ADK web server.</p><pre>cd my-bq-agent &amp;&amp; make install &amp;&amp; make playground</pre><pre>...<br>INFO:     Started server process [5537]<br>INFO:     Waiting for application startup.<br><br>+-----------------------------------------------------------------------------+<br>| ADK Web Server started                                                      |<br>|                                                                             |<br>| For local testing, access at http://127.0.0.1:8501.                         |<br>+-----------------------------------------------------------------------------+<br><br>INFO:     Application startup complete.<br>INFO:     Uvicorn running on http://127.0.0.1:8501 (Press CTRL+C to quit)</pre><h4>Test the Agent</h4><ol><li>Click on the link provided by the server output (e.g., <a href="http://127.0.0.1:8501).">http://127.0.0.1:8501).</a> If you are using Cloud Shell, this will open a new tab targeting your application (Example: <a href="https://8501-cs-redacted-default.cs-us-west1-vwey.cloudshell.dev/dev-ui/).">https://8501-cs-REDACTED-default.cs-us-west1-vwey.cloudshell.dev/dev-ui/).</a></li><li>In the top left, select “bigquery” from the “Select an agent” dropdown menu.</li><li>Start conversing with the agent. The agent will now interact with BigQuery using your credentials stored on the Cloud Shell VM.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*WiJl3lZAdde_KIKhduW-XA.png" /></figure><h4>Deploy the Agent</h4><p>Now that you are satisfied with the functioning of your agent, follow <a href="https://googlecloudplatform.github.io/agent-starter-pack/guide/deployment.html">https://googlecloudplatform.github.io/agent-starter-pack/guide/deployment.html</a> for deploying it to the Agent Engine.</p><blockquote><strong>Note:</strong> In this exercise, the cloud shell environment is very close to the prospective Agent Engine (both within Google Cloud), so we expect the user interactions with the deployed agent to be similar to what we tested locally.</blockquote><p>For a quick deployment, first set the target GCP project in your local environment (replace <em>YOUR_GCP_PROJECT_ID</em> with your GCP project id):</p><pre>gcloud config set project YOUR_GCP_PROJECT_ID</pre><p>Next, deploy the agent:</p><pre>make deploy</pre><p>This could take a few minutes, doing the work behind the scenes.</p><pre>    ╔═══════════════════════════════════════════════════════════╗<br>    ║                                                           ║<br>    ║   🤖 DEPLOYING AGENT TO VERTEX AI AGENT ENGINE 🤖         ║<br>    ║                                                           ║<br>    ╚═══════════════════════════════════════════════════════════╝<br><br>📋 Deployment Parameters:<br>  Project: YOUR_GCP_PROJECT_ID<br>  Location: us-central1<br>  Display Name: my-bq-agent<br>  Min Instances: 1<br>  Max Instances: 10<br>  CPU: 4<br>  Memory: 8Gi<br>  Container Concurrency: 9<br><br>🌍 Environment Variables:<br>  GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY: true<br>  GOOGLE_CLOUD_REGION: us-central1<br>  NUM_WORKERS: 1<br>  OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT: true<br>INFO:root:Importing app.agent_engine_app.agent_engine<br><br>🚀 Creating new agent: my-bq-agent<br>🚀 Deploying to Vertex AI Agent Engine (this can take 3-5 minutes)...<br>INFO:vertexai_genai.agentengines:Creating in-memory tarfile of source_packages<br>INFO:vertexai_genai.agentengines:Using agent framework: google-adk<br>INFO:vertexai_genai.agentengines:View progress and logs at https://console.cloud.google.com/logs/query?project=YOUR_GCP_PROJECT_ID&amp;query=resource.type%3D%22aiplatform.googleapis.com%2FReasoningEngine%22%0Aresource.labels.reasoning_engine_id%3D%223641781522798739456%22.<br>INFO:vertexai_genai.agentengines:Agent Engine created. To use it in another session:<br>INFO:vertexai_genai.agentengines:agent_engine=client.agent_engines.get(name=&#39;projects/476297540060/locations/us-central1/reasoningEngines/3641781522798739456&#39;)<br>INFO:root:Agent Engine ID written to deployment_metadata.json<br><br>✅ Deployment successful!<br>Service Account: service-YOUR_GCP_PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com<br><br>📊 Open Console Playground: https://console.cloud.google.com/vertex-ai/agents/locations/us-central1/agent-engines/3641781522798739456/playground?project=YOUR_GCP_PROJECT_ID</pre><p>In the end it gave you a link to the Vertex AI Agent Engine playground page, where you can start interacting right away.</p><blockquote><strong>Pro-Tip:</strong> It also printed the service account that is the identity of this agent, on which you may need to provision any additional IAM roles to support your interaction, such as “BigQuery Job User” for running queries in your choice of project, and “BigQuery Data Viewer” for accessing the data in the project.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*oM9rs9yx-lZvpFCCacshcQ.png" /></figure><p>There you have it, a Data Analytics agent deployed to Vertex AI Agent Engine in Google Cloud.</p><h4>Observe the Agent</h4><p>Refer to <a href="https://googlecloudplatform.github.io/agent-starter-pack/guide/observability.html">https://googlecloudplatform.github.io/agent-starter-pack/guide/observability.html</a> for utilizing the full suit of observability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qt1rpcY4NCePmNGv3xgINA.png" /></figure><p>You could also complement the operational observability with the analytical intelligence by leveraging <a href="https://google.github.io/adk-docs/observability/bigquery-agent-analytics/">ADK Agent Analytics plugin</a>, with just one line change to your agent code (in <em>my-bq-agent/bigquery/agent.py</em>), and having the agentic events flow directly to a Google BigQuery table for in-depth agent behavior analysis.</p><h3>Conclusion and Feedback</h3><p>The BigQuery Agentic Tools Team and the Agent Starter Pack Team would love to hear from you. You could create a discussion/issue on the respective github repositories <a href="https://github.com/google/adk-python">https://github.com/google/adk-python</a> and <a href="https://github.com/GoogleCloudPlatform/agent-starter-pack">https://github.com/GoogleCloudPlatform/agent-starter-pack</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=503a34fd921c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/jumpstart-production-grade-bigquery-agent-with-agent-starter-pack-503a34fd921c">Jumpstart production grade BigQuery Agent with Agent starter pack</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[Build a Linear Regression model on large data in Python using BigQuery DataFrames]]></title>
            <link>https://medium.com/google-cloud/build-a-linear-regression-model-on-large-data-in-python-using-bigquery-dataframes-3d80a0ccf199?source=rss-8e877be7bd56------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d80a0ccf199</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bigframes]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Shobhit Singh]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 00:32:52 GMT</pubDate>
            <atom:updated>2025-04-21T19:08:49.881Z</atom:updated>
            <content:encoded><![CDATA[<h4>Scaling Linear Regression with BigFrames ML</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ws4UH61URFF0cn4cTgbIMg.png" /></figure><blockquote>BigQuery DataFrames aka BigFrames is an open source Python library offered by Google. BigFrames scales Python data processing by transpiling common Python data science and machine learning APIs to BigQuery SQL. You can read more about BigFrames in the <a href="https://cloud.google.com/bigquery/docs/bigquery-dataframes-introduction">official introduction to BigFrames</a> and can refer to the <a href="https://github.com/googleapis/python-bigquery-dataframes">public git repository for BigFrames</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*xOpb3sXaaGgjbXO1PBCOww.png" /></figure><h3>Introduction</h3><p>In today’s data-driven world, the ability to train and deploy machine learning models on massive datasets is crucial. Linear regression, a fundamental and widely used algorithm, is no exception. However, traditional machine learning libraries often struggle when faced with datasets that exceed available memory or require extensive computational resources. This is where BigQuery DataFrames (BigFrames) shines, providing a seamless way to perform scalable linear regression directly on BigQuery.</p><h3>The Importance of Large-Scale Linear Regression</h3><p>Many industries rely on linear regression for tasks like:</p><ul><li><strong>Predicting sales:</strong> Retailers use it to forecast future sales based on historical data.</li><li><strong>Financial modeling:</strong> Financial institutions predict stock prices or assess credit risk.</li><li><strong>Demand forecasting:</strong> Supply chain managers predict product demand to optimize inventory.</li><li><strong>Real estate:</strong> Predicting home values based on multiple features.</li></ul><p>These use cases often involve massive datasets, making traditional in-memory processing impractical. BigFrames overcomes this limitation by leveraging the power of BigQuery.</p><h3>BigFrames ML Linear Regression: A Practical Example</h3><p>Let’s illustrate how to use BigFrames ML LinearRegression with a practical example. We’ll use the <a href="https://console.cloud.google.com/marketplace/product/epa/historical-air-quality">epa_historical_air_quality</a> dataset from the <a href="https://cloud.google.com/bigquery/public-data">BigQuery Public Data</a>. This data is courtesy the United States Environmental Protection Agency (EPA) which protects both public health and the environment by establishing the standards for national air quality. The EPA provides annual summary data as well as hourly and daily data about several measurements of the atmosphere in the categories of criteria gases, particulates, meteorological, and toxics. We will be particularly making use of the hourly data, which consists of:</p><blockquote>more than 450 GB of data spread over several tables across more than 2 billion rows.</blockquote><p>Let’s define our problem statement as: <strong>Train a linear regression model to predict the level of ozone in the atmosphere given the measurements of other constituents and properties of the atmosphere.</strong></p><p>In the real world, the need to predict ozone levels could be an outcome of missing measurements due to several situations, such as</p><ul><li>The ozone measuring device not working</li><li>Data corruption post measurement</li></ul><p>Missing data can cause issues in several data analysis and reporting tools and processes, and in this scenario let’s say EPA wants to fix this by predicting the most reasonable ozone level given the measurements of other atmospheric constituents and properties. Their data scientists just learnt about BigQuery DataFrames and its simplicity, scalability and performance. Here is how they go about building a linear regression model to fill in, or predict the missing ozone levels.</p><h3>Set up</h3><p>Let’s first make sure the BigQuery DataFrames (<a href="https://pypi.org/project/bigframes/">BigFrames</a>) package is installed. It can be installed using the shell command:</p><pre>pip install bigframes</pre><p>Then in our python environment we import the <em>bigframes.pandas</em> module and initialize the Google Cloud project and BigQuery location:</p><pre>import bigframes.pandas as bpd<br><br># NOTE: The project option is not required in all environments.<br># On BigQuery Studio, the project ID is automatically detected.<br>bpd.options.bigquery.project = PROJECT_ID<br><br># NOTE: The location option is not required.<br># It defaults to the location of the first table or query<br># passed to read_gbq(). For APIs where a location can&#39;t be<br># auto-detected, the location defaults to the &quot;US&quot; location.<br>bpd.options.bigquery.location = LOCATION<br><br># NOTE: For a machine learning model the order of the data is<br># not important. So let&#39;s relax the ordering_mode to accept<br># partial ordering. This allows BigQuery DataFrames to run cost<br># and performance optimized jobs at the BigQuery engine.<br>bpd.options.bigquery.ordering_mode = &quot;partial&quot;</pre><p>Note the partial ordering mode, which offers performance and cost optimized execution when strict ordering of the DataFrame is not important. Learn about all the configuration options provided by BigQuery DataFrames <a href="https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes._config.Options">here</a>.</p><h3>Define the data</h3><p>We will combine measurements of various parameters of the atmosphere from multiple tables with hourly data to represent a consolidated DataFrame to use for our model training and prediction.</p><pre>dataset = &quot;bigquery-public-data.epa_historical_air_quality&quot;<br>hourly_summary_tables = [<br>    &quot;co_hourly_summary&quot;,<br>    &quot;hap_hourly_summary&quot;,<br>    &quot;no2_hourly_summary&quot;,<br>    &quot;nonoxnoy_hourly_summary&quot;,<br>    &quot;o3_hourly_summary&quot;,<br>    &quot;pm10_hourly_summary&quot;,<br>    &quot;pm25_frm_hourly_summary&quot;,<br>    &quot;pm25_nonfrm_hourly_summary&quot;,<br>    &quot;pm25_speciation_hourly_summary&quot;,<br>    &quot;pressure_hourly_summary&quot;,<br>    &quot;rh_and_dp_hourly_summary&quot;,<br>    &quot;so2_hourly_summary&quot;,<br>    &quot;temperature_hourly_summary&quot;,<br>    &quot;voc_hourly_summary&quot;,<br>    &quot;wind_hourly_summary&quot;,<br>]</pre><p>In the hourly data tables let’s define the columns which represent the identity of the measurement samples — state, county, site, date and time. Let’s also define the column that contains the parameter for which the measurement was collected, and also the column that contains the measurement value itself.</p><pre>index_columns = [&quot;state_name&quot;, &quot;county_name&quot;, &quot;site_num&quot;, &quot;date_local&quot;, &quot;time_local&quot;]<br>param_column = &quot;parameter_name&quot;<br>value_column = &quot;sample_measurement&quot;</pre><h3>Analyze the tables</h3><p>Before using the data from the BigQuery dataset, let’s analyze the tables of interest about how much data they contain and across how many parameters:</p><pre>for table in hourly_summary_tables:<br>    # get the bigframes global session<br>    bigframes_session = bpd.get_global_session()<br><br>    # get the bigquery table info<br>    table_info = bigframes_session.bqclient.get_table(f&quot;{dataset}.{table}&quot;)<br><br>    # read the table as a dataframe<br>    df = bpd.read_gbq(f&quot;{dataset}.{table}&quot;)<br><br>    # print metadata about the table<br>    print(<br>        f&quot;{table}: &quot;<br>        f&quot;{round(table_info.num_bytes/1_000_000_000, 1)} GB, &quot;<br>        f&quot;{round(table_info.num_rows/1_000_000, 1)} million rows, &quot;<br>        f&quot;{df[param_column].nunique()} params&quot;<br>    )</pre><pre>co_hourly_summary: 22.5 GB, 105.3 million rows, 1 params<br>hap_hourly_summary: 1.2 GB, 5.1 million rows, 17 params<br>no2_hourly_summary: 22.8 GB, 105.5 million rows, 1 params<br>nonoxnoy_hourly_summary: 78.1 GB, 358.4 million rows, 3 params<br>o3_hourly_summary: 117.2 GB, 609.9 million rows, 1 params<br>pm10_hourly_summary: 13.0 GB, 54.4 million rows, 1 params<br>pm25_frm_hourly_summary: 12.2 GB, 47.9 million rows, 1 params<br>pm25_nonfrm_hourly_summary: 15.5 GB, 58.5 million rows, 1 params<br>pm25_speciation_hourly_summary: 1.6 GB, 6.5 million rows, 9 params<br>pressure_hourly_summary: 11.0 GB, 54.8 million rows, 1 params<br>rh_and_dp_hourly_summary: 18.5 GB, 82.6 million rows, 2 params<br>so2_hourly_summary: 30.5 GB, 146.8 million rows, 1 params<br>temperature_hourly_summary: 38.6 GB, 175.2 million rows, 1 params<br>voc_hourly_summary: 39.1 GB, 163.2 million rows, 92 params<br>wind_hourly_summary: 54.8 GB, 260.1 million rows, 2 params</pre><p>In addition to Ozone (<em>o3_hourly_summary</em>) — the target for our regression model, we find the following data interesting for predicting the ozone levels because they have significant amount of data available and we believe they can be correlated with the ozone levels:</p><ul><li>Carbon monoxide (<em>co_hourly_summary</em>)</li><li>Nitrogen dioxide (<em>no2_hourly_summary</em>)</li><li>Sulphur dioxide (<em>so2_hourly_summary</em>)</li><li>Nitric Oxide, Oxides of nitrogen and Reactive oxides of nitrogen (<em>nonoxnoy_hourly_summary</em>)</li><li>Pressure (<em>pressure_hourly_summary</em>)</li><li>Temperature (temperature_hourly_summary)</li><li>Wind speed and direction (wind_hourly_summary)</li></ul><p>We exclude the data for hazardous air pollutants (in <em>hap_hourly_summary</em> table) and volatile organic compounds (in <em>voc_hourly_summary</em> table) because it is relatively sparse per parameter. We also leave the particulate matter (<em>pm*_hourly_summary</em> tables) and relative humidity and dew point (<em>rh_and_dp_hourly_summary</em> table) data as we don’t find them interesting enough. We leave them for you to try them in a separate modeling exercise.</p><h3>Read tables as DataFrame</h3><p>Since we will be combining data from multiple tables, let’s instantiate a list of dataframes for various metrics which then would be combined to create the final dataframe.</p><pre>params_dfs = []</pre><p>Let’s first read the tables which each carry data for a single parameter.</p><pre>table_param_dict = {<br>    &quot;co_hourly_summary&quot; : &quot;co&quot;,<br>    &quot;no2_hourly_summary&quot; : &quot;no2&quot;,<br>    &quot;o3_hourly_summary&quot; : &quot;o3&quot;,<br>    &quot;pressure_hourly_summary&quot; : &quot;pressure&quot;,<br>    &quot;so2_hourly_summary&quot; : &quot;so2&quot;,<br>    &quot;temperature_hourly_summary&quot; : &quot;temperature&quot;,<br>}<br><br>for table, param in table_param_dict.items():<br>    param_df = bpd.read_gbq(<br>        f&quot;{dataset}.{table}&quot;,<br>        columns=index_columns + [value_column]<br>    )<br>    param_df = param_df\<br>        .sort_values(index_columns)\<br>        .drop_duplicates(index_columns)\<br>        .set_index(index_columns)\<br>        .rename(columns={value_column : param})<br>    params_dfs.append(param_df)</pre><p>The <em>nonoxnoy</em> table captures measurements for 3 parameters. Let’s analyze how many instances of each parameter it contains.</p><pre>nonoxnoy_table = f&quot;{dataset}.nonoxnoy_hourly_summary&quot;<br>bpd.read_gbq(nonoxnoy_table, columns=[param_column]).value_counts()</pre><pre>parameter_name<br>Nitric oxide (NO)                    183220785<br>Oxides of nitrogen (NOx)             155766556<br>Reactive oxides of nitrogen (NOy)     19404954<br>Name: count, dtype: Int64</pre><p>We see that the NOy data is significantly sparse as compared to NO and NOx, so we skip that and include NO and NOx data.</p><pre>no_df = bpd.read_gbq(<br>    nonoxnoy_table,<br>    columns=index_columns + [value_column],<br>    filters=[(param_column, &quot;==&quot;, &quot;Nitric oxide (NO)&quot;)]<br>)<br>no_df = no_df\<br>    .sort_values(index_columns)\<br>    .drop_duplicates(index_columns)\<br>    .set_index(index_columns)\<br>    .rename(columns={value_column: &quot;no_&quot;})<br>params_dfs.append(no_df)<br><br>nox_df = bpd.read_gbq(<br>    nonoxnoy_table,<br>    columns=index_columns + [value_column],<br>    filters=[(param_column, &quot;==&quot;, &quot;Oxides of nitrogen (NOx)&quot;)]<br>)<br>nox_df = nox_df\<br>    .sort_values(index_columns)\<br>    .drop_duplicates(index_columns)\<br>    .set_index(index_columns)\<br>    .rename(columns={value_column: &quot;nox&quot;})<br>params_dfs.append(nox_df)</pre><p>The wind table captures measurements for 2 parameters. Let’s analyze how many instances of each parameter it contains.</p><pre>wind_table = f&quot;{dataset}.wind_hourly_summary&quot;<br>bpd.read_gbq(wind_table, columns=[param_column]).value_counts()</pre><pre>parameter_name<br>Wind Direction - Resultant    130774795<br>Wind Speed - Resultant        129354971<br>Name: count, dtype: Int64</pre><p>Let’s include the data for wind speed and wind direction.</p><pre>wind_speed_df = bpd.read_gbq(<br>    wind_table,<br>    columns=index_columns + [value_column],<br>    filters=[(param_column, &quot;==&quot;, &quot;Wind Speed - Resultant&quot;)]<br>)<br>wind_speed_df = wind_speed_df\<br>    .sort_values(index_columns)\<br>    .drop_duplicates(index_columns)\<br>    .set_index(index_columns)\<br>    .rename(columns={value_column: &quot;wind_speed&quot;})<br>params_dfs.append(wind_speed_df)<br><br>wind_dir_df = bpd.read_gbq(<br>    wind_table,<br>    columns=index_columns + [value_column],<br>    filters=[(param_column, &quot;==&quot;, &quot;Wind Direction - Resultant&quot;)]<br>)<br>wind_dir_df = wind_dir_df\<br>    .sort_values(index_columns)\<br>    .drop_duplicates(index_columns)\<br>    .set_index(index_columns)\<br>    .rename(columns={value_column: &quot;wind_dir&quot;})<br>params_dfs.append(wind_dir_df)</pre><p>Let’s combine data from all parameters into a single DataFrame. The measurements for each parameter may not be available for every (state, county, site, date, time) identifier, we will consider only those identifiers for which measurements of all parameters are available. To achieve this we will combine the measurements via “inner” join. We will also materialize this combined data via <em>cache</em> method for efficient reuse in the subsequent steps.</p><pre>df = bpd.concat(params_dfs, axis=1, join=&quot;inner&quot;).cache()<br>df.shape</pre><pre>(2768736, 10)</pre><p>We have 2.76 million rows of data with 10 parameters. Next we will split this into training data, test data and prediction data and proceed with our modeling exercise. We will be doing some analysis and slicing based on one of the index columns, so let’s temporarily bring the index as regular columns. We will reconstruct the index back at the time of the model training.</p><h3>Prepare data</h3><p>Let’s temporarily bring the index columns as dataframe columns for further processing on the index values for the purpose of data preparation. We will reconstruct the index back at the time of the model training.</p><pre>df = df.reset_index()</pre><p>Let us observe the years from which we have consolidated data so far.</p><pre>df[&quot;date_local&quot;].dt.year.value_counts().sort_index().to_pandas()</pre><pre>date_local<br>1993      4742<br>1994      8222<br>1995     12288<br>1996     19867<br>...<br>2021    117806<br>2022     14570<br>2023      6491<br>2024     37268<br>Name: count, dtype: Int64</pre><p>So we have the data from the years 1993 up to 2024. In this tutorial we would train a model from the past data to predict ozone levels for the future data. Let’s define the cut-off year as 2020. We will pretend that the data before 2020 has known ozone levels, and the 2020 onwards the ozone levels are unknown, which we will predict using our model.</p><p>Let us also further separate the known data into training and test sets. The model would be trained on the training set and then evaluated on the test set to make sure the model generalizes beyond the training data. We could use the <a href="https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.ml.model_selection#bigframes_ml_model_selection_train_test_split">train_test_split</a> method to randomly split the training and test data, but we leave that for you to try out. In this exercise, let’s split based on another cutoff year 2017 — the known data before 2017 would be training data and 2017 onwards would be the test data. This way we stay with the idea that the model is trained on past data and then used to predict the future values.</p><pre>train_data_filter = (df.date_local.dt.year &lt; 2017)<br>test_data_filter = (<br>    (df.date_local.dt.year &gt;= 2017) &amp; (df.date_local.dt.year &lt; 2020)<br>)<br>predict_data_filter = (df.date_local.dt.year &gt;= 2020)<br><br>df_train = df[train_data_filter].set_index(index_columns)<br>df_test = df[test_data_filter].set_index(index_columns)<br>df_predict = df[predict_data_filter].set_index(index_columns)<br><br>df_train.shape, df_test.shape, df_predict.shape</pre><pre>((1906809, 10), (552183, 10), (309744, 10))</pre><p>Thus we have about 1.9 million rows in the training data, about half a million rows for the test data and about 300 thousand rows of the unknown ozone data for which we would be making the predictions. Let’s prepare our feature (or input) columns and the target (or output) column for the purpose of model training and evaluation.</p><pre>X_train = df_train.drop(columns=&quot;o3&quot;)<br>y_train = df_train[&quot;o3&quot;]<br><br>X_test = df_test.drop(columns=&quot;o3&quot;)<br>y_test = df_test[&quot;o3&quot;]</pre><p>Let’s also prepare the unknown data for prediction.</p><pre>X_predict = df_predict.drop(columns=&quot;o3&quot;)</pre><h3>Train the model</h3><p>BigQuery DataFrames ML lets you seamlessly transition from exploring data to creating machine learning models through its scikit-learn-like API <em>bigframes.ml</em>. BigQuery DataFrames ML supports several types of <a href="https://cloud.google.com/python/docs/reference/bigframes/latest#ml-capabilities">ML models</a>. In this exercise, we create a <a href="https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.ml.linear_model.LinearRegression">LineaRegression</a> model, a type of regression model that generates a continuous value from a linear combination of input features.</p><pre>from bigframes.ml.linear_model import LinearRegression<br><br>model = LinearRegression()<br>model.fit(X_train, y_train)</pre><p>Please note that BigQuery DataFrames ML is backed by BigQuery ML, which uses <a href="https://cloud.google.com/bigquery/docs/auto-preprocessing">automatic preprocessing</a> to encode string values and scale numeric values when you pass the feature columns without transforms.</p><p>BigQuery ML also <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-create-glm#data_split_method">automatically splits the data for training and evaluation</a> to attach evaluation metric with the model, although for datasets with less than 500 rows (such as this one), all rows are used for training.</p><p>Let’s check how the model performs on the training data by using the <a href="https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.ml.linear_model.LinearRegression#bigframes_ml_linear_model_LinearRegression_score">score</a> method. More information on BigQuery ML model scoring can be found <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-evaluate#mlevaluate_output">here</a>.</p><pre>model.score(X_train, y_train)</pre><h3>Test the model</h3><p>Let’s also check how the mode performs on the test data to check whether the training generalizes for unseen data.</p><pre>model.score(X_test, y_test)</pre><p>If the generalization looks good, we will go ahead and use the model for prediction. Otherwise, we will iteratively train and test with the various training parameters provided by the <a href="https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.ml.linear_model.LinearRegression">LinearRegression</a> model until we achieve the desired generalization.</p><h3>Predict with the model</h3><p>Let’s use the model to predict the ozone levels. The predicted levels are returned in the column <em>predicted_o3</em>.</p><pre>df_pred = model.predict(X_predict)<br>df_pred.peek()</pre><h3>Save the model</h3><p>When you create a model with BigQuery DataFrames ML, it is saved in an internal location and limited to the BigQuery DataFrames session. However, as you’ll see in the next section, you can use <a href="https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.ml.linear_model.LinearRegression#bigframes_ml_linear_model_LinearRegression_to_gbq">to_gbq</a> to save the model permanently to your BigQuery project.</p><pre>model.to_gbq(DATASET_ID + &quot;.o3_lr_model&quot;)</pre><p>You can view the saved model in the BigQuery console under the dataset you used in the previous step. Run the following cell and follow the link.</p><pre>print(f&#39;https://console.cloud.google.com/bigquery?ws=!1m5!1m4!5m3!1s{PROJECT_ID}!2s{DATASET_ID}!3so3_lr_model&#39;)</pre><p>There you have it, ozone levels in the atmosphere successfully predicted using BigFrames ML via simple Pythonic APIs, smoothly handling a large size data, without transferring any data to the client side! And we also preserved the model for further use.</p><h3>Key Advantages of BigFrames ML LinearRegression</h3><ul><li><strong>Scalability:</strong> BigFrames seamlessly handles large datasets by pushing computation to BigQuery’s distributed infrastructure.</li><li><strong>Efficiency:</strong> By leveraging BigQuery, BigFrames optimizes query execution, resulting in faster training and prediction times.</li><li><strong>Simplified Workflow:</strong> The scikit-learn-like API makes it easy for data scientists to transition to BigQuery without learning new tools.</li></ul><p><strong>Direct BigQuery Integration:</strong> Eliminates the need to move data between systems, reducing complexity and potential bottlenecks.</p><h3>Public Notebook</h3><p>You can find the associated notebook here: <a href="https://github.com/googleapis/python-bigquery-dataframes/blob/main/notebooks/ml/bq_dataframes_ml_linear_regression_big.ipynb">https://github.com/googleapis/python-bigquery-dataframes/blob/main/notebooks/ml/bq_dataframes_ml_linear_regression_big.ipynb</a>.</p><p>For more examples of BigFrames linear regressions, see</p><ul><li><a href="https://cloud.google.com/bigquery/docs/linear-regression-tutorial#bigquery-dataframes">https://cloud.google.com/bigquery/docs/linear-regression-tutorial#bigquery-dataframes</a></li><li><a href="https://cloud.google.com/bigquery/docs/samples/bigquery-dataframes-regression-model">https://cloud.google.com/bigquery/docs/samples/bigquery-dataframes-regression-model</a></li></ul><h3>Conclusion and Feedback</h3><p>The BigFrames team would love to hear from you. If you would like to reach out, please send an email to: bigframes-feedback@google.com or by filing an issue at the<a href="https://github.com/googleapis/python-bigquery-dataframes/issues"> open source BigFrames repository</a>. To receive updates about BigFrames, subscribe to the <a href="https://docs.google.com/forms/d/10EnDyYdYUW9HvelHYuBRC8L3GdGVl3rX0aroinbRZyc/edit?resourcekey=0-QUsnpzF91gm9hsp04rSA6Q">BigFrames email list</a>.</p><p>The BigFrames team would love to hear from you. If you would like to reach out, please send an email to: bigframes-feedback@google.com or by filing an issue at the<a href="https://github.com/googleapis/python-bigquery-dataframes/issues"> open source BigFrames repository</a>. To receive updates about BigFrames, subscribe to the <a href="https://docs.google.com/forms/d/10EnDyYdYUW9HvelHYuBRC8L3GdGVl3rX0aroinbRZyc/edit?resourcekey=0-QUsnpzF91gm9hsp04rSA6Q">BigFrames email list</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d80a0ccf199" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/build-a-linear-regression-model-on-large-data-in-python-using-bigquery-dataframes-3d80a0ccf199">Build a Linear Regression model on large data in Python using BigQuery DataFrames</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>