3313
Of your peers have already watched this video.
21:26 Minutes
The most insightful time you'll spend today!
What are TPUs and Why Should Data Scientists Care?
When it comes to machine learning, more data means better results.
But processing more data also requires more computing power. CPUs are great for sequential arithmetic calculations. They offer low latency with this type of workload. But to speed up machine learning, models have to perform multiple calculations in parallel. And that’s where GPUs perform better.
TensorFlow Processing Units, or TPUs, represent the most advanced hardware accelerators that has been architected ground up for TensorFlow by Google Cloud. Cloud TPUs deliver accelerated performance to help businesses train deep learning models in a matter of hours instead of weeks.
This allows enterprises to be more productive with their scarcest resource, the ML scientist, and drive more innovations, thanks to the advanced computing capability.
Watch John Barrus, Senior Product Manager, Google Cloud; and Zak Stone, Product Manager, Google Brain, show you benefits of using TPUs and how to get started.
AL/ML and Data Products Delivered through Google Cloud Makes them Leader of Gartner 2022 Magic Quadrant

4889
Of your peers have already read this article.
2:00 Minutes
The most insightful time you'll spend today!
Gartner® named Google as a Leader in the 2022 Magic Quadrant™ for Cloud AI Developer Services report. This evaluation covered Google’s language, vision and structured data products including AutoML, all of which we deliver through Google Cloud. We believe this recognition is a reflection of the confidence and satisfaction that customers have in our language, vision, and AutoML products for developers. Google remains a Leader for the third year in a row, based upon the completeness of our vision and our ability to execute.
Developers benefit in many ways by using Cloud AI services and solutions. Customers recognize the advantages of Google’s AI and ML services for developers, such as Vertex AI, BigQuery ML, AutoML and AI APIs. In addition, customers benefit from the pace of progress in the field of Responsible AI and actionable ethics processes applied to all customer and partner solutions leveraging Google Cloud technology, as well as our core architecture including the Vertex AI platform, vision, conversational AI, language and structured data, and optimization services and key vertical industry solutions.
We believe that our ‘Leader’ placement validates this vision for AI developer tools. Let’s take a closer look at some of the report findings.
ML tools purpose-built for developers
Google’s machine learning tools have been built by developers, for developers, based on the groundbreaking research generated from Google Research and DeepMind. This developer empathy drives product development, which supports the developer community to achieve deep value from Google’s AI and ML services. An example of this is the unification of all of the tools needed for building, deploying and managing ML models into one ML platform, Vertex AI, resulting in accelerated time to production. They also cite BigQuery ML, AutoML for language, vision video and tabular data) and prebuilt ML APIs (such as speech and translation) as having high utility for developers at all levels of ML expertise to build custom AI and quickly infuse AI into their applications.
Leading organizations like OTOY, Allen Institute for AI and DeepMind (an Alphabet subsidiary) choose Google for ML, and enterprises like Twitter, Wayfair and The Home Depot shared more about their partnership with Google in their recent sessions at Google Next 2021.
Responsible AI principles and practices
Responsible AI is a critical component of successful AI. A 2020 study commissioned by Google Cloud and the Economic Intelligence Unit highlighted that ethical AI does not only prevent organizations from making egregious mistakes, but that the value of responsible AI practices for competitive edge, as well as talent acquisition and retention are notable. At Google, we not only apply our ethics review process to first party platforms and solutions, to ensure that our services design-in responsible AI from the outset, we also consult with customers and partners based on AI principles to deliver accountability and avoid unfair biases. In addition, our best-in-class tools provide developers with the functionality they need to evaluate fairness and biases in datasets and models. Our Explainable AI tools such as model cards provide model transparency in a structured, accessible way, and the What-If Tool is essential for developers and data scientists to evaluate, debug and improve their ML models.
Clear and understandable product architecture
Google Cloud’s investment in our ML product portfolio has led to a comprehensive, integrated and open offering that spans breadth (across vision, conversational AI, language and structured data, and optimization services) and depth (core AI services, with features such as Vertex AI Pipelines and Vertex Explainable AI built on top). Industry-specific solutions tailored by Google for retail, financial services, manufacturing, media and healthcare customers, such as Recommendations AI, Visual Inspection AI, Media Translation, Healthcare Data Engine, add another layer leveraging this foundational platform to help organizations and users adopt machine learning solutions more easily.
At Google Cloud, we refuse to make developers jump through hoops to derive value out of our technology; instead, we bring the value directly to them by ensuring that all of our AI and ML products and solutions work seamlessly together. To download the full report, click here. Get started on Vertex AI and talk with our sales team.
Disclaimer:
Gartner, Magic Quadrant for Cloud AI Developer Services, Van Baker, Arun Batchu, Erick Brethenoux, Svetlana Sicular, Mike Fang, May 23, 2022.
Gartner and Magic Quadrant are registered trademarks of Gartner, Inc. and/or its affiliates in the U.S. and internationally and is used herein with permission. All rights reserved.
Gartner does not endorse any vendor, product or service depicted in its research publications, and does not advise technology users to select only those vendors with the highest ratings or other designation. Gartner research publications consist of the opinions of Gartner’s research organization and should not be construed as statements of fact. Gartner disclaims all warranties, expressed or implied, with respect to this research, including any warranties of merchantability or fitness for a particular purpose.
WayFair and Google Cloud Get Together to Raise the Bar on World-class Experience!

