<?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 Alexander Wijns on Medium]]></title>
        <description><![CDATA[Stories by Alexander Wijns on Medium]]></description>
        <link>https://medium.com/@awijns?source=rss-6cc2e8dcf5cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fuK8Rhdb_j_DNUgY9HoYow.jpeg</url>
            <title>Stories by Alexander Wijns on Medium</title>
            <link>https://medium.com/@awijns?source=rss-6cc2e8dcf5cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:32:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@awijns/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[Build a recommender with BigQuery ML]]></title>
            <link>https://medium.com/g-company/build-a-recommender-with-bigquery-ml-15e67a457548?source=rss-6cc2e8dcf5cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/15e67a457548</guid>
            <category><![CDATA[google-cloud-workflows]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alexander Wijns]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 12:51:15 GMT</pubDate>
            <atom:updated>2022-02-01T12:51:15.908Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Flex slots and Cloud Workflows</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QaXoUcdEiX4oTOCy" /><figcaption>Photo by <a href="https://unsplash.com/@xoforoct?utm_source=medium&amp;utm_medium=referral">EJ Strat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the <a href="https://medium.com/g-company/build-a-recommender-with-bigquery-ml-4dfb72041f6e">previous post</a>, we talked about why you would want to use matrix factorization (and collaborative filtering in general) to build a recommender system, and why BigQuery provides a good place to do it, even if it’s only for a baseline model. In this post, we’ll assume that after reading part 1 you now have an uncontrollable urge to generate recommendations with BigQuery ML, but need a little help getting started. To this end, this post will be a lot more hands-on, using SQL stored procedures to define the necessary tasks in our small pipeline and Cloud Workflows to automate these tasks in a fully serverless way.</p><p>As we discussed previously, before you can create and train a matrix factorization model in BigQuery, you need to reserve the <a href="https://cloud.google.com/bigquery/docs/slots">slots</a> that will perform the necessary data processing. We’ll kick things off with that.</p><h3>Flex slots</h3><p>Until not so long ago, you could only reserve slots on a monthly or yearly basis, which would be overkill for a daily or weekly scheduled batch process, let alone a quick trial run. Luckily, these days you can also reserve what are called Flex slots. In a nutshell, you can reserve a number of slots when you need them, run your job, and turn them off again when the job is done. A crucial point here is that you keep paying for those slots until you explicitly turn them off again. That fact alone should already make the little voice in your head go “automate this sh*t.” Let’s first spend a few words on how to turn on and off a Flex slot reservation and organise these tasks in a way that will make it easier to orchestrate and automate the flow later on.</p><p>Setting up a Flex slots reservation comprises three steps:</p><ol><li><strong>Capacity commitment</strong>: commit to paying for a fixed number of slots for a certain duration. The beauty of Flex slot is that you only need to commit for 60 seconds at the start, and can cancel at any time after that first minute.</li><li><strong>Reservation</strong>: optionally split the commitment into different parts that fit how you organise your workloads (for example, things like production, test and analytics) so that these different workloads with potentially very different constraints and priorities won’t fight each other over resources. If you don’t do this the whole commitment is linked to one <em>default</em> reservation.</li><li><strong>Assignment</strong>: to actually use the slots you then need to assign a project, folder or organisation to one of the reservations. Projects that are not assigned to a reservation will keep using the default on-demand pricing (and won’t be able to run matrix factorization, for example).</li></ol><p>A first (optional, but useful) step towards automation, is to group these three tasks into one SQL stored procedure in BigQuery, as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81191e6c0af44e60c3b191873f5ab55a/href">https://medium.com/media/81191e6c0af44e60c3b191873f5ab55a/href</a></iframe><p>Note that the “admin project,” where you create the commitment and manage the reservations, does not need to be the same as the assignee in the final statement. It’s in this step that you choose which projects or folders will actually make use of which chunks of the reserved slots by assigning them to a specific reservation. In this example, we set the capacity to 100 slots, which is the minimum commitment size and should be more than enough to get you started.</p><p>Very importantly, you also want to be able to just as easily turn them back off. You do this in reverse order: first remove the assignment(s), then the reservation(s) and then finally the commitment itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34c2297d9a19deab9185d901f2d610b2/href">https://medium.com/media/34c2297d9a19deab9185d901f2d610b2/href</a></iframe><h3>Creating the model</h3><p>In order to automate the whole process, it’s also useful to store the creation (and training) of the BigQuery ML matrix factorization model in its own procedure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa86d0372c73e8ed52f43e18fd8eab8/href">https://medium.com/media/3aa86d0372c73e8ed52f43e18fd8eab8/href</a></iframe><p>Notice how easy it is to train a machine learning model with just a few lines of SQL code. Even though it might at first glance look like you are only setting up the model with this statement, BigQuery will automatically also train it on the data as it is defined in the SELECT clause. Needless to say that this clause could involve any data transformations you need (but do also have a look at the <a href="https://cloud.google.com/bigquery-ml/docs/bigqueryml-transform">TRANSFORM</a> clause), as long as at the end the columns expected as input by the model are selected, in this case user, item, and rating.</p><p>For pedagogical reasons, we kept this model creation statement as simple as possible, because the defaults are sensible for many use cases. But the OPTIONS clause allows for a lot of customization if you know what you’re doing. For example, explicit feedback (see <a href="https://medium.com/g-company/build-a-recommender-with-bigquery-ml-4dfb72041f6e">part 1</a>) is the default, but if you want to train a model based on implicit feedback, you can set FEEDBACK_TYPE=&quot;IMPLICIT&quot;. Another important hyperparameter to experiment with, in case the default does not suit your needs, is the number of latent factors NUM_FACTORS (again, see part 1).</p><p>I also hear you thinking “Wouldn’t it be better to parametrize these queries, instead of hardcoding the project and dataset name all over the place?” and you would, of course, as you probably usually are, be absolutely right. Unfortunately, even though there is such a thing as <a href="https://cloud.google.com/bigquery/docs/parameterized-queries">parametrized SQL queries</a>, they can’t be used for identifiers such as table names. In order to do this properly (read: without a lot of bash hacking), I would advise looking into tools like <a href="https://www.getdbt.com/">dbt</a>.</p><h3>Cloud Workflows</h3><p>Now, as much as you’d surely enjoy running these three procedures by hand every day, let’s turn our attention to automating them with an orchestration tool. It might feel like you’d just about get away with shell scripting this small workflow right now, but especially once this becomes part of a bigger production pipeline, you’ll want to look into more robust options. There are many orchestration solutions out there, several of them managed on, or native to, GCP, but those either require you to manage some infrastructure, or might be a bit heavy handed and costly for your needs, often both. A very nice, fairly recent offering on GCP is <a href="https://cloud.google.com/workflows/docs/overview">Cloud Workflows</a>, a completely serverless way to orchestrate pipelines of services on GCP. Moreover, it allows you to start small just as easily as you would with a shell script, but will grow with you as your needs grow much more willingly than good old (but occasionally grumpy) bash.</p><p>Cloud Workflows allows us to run our three tasks one after the other, each time waiting for the previous step to complete, with a simple YAML instruction file. You can find the full code example <a href="https://github.com/gcompany/bqml-workflow">here</a> (and the full specification <a href="https://cloud.google.com/workflows/docs/reference/syntax">here</a>), but let’s break it down step by step.</p><p>First, we create the Flex reservation and wait a bit for the slots to become available:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af82ea6d9aa41c203eeb3d40cf1babbd/href">https://medium.com/media/af82ea6d9aa41c203eeb3d40cf1babbd/href</a></iframe><p>You can see here that a workflow is composed of several <a href="https://cloud.google.com/workflows/docs/reference/syntax/steps">steps</a>:</p><ol><li>The first step, init, (you can give these steps any name you want, as long as it follows a few conventions) defines a few variables for easy reference throughout the workflow.</li><li>Then, in create_slots, we use the <a href="https://cloud.google.com/workflows/docs/reference/googleapis/bigquery/Overview">BigQuery API connector</a> to conveniently call the jobs.insert endpoint to invoke our get_slots procedure.</li><li>In the log_create_job_id step, we use the handy integration with <a href="https://cloud.google.com/logging">Cloud Logging</a> to log the id of the created job for later reference or debugging.</li><li>Then, it’s crucial to wait for the slots to be available before moving on to the next step. There are a few options here. In this example, we’ve chosen the lazy approach, namely to simply wait for 2 minutes by calling the built-in sys.sleep. This will typically be sufficient, but is not guaranteed to be enough.</li></ol><p>You might be tempted to use the job id that was returned by the create_slots step in order to check the status of the slot creation (see below for an example of this approach), but it turns out that even if the job status is “DONE” the slots might not be quite ready for use yet. As an exercise for the adventurous reader, I suggest looking into the INFORMATION_SCHEMA.RESERVATIONS_BY_PROJECT <a href="https://cloud.google.com/bigquery/docs/information-schema-reservations">metadata table</a>. You can query this table to make sure the reservation is there before proceeding to the next step. If it’s not, you sys.sleep, a bit longer in a conditional loop (see below).</p><p>Next, assuming we’ve made sure that the slots are ready for action, we create and train the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60032b2af9f6b7babc1ed31555cb1b1e/href">https://medium.com/media/60032b2af9f6b7babc1ed31555cb1b1e/href</a></iframe><p>Again, because we’ve nicely prepared our procedures, training the model is once more a simple query passed on to the jobs.insert endpoint. This time, we do check the job id to make sure the model is fully trained before moving on to the next step. To achieve this, we use a switch block to check that the job status equals “DONE”. If not, we push some status info to the logs and sleep for a while. We could consider using exponential backoff here, making the sleep times longer and longer until some threshold is reached, after which we might prefer to abort the workflow altogether and trigger an alert to an administrator account. Do keep in mind here that training can take a while, depending on the amount of training data. If the status is “DONE”, we continue.</p><p>The final step is now easy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5592e3c3e24e4016ac134791ccff4427/href">https://medium.com/media/5592e3c3e24e4016ac134791ccff4427/href</a></iframe><p>We call the drop_slots procedure, get the job status and use that as a return value of the workflow. But notice that we’re again being a bit sloppy here. We’re not properly handling a possible failure to drop the slots, so that we risk paying for them for much longer than we need to. You could <a href="https://cloud.google.com/workflows/docs/reference/syntax/catching-errors">catch the exception</a> and do a few retries before really giving up. Arguably, you’d anyway want to monitor the resources through independent <a href="https://cloud.google.com/monitoring">services</a> and take appropriate action in case slots are turned on for much longer than expected.</p><h3>Wrapping up</h3><p>This example workflow gets you 70% of the way as far as model training goes. As we’ve highlighted throughout, there are a few places in the workflow where you’d want to build in some more robust status checks, exception handling, etcetera. Another useful exercise is to <a href="https://cloud.google.com/workflows/docs/reference/syntax/runtime-args">parametrize</a> the workflow in order to remove any explicit mention of the project and dataset, which is not hard to do and will make your workflow sit more snugly inside your Terraform setup.</p><p>Then, the next step would, of course, be to use this model to generate some <a href="https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-recommend">batch predictions</a> and store them in your production database so that you can use the results in your application. This smells like a whole other workflow to me! The whole thing could be kicked off daily (for example) by a <a href="https://cloud.google.com/scheduler/docs/quickstart">scheduler</a>.</p><p>If all of this still feels a bit daunting to you, feel free to <a href="https://g.company/en_nl/solutions/data-driven-organizations/">contact us</a>! And see you next time.</p><p><em>Big shout-out to </em><a href="https://www.linkedin.com/in/basleenders/"><em>Bas Leenders</em></a><em> for helping out with the final tweaks and edits of part 1 and 2!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15e67a457548" width="1" height="1" alt=""><hr><p><a href="https://medium.com/g-company/build-a-recommender-with-bigquery-ml-15e67a457548">Build a recommender with BigQuery ML</a> was originally published in <a href="https://medium.com/g-company">g-company</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 recommender with BigQuery ML]]></title>
            <link>https://medium.com/g-company/build-a-recommender-with-bigquery-ml-4dfb72041f6e?source=rss-6cc2e8dcf5cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dfb72041f6e</guid>
            <category><![CDATA[matrix-factorization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alexander Wijns]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 10:21:40 GMT</pubDate>
            <atom:updated>2022-02-03T08:55:24.073Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: introduction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wY3jEGiQJLoyIEoF" /><figcaption>Photo by <a href="https://unsplash.com/@aarez?utm_source=medium&amp;utm_medium=referral">Aarón González</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This is the first of two posts on using BigQuery to build (a component of) a recommender system. This first part is mostly conceptual, while in the </em><a href="https://medium.com/g-company/build-a-recommender-with-bigquery-ml-15e67a457548"><em>second part</em></a><em> we’ll dive into some actual code and explain how to set up a daily training pipeline in practice.</em></p><p>Here’s a scenario for you: say you have a website on which people can show off their self-made digital art creations (each obviously linked to an NFT) and other people can rate them by, say, 1 (try again…) through 5 (do this again!!). You would like to show recommendations for pieces of art a user might like based on their “taste”. You could show “similar” items, but it’s not straightforward at all to extract features from these artworks to base yourself on. You allow people to tag and describe their art, but most of them are too lazy to do this well, if they do it at all. So, what are called “content-based similarities” are not an easy fit in this case. You do however stream all the user ratings to a table, called a rating matrix (often also called a user-item matrix), in your database. This table has (at least) three columns: the user id, the item id and the rating. Typically it’s also useful to store a timestamp, for example to enable you to split the data into training, validation and test sets.</p><h3>Collaborative filtering</h3><p>This type of data allows you to generate recommendations in a different way. Say you want to know whether to recommend item A to user 1. If other users “similar to” user 1 (in the sense that they rated other items similarly) rate item A highly, user 1 might also like it. Alternatively, if items “similar to” item A (in the sense that they were rated similarly by other users) got a high rating from user 1, user 1 might like item A as well. After you’ve read the previous two sentences a few times, store them in your brain under the heading of “collaborative filtering”.</p><p><a href="https://developers.google.com/machine-learning/recommendation/collaborative/basics">Collaborative</a> <a href="https://en.wikipedia.org/wiki/Collaborative_filtering#:~:text=Collaborative%20filtering%20(CF)%20is%20a%20technique%20used%20by%20recommender%20systems.&amp;text=In%20the%20newer%2C%20narrower%20sense,from%20many%20users%20(collaborating).">filtering</a> is a generic term for many different, albeit related, algorithms, and is actually often combined with other techniques in what are called <a href="https://en.wikipedia.org/wiki/Recommender_system#Hybrid_recommender_systems">hybrid recommenders</a>. It’s as much an art as a science to figure out which approach best fits your use case. And on top of that the state of the art is constantly evolving. One of the challenges is that you typically end up with what is called a very sparse rating matrix: you might have thousands of items and millions of users, but every user will only have explicitly rated a handful of items, if they’re even willing to rate anything at all. One of the reasons for the ever increasing refinement of state of the art approaches is to find new ways of fighting this sparseness.</p><p>In these posts, we’ll focus on using explicit feedback, based on explicit user ratings as described above. But it’s good to keep in mind that you can also base your model on what is called implicit feedback. In this approach, you don’t rely on explicit ratings, but you try to interpret other types of user behaviour, such as clicks on items, play times of songs, time spent on a page or shares on social media as a level of interest a user might have in an item. Needless to say, such a model is more complicated to build and subtle to interpret, but it also offers a way to partially mitigate the sparsity problem. To this end, it can even be combined with explicit feedback modelling.</p><p>Many collaborative filtering approaches are based on a technique called <a href="https://developers.google.com/machine-learning/recommendation/collaborative/matrix">matrix</a> <a href="https://en.wikipedia.org/wiki/Matrix_factorization_(recommender_systems)">factorization</a>. There are again different ways in which this can be achieved, but in essence the goal of matrix factorization is to write the rating matrix as a product of two “smaller” and more dense matrices (representing users and items, respectively) using something called a latent representation. Users and items are both represented as higher dimensional vectors in the same “latent space”. Every component in this latent space is called a latent factor and conceptually represents an aspect of a user’s interests or the corresponding item characteristic. For example, if you’re building a movie recommender, one of the latent factors could indicate how much a user is into comedy, and similarly, how much a movie contains comedy. If this factor is high in both user 1 and movie A, it will increase the likelihood that this is a good recommendation. In reality, the latent factors will be more subtle than that, and are actually learned by the model during training.</p><h3>BigQuery ML</h3><p>Ok, you ask, now that we’re all collaborative filtering experts and I have a rating matrix based on explicit feedback ready to go, how do I actually do this in practice? One way to go about it is to build your own model using your favourite Python framework, but even though there are a lot of implementations out there, even if one of them suits your needs perfectly, you’d still need to set up a preprocessing pipeline, training infrastructure, model validation and a way to get recommendations from the model (even if it’s through a batch process). In reality, it’s actually even more complicated than that. Most likely, you won’t know ahead of time which approach works best for your use case, so you’ll need to try at least a few, and for each model try at least a few hyperparameters to see which version of which model works best. I bet you (smart cookie, you) see where this is going. And of course this early in the game you don’t even have a solid grasp on the return on investment this fancy recommender will actually bring.</p><p>All of this to say, even if you’ll end up investing into a more involved machine learning infrastructure eventually, it’s good to start with a baseline that’s relatively quick to set up and allows you to easily play around with some hyperparameters, an important one being the number of latent factors. <a href="https://cloud.google.com/bigquery/docs/introduction">BigQuery</a> is a highly scalable structured data storage service and SQL engine which is often used as the foundation of a data warehouse and general “playground” for data analysts. More recently, it also offers a wide range of machine learning capabilities, allowing you to train ML models with often just a few lines of SQL. One of the goodies on offer is precisely a matrix factorization model. It uses a widely used and battle-tested variant called <a href="https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-create-matrix-factorization#feedback-info">Alternating Least Squares</a> (ALS) for <a href="https://cloud.google.com/bigquery-ml/docs/bigqueryml-mf-explicit-tutorial">explicit feedback</a> or <a href="http://yifanhu.net/PUB/cf.pdf">Weighted Alternating Least Squares</a> (WALS) for <a href="https://cloud.google.com/bigquery-ml/docs/bigqueryml-mf-implicit-tutorial">implicit feedback</a>. In other words, it might very well be that this fairly quickly to set up baseline model is the one that you end up using in production.</p><h3>But not so fast…</h3><p>I’ll skip the SQL and BigQuery intro that you can find in <a href="https://www.freecodecamp.org/news/sql-and-databases-full-course/">many</a> <a href="https://www.datacamp.com/courses/introduction-to-sql">other</a> <a href="https://www.coursera.org/specializations/from-data-to-insights-google-cloud-platform">places</a>, if you don’t mind. But I would like to focus on another, initially slightly cumbersome, aspect of the workflow. Remember how I said that BigQuery ML makes training and running ML models a breeze. Well… as it turns out, matrix factorization does require an additional step.</p><p>When starting out with BigQuery, most people will use its <a href="https://cloud.google.com/bigquery/pricing#on_demand_pricing">on-demand pricing scheme</a>, where you simply pay for the number of bytes read per (uncached) query. This makes the barrier of entry very low, as you can quickly start exploring your data without worrying about costs as long as the size of the data involved stays within certain bounds — although what “low cost” and “certain bounds” mean will depend on your situation. For some types of workloads this is however not a fair representation of the amount of processing power needed. Matrix factorization using ALS is such a case, as it requires many iterations over the data to achieve good model performance. Because of this, a different pricing scheme is used in this case — instead of paying for the amount of <em>data read</em>, you pay for the amount of <em>processing power needed</em>. To this end, you first need to <a href="https://cloud.google.com/bigquery/docs/reservations-intro">reserve</a> the number of processing units, called <a href="https://cloud.google.com/bigquery/docs/slots">slots</a>, you need (or are willing to pay) in order to process the data.</p><p><em>By now you must be screaming at your screen “Alex, stop it with the general chat, and show me some code already!”. Duly noted. In the </em><a href="https://medium.com/g-company/build-a-recommender-with-bigquery-ml-15e67a457548"><em>next part</em></a><em>, we’ll use </em><a href="https://cloud.google.com/workflows/docs/overview"><em>Workflows</em></a><em> to automate a small pipeline that reserves the BigQuery slots that we need, trains a matrix factorization model, and importantly, removes the slot reservation when we’re done. Hopefully see you there!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dfb72041f6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/g-company/build-a-recommender-with-bigquery-ml-4dfb72041f6e">Build a recommender with BigQuery ML</a> was originally published in <a href="https://medium.com/g-company">g-company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-world TensorFlow Extended]]></title>
            <link>https://awijns.medium.com/real-world-tensorflow-extended-b0ecaf0827e6?source=rss-6cc2e8dcf5cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ecaf0827e6</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[tensorflow-extended]]></category>
            <dc:creator><![CDATA[Alexander Wijns]]></dc:creator>
            <pubDate>Fri, 16 Apr 2021 08:02:04 GMT</pubDate>
            <atom:updated>2021-04-16T08:02:04.953Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Introductions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJfNwradVl5uowGuK1RkHA.jpeg" /><figcaption>Hercules and the Hydra of Lerna — Los Angeles County Museum of Art, Public domain, via <a href="https://commons.wikimedia.org/wiki/File:Hercules_and_the_Hydra_of_Lerna_LACMA_65.37.9.jpg">Wikimedia Commons</a></figcaption></figure><p><em>This is the first in a series of posts on </em><a href="https://www.tensorflow.org/tfx"><em>TensorFlow Extended</em></a><em>. In this post I’ll set the stage without diving into any code yet, but bare with me. In subsequent posts, I’ll try to steer clear from the typical “getting started” content (the </em><a href="https://www.tensorflow.org/tfx/guide"><em>official docs</em></a><em> do a fantastic job at that) and instead dive into some real-world use cases that require going beyond the built-in components and standard approach. I will assume some familiarity with basic machine learning and data science terminology.</em></p><p>As machine learning has increasingly inundated the tech world, it’s been pretty much impossible to keep track of the growing set of tools, frameworks and platforms which all claim to be the next best thing. While those of us that have been “around” for a while might remember (more or less fondly) such frameworks as (the original) Torch, Caffe, Theano, etc… these days it will be hard to get by in the data science world without at least a passing knowledge of both <a href="https://www.tensorflow.org/">TensorFlow</a> and <a href="https://pytorch.org/">PyTorch</a>. That is not to say that the steady stream of new tools has slowed down, but it does seem that, at least for the time being, large ecosystems of tools have aggregated around these two frameworks.</p><p>While they are both excellent, TensorFlow (or TF for friends) has typically had a stronger following in the business world, while PyTorch seems to be more widely adopted by the academic community. If you don’t mind, I will keep a safe distance from the chicken-or-egg question of how and why that came to be. It is however fair to say that, at least until the “recent” major update of TensorFlow, PyTorch has been easier to experiment with, while TensorFlow has had much better support for bringing machine learning pipelines and models to production. Now, with TF 2.x and its wholehearted embrace of the “Keras way,” TF has become a delight (that is, if you are “that kind” of person) to experiment with. On the other hand, I think it’s still fair to say that the ecosystem around TF continues to be stronger and more unified when it comes to “productionising” machine learning compared to what the PyTorch world currently offers. This is in no small part due to the main character in this multipart story: TensorFlow Extended a.k.a TFX.</p><h3>TensorFlow Extended in context</h3><p>Calling TFX a “character” is perhaps a bit of an understatement: imagining a multi-headed Hydra will probably give you a better sense of what it can do for you. TFX is the continuation of a project at Google called <a href="https://blog.tensorflow.org/2020/09/brief-history-of-tensorflow-extended-tfx.html">Sibyl</a>, which grew from the realisation that coming up with ingenious machine learning models and writing slick loss-optimisation code is only a small part of what’s needed to put ML to effective use in the scary and chaotic wild west we tend to call reality.</p><p>What do you do if suddenly the distribution of the training data changes and retraining your model results in a dramatic drop in performance? Or worse, what if the distribution of the data your production model is making predictions on slowly drifts over time without anyone noticing? Even if you do notice, this means that you’ll (in the easiest scenario) need to adapt your features, and corresponding feature engineering, over time. How much of this can you automate? And what if you need to track and manage this for thousands of models simultaneously? Even if your model count in production is much lower than that, you will quickly realise that finding the right tools to help you with these challenges is more than just a luxury problem.</p><p>That’s where TFX comes in. It extends (as you might have guessed) TF with a suite of tools that help you deal with the (MLOps) challenges I just described. In order to understand its power, it’s useful to know a bit about how it works under the covers. Many of the TFX components require processing large amounts of data, preferably in a distributed way. Instead of reinventing the wheel, these components leverage another Google-developed powerhouse that excels in exactly this, <a href="https://beam.apache.org/">Apache Beam</a>. This will become very clear in an upcoming post in which we’ll write a custom component to ingest data into the pipeline. What we’ll end up creating will essentially be a thin wrapper around Beam code.</p><p>Another important aspect of TFX’s architecture is that, very much like Beam, it should be seen as a tool for authoring pipelines. To actually run TFX at scale requires a runner. You can, as is the case for Beam, run it locally during development. In fact, TFX’s local runner <em>is</em> essentially Beam’s local runner in that it leverages Beam both for running many of its components <em>and</em> for orchestrating the full pipeline. To run your pipeline at scale, you have three options:</p><ul><li><strong>Use a Beam runner:</strong> you can keep leveraging Beam for both processing and orchestration at scale by using a Beam runner such as Google Cloud’s <a href="https://cloud.google.com/dataflow">Dataflow</a>. This is the easiest option as it requires minimal extra setup and configuration to promote your local setup to one that runs at scale (similar to promoting a local Beam pipeline to a Dataflow pipeline). On the other hand, it will not be as fully-featured as the two options that follow.</li><li><strong>Use Apache Airflow:</strong> a lot of companies are already using <a href="https://airflow.apache.org/">Airflow</a> for orchestrating their data pipelines. If that’s the case, running your TFX pipelines on Airflow as well might be the path of least resistance. This is an excellent option and will offer more control than a Beam runner as far as the orchestration goes. Note that even in this case, the data processing that is part of many of the components will still be done by Beam, so it’s perhaps more appropriate to call this option Airflow + Beam, or, if you’re on Google Cloud Platform (GCP) for example, <a href="https://cloud.google.com/composer">Cloud Composer</a> + Dataflow.</li><li><strong>Use Kubeflow Pipelines:</strong> <a href="https://www.kubeflow.org/">Kubeflow</a> is an open source project that aims to make deployments of ML workloads on Kubernetes simpler. One of its sub-projects is <a href="https://www.kubeflow.org/docs/components/pipelines/">Kubeflow Pipelines</a>, which offers a UI, API and SDK that together enable authoring and orchestrating ML pipelines, running and comparing ML experiments, and artifact lineage tracking through a metadata store. This requires a bit more setup (although managing Airflow on Kubernetes is not that different), but offers the most fully-featured experience and richest UI for a data science team. Furthermore, on GCP you can also find a fully managed version as <a href="https://cloud.google.com/ai-platform/pipelines/docs">AI Platform Pipelines</a>.</li></ul><p>We will not focus on the runners in this series, although it is an essential part of the <a href="https://www.linkedin.com/pulse/ml-from-experiments-production-thomas-van-latum/">MLOps story</a>. In what follows, we will either use the local Beam runner or the “manual” Interactive runner that essentially turns your Jupyter notebook into an orchestrator with your fingertips as the triggers, very handy while developing pipelines or exploring metadata and artifacts.</p><h3>TFX components</h3><p>TFX comes in two flavours: a set of stand-alone Python libraries on one hand and a collection of components that can be used as building blocks for authoring DAGs (Directed Acyclic Graphs, welcome to Data Engineering) on the other. The components wrap some of the functionality from the stand-alone libraries with the specific purpose of building automated machine learning pipelines. We will focus on the component approach, although, as you’ll see, we will sometimes need to break through this abstraction layer and use some of the library features that are not exposed through the wrappers. In any case, we encourage you to dig into the libraries themselves as well, as they allow you to perform very in-depth analysis of your data, metadata and models in a more exploratory way.</p><p>We will get to know most of the components better as we progress through the subsequent posts, but it would be rude to not include the main ones at least briefly in this general round of introductions:</p><p><strong>Ingest and validate data:</strong> First, data needs to be ingested into the pipeline and ideally turned into a binary format that is optimised for further processing. This is done by the <em>ExampleGen</em> component (TensorFlow tends to call data points Examples), which typically turns external files into binary TFRecord files of protobuf messages. Subsequently, <em>StatisticsGen</em> extracts feature statistics from the data that are then used by <em>SchemaGen</em> to generate a schema for your data. This schema can be adapted to your needs, after which it is used by <em>ExampleValidator</em> to validate future data against. This allows you to automatically detect data drift or training-serving skew and act accordingly. If these terms don’t ring many bells, more on all of this in future posts. Note that <em>ExampleGen</em>, <em>StatisticsGen</em> and <em>ExampleValidator</em> use Beam under the hood.</p><p><strong>Transform data and train model:</strong> After the data has been validated, it needs to be transformed into the input shape required by the training loop. This can be much more elaborate than you might expect. The <em>Transform</em> component leverages Beam to first analyse the full training set (unless the required information already exists in the schema) and then uses the obtained statistics (such as mean or standard deviation) to transform the data (for example, impute missing values or normalise the data). To ensure that the same preprocessing steps are performed during serving/prediction, it then saves the transformation steps into a TF graph which can be saved along with the trained model. The transformed data is then fed into the <em>Trainer</em> component that finally runs that precious bit of code you thought was going to be 90% of the work. The <em>Trainer</em> can run distributed training on, for example, a Kubeflow cluster, or offload this job to a service such as Google’s <a href="https://cloud.google.com/ai-platform/training/docs">AI Platform Training</a>. The <em>Trainer</em> works hand in hand with the <em>Tuner</em>, the newest addition to the TFX family responsible for handling hyperparameter tuning.</p><p><strong>Evaluate and validate model:</strong> The Trainer spits out a SavedModel, but that should not be the end of your pipeline. What if the new model performs worse than the one that’s currently running in production? The <em>Evaluator</em> first evaluates the model on the test set, but then, more importantly, compares its performance against that of the latest “blessed model.” A blessed model is one that was previously deemed good enough by the <em>Evaluator</em> (or your-human-in-the-loop-self) to be representing your company in production. If the new model performs better than the previous blessed model (in ways that you have a lot of control over), it is tagged as the latest blessed model. The aptly named Pusher is then responsible for “pushing” any new blessed model to the right deployment target (ready to be served in the cloud, on the edge or in the browser, depending on your use case).</p><p>Finally, the (not so) secret glue that holds everything together is the ML Metadata (MLMD) library. This layer allows all the components to share metadata and artifacts (even though every component typically runs in its own container or service) and exposes a rich interface for lineage tracking and pipeline debugging. We will cross paths with it many times on our travels “along the pipeline.”</p><p>Note that this story did not include the actual serving of the model, but also there, TFX is your friend through the TensorFlow Serving library, but this should be seen as a separate application, not one of the components of the pipeline. You can alternatively use any other framework or service that can serve SavedModels, such as Google’s <a href="https://cloud.google.com/ai-platform/prediction/docs">AI Platform Prediction</a> service.</p><p>That’s it from me for now. I realise that we had a bit of an information density explosion going on there towards the end, but we’ll revisit a lot of this at a slower pace later on. Hopefully see you soon in the next post, where we’ll dive deeper into some of the components and how to wield them to your custom needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ecaf0827e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>