3021
Of your peers have already read this article.
2:00 Minutes
The most insightful time you'll spend today!
On Dec 9th and 10th, Wayfair and Google Cloud came together for the inaugural Wayfair-Google Cloud Machine Learning Hackathon. Wayfair firmly believes that hackathons are a great way to fuel a culture of collaboration and experimentation. To fuel Wayfair’s incredible pace of innovation at scale, it’s team of more than 3,000 technologists is constantly experimenting and taking smart risks. It’s test-and-learn culture empowers everyone to think critically and creatively, and take big swings to raise the bar on its world-class experience.
The Wayfair-Google Cloud Machine Learning Hackathon was all about getting Wayfairians excited about and enabled on new technology. More specifically, this event was a contained test environment for Wayfair innovators to validate AI and ML tools in order to understand how to get better insight from their data. The projects worked on during this hackathon will help Wayfair build new use cases that could impact the business and the end customer in new and productive ways. Google Cloud’s focus for this Hackathon was to enable Wayfairains to harness the power of Machine Learning and AI to enable their own goals around continual improvement and relentless customer focus.
Prior to the event, Wayfair Data Scientists and Machine Learning Engineers who signed up and submitted ideas for the Hackathon were invited to optional Google Cloud enablement and training sessions. Google Cloud set up classrooms in Qwiklabs on topics including, but not limited to, BigQuery, Vertex AI, and Natural Language AI, so that all Hackathon participants could try out new technologies and tools in a learning environment. Google Cloud subject matter experts were available to field any questions Wayfairians had about the use cases they were hacking on.
The Hackathon was a hybrid virtual & physical event that hosted 67+ innovators, 49 of which registered for Google Cloud supported ideas. 15 judges from both Google Cloud and Wayfair oversaw the event. The esteemed list of judges included Steven Conine, Wayfair’s Co-Founder and Co-Chairman who has helped pave the way for the development of practical applications of next-generation technologies like augmented reality. The judges measured and evaluated the success of a project based on the following criteria:
- “Wow Factor”: How innovative is the project?
- Impact: How impactful is the project to Wayfair?
- Polish: How complete is the project?
- Presentation Quality: How clear and consistent is the demo?
The theme of the Hackathon was Machine Learning and AI. Teams were able to collaborate with participants globally, either in-person or virtually, and work together on projects in five categories: Relentless Customer Focus, Always Improving, Google’s Choice, People’s Choice, and Hackers’ choice.
At the end of the two days there were winners in all 5 categories. The Google’s Choice award went to “Entity Extraction for Order Matching”. Team “Project Clippy” was named both Hackers’ Choice and the winners of the Relentless Customer Focus category. See below for the results of the 5 categories:
- Relentless Customer Focus and Hackers’ Choice
- Winning Team: Project Clippy
- Hackers: Misha Balyasin, Alex Saad, Leo Smerling, and Gabriele Lanaro
- This project provided a gamified experience to make the process of leaving a product review even more seamless.
- Always Improving
- Winning Team: Customer Causal MetaLeaners
- Hackers: Colin Gray, Irene Wang, Huy Vo Tran, Wenhao Xu, and Santiago Velez Ferro
- Team Customer Causal MetaLeaners worked to build lightweight procedure(s) for computationally distributed, multi-target, customized loss functions to make causal meta-learners more applicable to real-world Wayfair problems.
- Google’s Choice Award:
- Winning Team: Entity Extraction for Order Matching
- Hackers: Roger Bock, Bradley West, Sina Moeini, and Jonathan de Melker Worms
- This team built out a solution to use text models to extract and identify the products that customers purchased from user reviews.
- People’s Choice:
- Winning Team: KNN and ANN on Vertex AI
- Hackers: Santosh Jhingade, Ashrith Marpaka, Nikhil Bhaip, Adam Schulze, and Brandon Sanders
- This team used Vertex AI to expand the impact they can have on suppliers and customers by providing accurate and real-time information of products that match either description or image.
Wayfair leaders reflected on the two days and shared their input. Matt Ferrari, Head of Ad Tech, Customer Intelligence, and Machine Learning; Engineering and Product at Wayfair said, “Wayfair has a lot of vendors, but very few strategic partners, and Google is that. Our Partner.” “Thank you all for the participation! I’m grateful to Google, and the many others for helping lead a successful event.”
Wayfair partners with Google Cloud to optimize performance and resiliency, support scaling data-driven decisions, and Increase employee productivity. “Our category is ripe for innovation, and our partnership with Google Cloud helps us ensure that great ideas can come from anywhere by empowering our technologists with cutting-edge products and solutions,” said Ferrari. “We’re proud to partner on efforts like hackathons that align with our team’s eagerness to work on complex, rewarding problems that push the envelope and challenge us to always think big.”
At first Google Cloud won Wayfair over with the speed, reliability and performance of their technology. Hackathons like this one exemplify that what is equally as important is Google Cloud’s willingness to work side-by-side with Wayfair at every level to enable a culture of innovation. Learn more about the Wayfair-Google Cloud partnership here.
An AI-Powered Cost Cutting Guide: 8 Strategies for Maximizing Profits

1721
Of your peers have already read this article.
3:30 Minutes
The most insightful time you'll spend today!
We are increasingly seeing one question arise in virtually every customer conversation: How can the organization save costs and drive new revenue streams?
Everyone would love a crystal ball, but what you may not realize is that you already have one. It’s in your data. By leveraging Data Cloud and AI solutions, you can put your data to work to achieve your financial objectives. Combining your data and AI reveals opportunities for your business to reduce expenses and increase profitability, which is especially valuable in an uncertain economy.
Google Cloud customers globally are succeeding in this effort, across industries and geographies. They are improving ROI by saving money and creating new revenue streams. We have distilled the strategies and actions they are implementing—along with customer examples and tips—in our eBook, “Make Data Work for You.” In it, you’ll find ways you can pare costs, increase profitability, and monetize your data.
Find money in your data
Our Google Cloud teams have identified eight strategies that successful organizations are pursuing to trim expenses and uncover new sources of revenue through intelligent use of data and AI. These use cases range from scaling small efficiencies in logistics to accelerating document-based workflows, monetizing data, and optimizing marketing spend.

The results are impressive. They include massive cost savings and additional revenue. On-time deliveries have increased sharply at one company, and procure-to-pay processing costs have fallen by more than half at another. Other organizations have reaped big gains in ecommerce upselling and customer satisfaction.
We’ve found that businesses across every industry and around the globe are able to take action on at least one of these eight strategies. Contrary to common misperceptions, implementation does not require massive technology changes, crippling disruption to your business, or burdensome new investments.
What success looks like
If you worry your business is not ready or you need to gain buy-in from leadership, the success stories of the 15 companies in this report are helpful examples. Learning how organizations big and small, in different industries and parts of the world, have implemented these data and AI strategies makes the opportunities more tangible.
Carrefour
Among the world’s largest retailers, Carrefour operates supermarkets, ecommerce, and other store formats in more than 30 countries. To retain leadership in its markets, the company wanted to strengthen its omnichannel experience.
Carrefour moved to Google Data Cloud and developed a platform that gives its data scientists secure, structured access to a massive volume of data in minutes. This paved the way for smarter models of customer behavior and enabled a personalized recommendation engine for ecommerce services.
The company saw a 60% increase in ecommerce revenue during the pandemic, which it partly attributes to this personalization.
ATB Financial
ATB Financial, a bank in the Canadian province of Alberta, uses its data and AI to provide real-time personalized customer service, generating more than 20,000 AI-assisted conversations monthly. Machine learning models enable agents to offer clients real-time tailored advice and product suggestions.
Moreover, marketing campaigns and month-end processes that used to take five to eight hours now run in seconds, saving over CA$2.24 million a year.
Bank BRI
Bank BRI, which is owned by the Indonesian government, has 75.5 million clients. Through its use of digital technologies, the institution amasses a lot of valuable data about this large customer base.
Using Google Cloud, the bank packages this data through more than 50 monetized open APIs for more than 70 ecosystem partners who use it for credit scoring, risk management, and other applications. Fintechs, insurance companies, and financial institutions don’t have the talent or the financial resources to do quality credit scoring and fraud detection on their own, so they are turning to Bank BRI.
Early in the effort, the project generated an additional $50 million in revenue, showing how data can drive new sources of income.
How to get going now
“Make Data Work for You” will help you launch your financial resiliency initiatives by outlining the steps to get going. The process lays the groundwork for realizing your own cost savings and new revenue streams by leveraging data and AI.
Among these steps include building frameworks to operate cost efficiently, make informed decisions related to spending and optimize your data and AI budgets.

Operate: Billing that’s specific to your use-case
Control your costs by choosing data and analytics vendors who offer industry-leading data storage solutions and flexible pricing options. For example, multiple pricing options such as flat rate and pay-as-you-go allow you to optimize your spend for best price-performance.
Inform: make informed decisions based on usage
Use your cloud vendor’s dashboards or build a billing data report to gain insights on your spending over time. Make use of cost recommendations and other forecasting tools to predict what your future expenses are going to be.
Optimize: Never pay more than you use
While planning data analytics capacity, organizations often overprovision and overpay than what they actually use. Consider migrating your workloads that have unpredictable demand to a data warehousing solution that offers granular level autoscaling features so that you never have to pay for more than what you use.
There are other key moves that will set your initiative up for success including how to shorten time to value in building AI models and measuring impact. You can find details in the report.
A brighter future
The teams at Google Cloud helped the companies in “Make Data Work for You,” along with many more organizations, use their data and AI to achieve meaningful results. Download the full report to see how you can too.
AgroStar: Small farms in India getting big help from the cloud

13270
Of your peers have already read this article.
3:30 Minutes
The most insightful time you'll spend today!
AgroStar has launched a cloud-based mobile app that is helping to boost crop yields and encourage best practices for small farmers in India. Launched as an on-premises ecommerce platform selling farm tools in 2008, the firm turned to Google Cloud Platform (GCP) to expand its offering. It now uses cloud-based analytics and is deploying ML models to provide timely advice in five languages on everything from seed optimization, crop rotation, and soil nutrition to pest control.
A 2018 survey underscored the demand for agricultural planning for Indian farmers. While farming remains a dominant sector in India, employing half of its labor force, 70 percent of small farmers – those cultivating fewer than three acres – said their crops are damaged by unforeseen weather and pests. An even higher number – 74 percent – say they lack access to farming-related information.
Widening that gap is the relative lack of access to new, higher yield seeds and improved soil analyses for small farmers, who must otherwise rely on traditional methods. “It could take a few years for innovative information to trickle down from universities to small, grassroots farmers,” says Pritesh Gudge, AgroStar Software Engineer. “Today, just by clicking through our Android application, farmers learn about new, effective farming practices and receive advice customized to their crop and soil.”
Connecting a million farmers in the cloud
Operating in the Indian states of Gujarat, Maharashtra, Rajasthan, Orissa, Bihar, and Karnataka, AgroStar is closing the knowledge gap with a full-service, cloud-based SaaS solution – the only one of its kind in India. It combines agronomy, data science, and analytics to help farmers by providing a variety of resources.
AgroStar has reached over a million farmers through its Android app, the AgroStar Agri-Doctor. The mobile client is available as a web-based or full-featured native app. Both provide access to the firm’s knowledge base hosted on GCP, a Q&A forum that connects farmers to each other to help understand and better solve problems and to learn about innovative practices and products. Farmers can also click through to follow local and national market trends that help forecast crop prices.
In addition to the self-service knowledge base, AgroStar provides access to agronomy experts who use cloud-based analytics tools and historical data to provide season-and locale-specific advice to each farmer. “We are now tracking thousands of calls in 5 languages each day,” says Pritesh.
The AgroStar app also provides links to purchase and then track the delivery of farm tools and supplies such as cultivators and fertilizers. An in-house platform manages fulfillment centers and a doorstep delivery network simplifies the supply chain while giving farmers what they need, when they need it. By procuring directly from the manufacturers and primary distributors of farm supplies, Agrostar is achieving cost savings, which it passes on to farmers.
Build fast, pivot faster
From the start, the human and environmental variables of farming in India, not to mention the volume of AgroStar’s few hundred thousand monthly active users, made a highly scalable cloud-based solution inevitable. Farmers rely on the firm’s Agri-Doctor app to provide advice in multiple languages on topics that range widely throughout three growing seasons, each with distinct crop nutrition and rotation cycles and farm implementation requirements.
“For farmers, the focus keeps changing every month, and every season,” says Pritesh. “To serve our growing community, we needed a platform that could process images at high volume, fulfill tools and seed orders across thousands of miles, and respond to multilingual queries. We quickly moved away from spreadsheets and server-based solutions – we needed to build fast and pivot faster.”
Ending late-night deployments
The firm’s first cloud experience was with an AWS solution. At the time, AWS was the only cloud provider in India, but AgroStar wanted to find a solution that was easier to use and offered better integration with Android devices. “Deployment and processing costs were very high, and the developer tools and documentation were not as intuitive as we needed,” says Pritesh.
When GCP service arrived in India in October 2017, AgroStar embarked on a platform re-implementation that made possible dramatic changes in the way it developed and deployed its solution. Using Google Kubernetes Engine (GKE) for crop advice management and Compute Engine for its production application services, the firm built the backend for the Agri-Doctor discussion forum in only three weeks. The platform’s microservice architecture is implemented in Python and Golang and deployed on GCP.
AgroStar began to realize significant efficiencies in its build, deploy, and test cycles. “We previously needed to work overnight to deploy to production,” says Pritesh. “Now using Google for Kubernetes containers and a rolling update strategy, we can deploy during the day without any problems or interruptions to service.”
The move to GCP streamlined AgroStar’s stack. “We were running 12 independent instances on AWS,” says Pritesh. “With Google Kubernetes Engine, we are deployed on a single cluster at a cost savings of $1,300 per month and growing.”
Improving customer response times by 85 percent
With a managed deployment capability, AgroStar can devote more time and resources to executing on its platform and Agri-Doctor app development plan. A strategic goal was managing customer response times as the firm grew its base. GCP has helped the firm meet that goal, achieving an 85 percent improvement in customer response times even as traffic grew significantly.
“With our on-premises solution, we could handle around 100 customers daily, which took 30 to 50 minutes for each customer,” says Pritesh. “We now handle thousands of customers daily, taking only 4 to 5 minutes for each one.”
AgroStar used Firebase to implement its Agri-Doctor app. A real-time cloud database, Firebase provides an API that enables the Agri-Doctor advice forum to be synchronized across all its far-flung mobile clients, effectively sharing knowledge base updates with one million users in near real time.
Using cloud tools to manage and monitor
Cloud Pub/Sub, Kafka, and Cloud Dataflow manage data ingestion and queueing of event and transaction data to the analytics layer. BigQuery fetches and persists data to Cloud Storage. Cloud SQL and dashboards powered by Tableau deliver farmer crop and soil profiles within minutes.
Cloud IAM helps AgroStar control access to all its cloud resources. And Stackdriver, the integrated logging aggregation capability for GCP, helps monitor and speed debugging on every tier of the AgroStar solution.
Machine learning to enhance yields
AgroStar is developing a variety of ML components to improve responsiveness and extend its platform offerings.
To speed up the diagnosis of and treatment for crop blight, AgroStar is building a deep learning pipeline using TensorFlow. The pipeline relies on GoogLeNet models that use multi-layered convolutional visual pattern recognition. It will assess uploaded images to support a disease-detection capability on the mobile app. Based on the commercially successful AI algorithms that automated postal code processing, GoogLeNet offers improved performance and computational efficiencies by using a creative layering technique that distinguishes them from older, sequential recognition engines.
To improve its customer search experience, AgroStar is developing an ML pipeline that shrinks fetch times by suggesting tags mapped to stored data. Processed using TPUs, Cloud Natural Language and Video AI, the tags provide a metadata layer that supports queries in any of the ten natural languages that AgroStar farmers can use.
The AgroStar search pipeline consists of Long Short-Term Memory (LSTM) models of Recurrent Neural Networks. Recurrent networks exhibit “memory” through iterative processing and are distinguished from feedforward networks by a feedback loop connected to their past decisions, ingesting their own outputs moment after moment as input.
Implementing a recommendation engine
The firm is also adapting the Random Forests TensorFlow AI model to develop a crop and product recommendation engine. The model is trained by consuming numerical (rainfall, humidity, water availability per acre) and categorical (soil type, water sources) parameters to suggest appropriate products by season, region, and locale.
To simplify the product suggestion experience, AgroStar developers are testing Cloud Dialogflow, the Google Cloud conversational interface, to build a chatbot capability into its mobile app. The bot will track a farmer’s crop schedules and answer simple questions by linking to the recommendation engine.
AgroStar is also extending its analytics platform with AI-powered sales planning and forecasting. Using linear regression models implemented in TensorFlow and powered by Cloud ML Engine, the capability will enhance supply chain logistics as the company scales its operations across India.
To provide a credit on-demand offering for a range of seed-to-harvest cycle products, AgroStar is attempting to use Vision API to create an AI model that will convert uploaded photos of customer application records into standard data formats. The firm’s credit policy features a grace period in which farmers begin paying back loans after harvested crops go to market.
A versatile and friendly development ecosystem
AgroStar credits the convivial tools and documentation that GCP offers and its incremental, pay-as-you-go pricing model for both the firm’s success and its ability to manage growth.
“What Google Cloud offers is extremely good documentation and extremely simple-to-use tools and interfaces across all services,” says Pritesh. “It helped us initially deploy our platform and at every scale that we have required since then, and its cost effectiveness enabled us to staff up to meet new feature milestones.”
Leverage ML to Spot Anomalies in Real-time Forex Data

3111
Of your peers have already read this article.
6:00 Minutes
The most insightful time you'll spend today!
Let’s say you are a quantitative trader with access to real-time foreign exchange (forex) price data from your favorite market data provider. Perhaps you have a data partner subscription, or you’re using a synthetic data generator to prove value first. You know there must be thousands of other quants out there with your same goal. How will you differentiate your anomaly detector?
What if, instead of training an anomaly detector on raw forex price data, you detected anomalies in an indicator that already provides generally agreed buy and sell signals? Relative Strength Index (RSI) is one such indicator; it is often said that RSI going above 70 is a sell signal, and RSI going below 30 is a buy signal. As this is just a simplified rule, it means there could be times when the signal is inaccurate, such as a currency market correction, making it a prime opportunity for an anomaly detector.
This gives us the following high level components:

Of course, we want each of these components to handle data in real time, and scale elastically as needed. Dataflow pipelines and Pub/Sub are the perfect services for this. All we need to do is write our components on top of the Apache Beam sdk, and they’ll have the benefit of distributed, resilient and scalable compute.
Luckily for us, there are some great existing Google plugins for Apache Beam. Namely, a Dataflow time-series sample library that includes RSI calculations, and a lot of other useful time series metrics; and a connector for using AI Platform or Vertex AI inference within a Dataflow pipeline. Let’s update our diagram to match, where the solid arrows represent Pub/Sub topics.

The Dataflow time-series sample library also provides us with gap-filling capabilities, which means we can rely on having contiguous data once the flow reaches our machine learning (ML) model. This lets us implement quite complex ML models, and means we have one less edge case to worry about.
So far we’ve only talked about the real time data flow, but for visualization and continuous retraining of our ML model, we’re going to want historical data as well. Let’s use BigQuery as our data warehouse, and Dataflow to plumb Pub/Sub into it. As this plumbing job is embarrassingly parallelizable, we wrote our pipeline to be generic across data types and share the same Dataflow job, such that compute resources can be shared. This results in efficiencies of scale both in cost savings and time required to scale-up.

Data Modeling
Let’s discuss data formats a bit further here. An important aspect of running any data engineering project at scale is flexibility, interoperability and ease of debugging. As such, we opted to use flat JSON structures for each of our data types, because they are human readable and ubiquitously understood by tooling. As BigQuery understands them too, it’s easy to jump into the BigQuery console and confirm each component of the project is working as expected.

As you can see, the Dataflow sample library is able to generate many more metrics than RSI. It supports generating two types of metrics across time series windows, metrics which can be calculated on unordered windows, and metrics which require ordered windows, which the library refers to as Type 1 metrics and Type 2 metrics, respectively. Unordered metrics have a many-to-one relationship, which can help reduce the size of your data by reducing the frequency of points through time. Ordered metrics run on the outputs of the unordered metrics, and help to spread information through the time domain without loss in resolution. Be sure to check out the Dataflow sample library documentation for a comprehensive list of metrics supported out of the box.
As our output is going to be interpreted by our human quant, let’s use the unordered metrics to reduce the time resolution of our flow of real time data to one per second, or one hertz. If our output was being passed into an automated trading algorithm, we might choose a higher frequency. The decision for the size of our ordered metrics window is a little more difficult, but broadly determines the amount of time-steps our ML model will have for context, and therefore the window of time for which our anomaly detection will be relevant. We at least need it to be larger than our end-to-end latency, to ensure our quant will have time to act. Let’s set it to five minutes.
Data Visualization
Before we dive into our ML model, let’s work on visualization to give us a more intuitive feel for what’s happening with the metrics, and confirm everything we’ve got so far is working. We use the Grafana helm chart with the BigQuery plugin on a Google Kubernetes Engine (GKE) Autopilot cluster. The visualisation setup is entirely config-driven and provides out-of-the-box scaling, and GKE gives us a place to host some other components later on.

GKE Autopilot has Workload Identity enabled by default, which means we don’t need to worry about passing around secrets for BigQuery access, and can instead just create a GCP service account that has read access to BigQuery and assign it to our deployment through the linked Kubernetes service account.
That’s it! We can now create some panels in a Grafana dashboard and see the gap filling and metrics working in real time.

Building and deploying the Machine Learning Model
Ok, ML time. As we alluded to earlier, we want to continuously retrain our ML model as new data becomes available, to ensure it remains up to date with the current trend of the market. TensorFlow Extended (TFX) is a platform for creating end-to-end machine learning pipelines in production, and eases the process around building a reusable training pipeline. It also has extensions for publishing to AI Platform or Vertex AI, and it can use Dataflow runners, which makes it a good fit for our architecture. The TFX pipeline still needs an orchestrator, so we can host that in a Kubernetes job, and if we wrap it in a scheduled job, then our retraining happens on a schedule too!

TFX requires our data be in the tf.Example format. The Dataflow sample library can output tf.Examples directly, but this tightly couples our two pipelines together. If we want to be able to run multiple ML models in parallel, or train new models on existing historical data, we need our pipelines to only be loosely coupled. Another option is to use the default TFX BigQuery adaptor, but this restricts us to each row in BigQuery mapping to exactly one ML sample, meaning we can’t use recurrent networks.
As neither of the out-of-the-box solutions met our requirements, we decided to write a custom TFX component that did what we needed. Our custom TFX BigQuery adaptor enables us to keep our standard JSON data format in BigQuery and train recurrent networks, and it keeps our pipelines loosely coupled! We need the windowing logic to be the same for both training and inference time, so we built our custom TFX component using standard Beam components, such that the same code can be imported in both pipelines.
def window_elements(pipeline: beam.Pipeline,window_length: int,drop_irregular_windows: bool = True,sort_windows_by: str = "timestamp",):"""Window elements into regular windows of a given size.Assumes elements flow at a fixed rate of 1Hz."""def _sort_windows(window: Iterable[Dict[Text, Any]]) -> List[Dict[Text, Any]]:sorted_window = sorted(window, key=lambda e: e[sort_windows_by])return sorted_windowwindowed_elements = (pipeline| "AddConstantKey" >> beam.Map(lambda item: (0, item))| "WithSlidingWindow">> beam.WindowInto(beam.transforms.window.SlidingWindows(window_length, 1),trigger=beam.transforms.trigger.AfterCount(window_length),accumulation_mode=beam.transforms.trigger.AccumulationMode.DISCARDING,)| "CombineWindow" >> beam.GroupByKey()| "GetValues" >> beam.Values())if drop_irregular_windows:windowed_elements = windowed_elements | "EnforceWindowLengths" >> beam.Filter(lambda w: len(w) == window_length).with_output_types(List[Dict[Text, Any]])if sort_windows_by is not None:windowed_elements = windowed_elements | "Sort" >> beam.Map(_sort_windows).with_output_types(List[Dict[Text, Any]])return windowed_elements
With our custom generator done, we can start designing our anomaly detection model. An autoencoder utilising long-short-term-memory (LSTM) is a good fit for our time-series use case. The autoencoder will try to reconstruct the sample input data, and we can then measure how close it gets. That difference is known as the reconstruction error. If there is a large enough error, we call that sample an anomaly. To learn more about autoencoders, please consider reading chapter 14 from Deep Learning by Ian Goodfellow, Yoshua Bengio, and Aaron Courville.
Our model uses simple moving average, exponential moving average, standard deviation, and log returns as input and output features. For both the encoder and decoder subnetworks, we have 2 layers of 30 time step LSTMs, with 32 and 16 neurons, respectively.
In our training pipeline, we include z score scaling as a preprocessing transformer – which is usually a good idea when it comes to ML. However, there’s a nuance to using an autoencoder for anomaly detection. We need not only the output of the model, but also the input, in order to calculate the reconstruction error. We’re able to do this by using model serving functions to ensure our model returns both the output and preprocessed input as part of its response. As TFX has out-of-the-box support for pushing trained models to AI Platform, all we need to do is configure the pusher, and our (re)training component is complete.
Detecting Anomalies in real time
Now that we have our model in Google Cloud AI Platform, we need our inference pipeline to call to it in real time. As our data is using standard JSON, we can easily apply our RSI rule of thumb inline, ensuring our model only runs when needed. Using the reconstructed output from AI Platform, we are then able to calculate the reconstruction error. We choose to stream this directly into Pub/Sub to enable us to dynamically apply an anomaly threshold when visualising, but if you had a static threshold you could apply it here too.
with beam.Pipeline(options=pipeline_options) as pipeline:(pipeline| "ReadFromPubSub">> beam.io.ReadFromPubSub(topic=input_metrics,timestamp_attribute=timestamp_key,)| "DeserialiseJSON" >> beam.Map(pubsub_serialiser.to_json)| "FilterSymbol" >> beam.Filter(lambda m: m["symbol"] == symbol)| "FilterRSIThreshold">> beam.Filter(lambda m: m["RELATIVE_STRENGTH_INDICATOR"] > rsi_upper_thresholdor m["RELATIVE_STRENGTH_INDICATOR"] < rsi_lower_threshold)| "WindowElements" >> window_elements(window_length)| "RunAutoencoder">> run_windowed_inference(gcp_project_id,model_name,window_length,{f: "FLOAT" for f in feature_metrics},)| "CalcReconError" >> beam.Map(calc_reconstruction_err)| "ToJSON">> beam.Map(lambda re: {"symbol": symbol, "reconstruction_error": re})| "SerialiseJSON" >> beam.Map(pubsub_serialiser.from_json)| "WriteToPubSub">> beam.io.WriteToPubSub(topic=output_alerts,timestamp_attribute=timestamp_key,))
Summary
Here’s what the wider architecture looks like now:

More importantly though, does it fit for our use case? We can plot the reconstruction error of our anomaly detector against the standard RSI buy/sell signal, and see when our model is telling us that perhaps we shouldn’t blindly trust our rule of thumb. Go get ‘em, quant!

In terms of next steps, there are many things you could do to extend or adapt what we’ve covered. You might want to explore with multi-currency models, where you could detect when the price action of correlated currencies is unexpected, or you could connect all of the Pub/Sub topics to a visualization tool to provide a real-time dashboard.
Give it a try
To finish it all off, and to enable you to clone the repo and set everything up in your own environment, we include a data synthesizer to generate forex data without needing access to a real exchange. As you might have guessed, we host this on our GKE cluster as well. There are a lot of other moving parts – TFX uses a SQL database and all of the application code is packaged into a docker image and deployed along with the infra using Terraform and cloud build. But if you’re interested in those nitty gritty details, head over to the repo and get cloning!
Feel free to reach out to our teams at Google Cloud and Kasna for help in making this pattern work best for your company.
More Relevant Stories for Your Company

Everything a Marketer Needs to Know About Machine Learning
As consumer expectations grow for more personalized, relevant, and assistive experiences, machine learning is becoming an invaluable tool to help meet those demands. It’s helping marketers create smarter customer segmentations, deliver more relevant creative campaigns, and measure performance more effectively. In fact, 85% of executives believe AI will allow their

How Vertex AI NAS is Suitable for Most Advanced ML Workloads
Vertex AI launched with the premise “one AI platform, every ML tool you need.” Let’s talk about how Vertex AI streamlines modeling universally for a broad range of use cases. The overall purpose of Vertex AI is to simplify modeling so that enterprises can fast track their innovation, accelerate time to market,

Hospitals Can Offer Interconnected Patient Experiences Using Google’s Natural Language Services
Machine Learning (ML) in healthcare helps extract data from conversations, medical records, forms, research reports, insurance claims and other documents across the care value-chain to help care providers have a holistic view of their patients to draw insights for diagnoses and treatments. With Natural Language Processing(NLP), healthcare organizations can program

Johnson & Johnson Increases it’s Ability to Find Highly Qualified Staffers for Business Critical Roles by 41% with Easy-to-Use AI
Job seekers can often feel lost or disconnected—like the right opportunity is out there, but they don’t know where or how to look. Employers face a similar challenge when trying to attract the right candidates. Many companies, especially large enterprises, face a talent shortage across a range of critical roles. For global






