<?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 Hang Yu on Medium]]></title>
        <description><![CDATA[Stories by Hang Yu on Medium]]></description>
        <link>https://medium.com/@hangyu_5199?source=rss-2665192d75e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*90Kh75UPYO6k-69hmbvp7g.jpeg</url>
            <title>Stories by Hang Yu on Medium</title>
            <link>https://medium.com/@hangyu_5199?source=rss-2665192d75e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:43:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hangyu_5199/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[Unveiling the Secret of Semantic IDs]]></title>
            <link>https://medium.com/data-science-collective/unveiling-the-secret-of-semantic-ids-e144f806e090?source=rss-2665192d75e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e144f806e090</guid>
            <category><![CDATA[perturbation]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[synthetic-data-generation]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <dc:creator><![CDATA[Hang Yu]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 00:30:41 GMT</pubDate>
            <atom:updated>2025-10-02T19:57:48.411Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discover the explainability of RQ-VAE via perturbation testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VLYnkWGXzq9Ja4aM" /><figcaption>Photo by <a href="https://unsplash.com/@lunarts?utm_source=medium&amp;utm_medium=referral">Volodymyr Hryshchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>Recently, Google DeepMind demonstrated how Semantic IDs effectively improve the ranking of recommender systems in their <a href="https://dl.acm.org/doi/10.1145/3640457.3688190">RecSys paper</a>. In this context, Semantic IDs are the categorical codes generated by RQ-VAE, which hierarchically quantizes the residuals of the input embeddings into multi-level cluster codes, aiming to categorize the sample and benefit generalization. For instance, in the three-level RQ-VAE shown below, the input embedding is pushed through the quantizers, gets assigned to the closest cluster at each level, and the corresponding cluster codes or IDs become its Semantic IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*xHdFm20X0toJ7f9DsZbClw.png" /><figcaption>Figure 1: Visualized RQ-VAE architecture | Image by author</figcaption></figure><p>Besides increasing accuracy, especially in a cold-start scenario, Semantic IDs at different levels theoretically reveal a categorical hierarchy in which the information flows from coarse to granular across successive levels, providing a view into the internal structure of the inputs. For example, given a product description, the first level reflects the category “<em>Mobile Phone</em>”, while the later levels contain more detailed ones such as “<em>Memory Size</em>”, “<em>Battery Capacity</em>”, and so on.</p><p>In this article, I’ll share my journey exploring the explainability of Semantic IDs, especially the hierarchical structure, by observing how the RQ-VAE codes change in response to the perturbations of the input. All the code and results presented below can be found in this <a href="https://github.com/simon19891101/ML_experiments/blob/main/RQ_VAE.ipynb">notebook</a>.</p><h4>Methodology</h4><p>My objective is to understand the underlying mechanism that generates Semantic IDs for a given input. Here, I focus on text inputs. Ideally, this should be achieved by investigating the model parameters and analyzing the contribution of each word or word span when clustering happens at each level. However, this is extremely hard because the input corpus is projected into the embedding space, and the residuals cannot be recovered back to words.</p><p>To tackle this challenge, the model-agnostic perturbation testing is adopted. The basic idea is to modify the attributes of the input in a controlled manner and observe how the Semantic IDs vary at each level of the RQ-VAE in response to the perturbed input. In this way, we can infer how different positions in the hierarchy process information differently.</p><h4>Synthetic Data Generation via LLMs</h4><p>In order to make the perturbation method as effective as possible, we need to train and test the RQ-VAE on the text inputs that are clear and informative, allowing the model to easily capture the data structure and precisely respond to any attribute change. To this end, a no-brainer is to generate synthetic data using LLMs to maximize controllability.</p><p>For this experiment, LLMs are used to synthesize product descriptions in three product categories: <em>bottle, hat, </em>and<em> carpet</em>. First, a product category is randomly sampled. Then, for the selected category, I instruct LLMs to generate a product description covering five attributes: <em>product name, color, durability, size, </em>and<em> material</em>. Every generated product is presented as JSON with attributes as keys and corresponding text as values, which makes it easy to perturb later on.</p><p>The code used to create synthetic data is presented below. First, the chat completion function is defined with a temperature of 2 to maximize the synthesis diversity. Then, 100 samples are synthesized following the steps mentioned above, which will be used later to train and analyze the Semantic IDs.</p><pre>client = OpenAI(api_key=userdata.get(&#39;OPENAI_API_KEY&#39;))<br><br>def chat_completion_request(messages, tools=None, tool_choice=None, model=&quot;gpt-4o-mini&quot;):<br>    try:<br>        response = client.chat.completions.create(<br>            model=model,<br>            messages=messages,<br>            temperature=2,<br>            max_tokens=500,<br>            top_p=0.95,<br>            frequency_penalty=0,<br>            presence_penalty=0,<br>            n=1,<br>            response_format={&quot;type&quot;: &quot;json_object&quot;}<br>        )<br>        return response<br>    except Exception as e:<br>        print(&quot;Unable to generate ChatCompletion response&quot;)<br>        print(f&quot;Exception: {e}&quot;)<br>        return e<br><br><br>dummy_data = []<br><br>for i in range(100):<br><br>  random_product = str(np.random.choice([&#39;bottle&#39;, &#39;hat&#39;, &#39;carpet&#39;]))<br><br>  messages = []<br>  messages.append({&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are synthetic data generator that creates product descriptions.&quot;})<br>  messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Generate one product in this category: {random_product}&quot;})<br>  messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;The description covers product name, color, durability, size, and material.&quot;})<br>  messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Output is a json with keys including product_name, color, durability, size, material&quot;})<br>  response = chat_completion_request(messages)<br>  response_json = json.loads(response.choices[0].message.content)<br>  dummy_data.append(response_json)</pre><p>The final dataset contains 37, 33, and 30 unique samples for the <em>bottle</em>, <em>carpet</em>, and <em>hat</em> categories. Some synthetic examples are presented below to illustrate what the actual data look like.</p><pre>{<br>&#39;product_name&#39;: &#39;EcoSip Stainless Steel Bottle&#39;,<br>&#39;color&#39;: &#39;Matte Black&#39;,<br>&#39;durability&#39;: &#39;Shock and rust resistant&#39;,<br>&#39;size&#39;: &#39;20 oz (600 ml)&#39;,<br>&#39;material&#39;: &#39;High-quality stainless steel&#39;<br>}<br><br>{<br>&#39;product_name&#39;: &#39;Plush Velvet Area Rug&#39;,<br>&#39;color&#39;: &#39;Emerald Green&#39;,<br>&#39;durability&#39;: &#39;High-traffic areas resistant&#39;,<br>&#39;size&#39;: &quot;5&#39; x 7&#39;&quot;,<br>&#39;material&#39;: &#39;100% Polyester&#39;<br>}<br><br>{<br>&#39;product_name&#39;: &#39;Cozy Knitted Beanie&#39;,<br>&#39;color&#39;: &#39;Dark Gray&#39;,<br>&#39;durability&#39;: &#39;Weather-resistant and long-lasting&#39;,<br>&#39;size&#39;: &#39;One size fits most&#39;,<br>&#39;material&#39;: &#39;100% Soft Acrylic Yarn&#39;<br>}</pre><h4>Implement and Train RQ-VAE</h4><p>Now we have the data, let’s implement the RQ-VAE. The code below provides an example of defining the model using Keras and TensorFlow, but you can also attempt other implementations.</p><pre># ---------------------------<br># Residual Quantizer Layer<br># ---------------------------<br>class ResidualQuantizer(layers.Layer):<br>    &quot;&quot;&quot;<br>    Residual vector quantizer (RQ) for (batch, dim) inputs.<br>    Args:<br>      num_quantizers: number of residual quantizers (stages)<br>      codebook_size: entries per codebook<br>      dim: latent dimensionality<br>      commitment_cost: weight for commitment loss<br>    Returns:<br>      quantized: tensor same shape as inputs<br>      loss: dictionary with &#39;codebook_loss&#39; and &#39;commitment_loss&#39;<br>      indices_list: list of argmin indices for each quantizer stage (for retrieval)<br>    &quot;&quot;&quot;<br>    def __init__(self,<br>                 num_quantizers: int,<br>                 codebook_size: int,<br>                 dim: int,<br>                 commitment_cost: float = 0.25,<br>                 **kwargs):<br>        super().__init__(**kwargs)<br>        self.num_q = int(num_quantizers)<br>        self.K = int(codebook_size)<br>        self.dim = int(dim)<br>        self.beta = float(commitment_cost)<br><br>        # Create codebooks as trainable variables: shape (num_q, K, dim)<br>        # Use initializer close to 0, small std.<br>        init = tf.random_normal_initializer(stddev=0.02)<br>        self.codebooks = [<br>            self.add_weight(<br>                name=f&#39;codebook_{i}&#39;,<br>                shape=(self.K, self.dim),<br>                initializer=init,<br>                trainable=True,<br>                dtype=tf.float32<br>            )<br>            for i in range(self.num_q)<br>        ]<br><br>    def call(self, inputs, training=None):<br>        # inputs: (batch, dim)<br>        x = tf.convert_to_tensor(inputs, dtype=tf.float32)<br>        batch = tf.shape(x)[0]<br><br>        residual = x  # residual to quantize<br>        quantized_total = tf.zeros_like(x)<br>        codebook_loss = 0.0<br>        commitment_loss = 0.0<br>        indices_list = []<br><br>        for i in range(self.num_q):<br>            cb = self.codebooks[i]            # (K, dim)<br>            # compute squared distances: (batch, K)<br>            # expand dims for broadcasting<br>            # dist = ||residual - cb_k||^2 = ||residual||^2 + ||cb_k||^2 - 2*residual·cb_k<br>            r2 = tf.reduce_sum(tf.square(residual), axis=1, keepdims=True)  # (B,1)<br>            cb2 = tf.reduce_sum(tf.square(cb), axis=1)  # (K,)<br>            # compute dot product<br>            dot = tf.matmul(residual, cb, transpose_b=True)  # (B, K)<br>            # distances<br>            distances = r2 + tf.reshape(cb2, (1, -1)) - 2.0 * dot  # (B, K)<br><br>            # find argmin<br>            indices = tf.argmin(distances, axis=1)  # (B,)<br>            indices_list.append(indices)<br><br>            # one-hot<br>            one_hot = tf.one_hot(indices, depth=self.K, dtype=tf.float32)  # (B,K)<br>            # quantized vectors: (B, dim) = one_hot @ cb<br>            quantized = tf.matmul(one_hot, cb)  # (B, dim)<br><br>            # accumulate quantized output and update residual<br>            quantized_total += quantized<br>            residual = residual - quantized  # new residual for next stage<br><br>            # losses for this stage:<br>            # codebook loss (move codebook towards encoder outputs): ||sg(residual_before) - q||^2<br>            # commitment loss (encourage encoder outputs to commit to codebook): ||res_before - sg(q)||^2<br>            # For codebook loss we use stop_gradient on residual_before so gradients go to cb only.<br>            # For commitment loss we use stop_gradient on quantized so gradients go to encoder only.<br>            # Note: residual_before = x - summed_previous_quantized. For easier bookkeeping,<br>            # compute residual_before_stage = residual + quantized (since residual already updated).<br>            residual_before = residual + quantized  # (B, dim)<br><br>            codebook_loss += tf.reduce_mean(tf.square(tf.stop_gradient(residual_before) - quantized))<br>            commitment_loss += tf.reduce_mean(tf.square(residual_before - tf.stop_gradient(quantized)))<br><br>        # Straight-through estimator: allow gradients to encoder, but treat quantized_total as discrete in backward path<br>        # z_q = x + stop_grad(quantized_total - x)<br>        z_q = x + tf.stop_gradient(quantized_total - x)<br><br>        losses = {<br>            &quot;codebook_loss&quot;: codebook_loss,<br>            &quot;commitment_loss&quot;: commitment_loss * self.beta<br>        }<br><br>        return z_q, losses, indices_list<br><br># ---------------------------<br># RQEmbeddingVAE (Encoder, Quantizer, Decoder)<br># ---------------------------<br>class RQEmbeddingVAE(keras.Model):<br>    def __init__(self,<br>                 embedding_dim: int,<br>                 latent_dim: int,<br>                 num_quantizers: int = 2,<br>                 codebook_size: int = 512,<br>                 commitment_cost: float = 0.25,<br>                 **kwargs):<br>        super().__init__(**kwargs)<br>        self.embedding_dim = embedding_dim<br>        self.latent_dim = latent_dim<br><br>        # Encoder: project embedding_dim -&gt; latent_dim<br>        self.encoder = keras.Sequential([<br>            layers.InputLayer(input_shape=(embedding_dim,)),<br>            layers.Dense(latent_dim, activation=&#39;relu&#39;)<br>        ])<br><br>        # Residual Quantizer<br>        self.quantizer = ResidualQuantizer(num_quantizers=num_quantizers,<br>                                           codebook_size=codebook_size,<br>                                           dim=latent_dim,<br>                                           commitment_cost=commitment_cost)<br><br>        # Decoder: latent_dim -&gt; embedding_dim<br>        self.decoder = keras.Sequential([<br>            layers.InputLayer(input_shape=(latent_dim,)),<br>            layers.Dense(embedding_dim)<br>        ])<br><br>        # track metrics<br>        self.recon_loss_tracker = keras.metrics.Mean(name=&quot;recon_loss&quot;)<br>        self.codebook_loss_tracker = keras.metrics.Mean(name=&quot;codebook_loss&quot;)<br>        self.commitment_loss_tracker = keras.metrics.Mean(name=&quot;commitment_loss&quot;)<br>        self.total_loss_tracker = keras.metrics.Mean(name=&quot;loss&quot;)<br><br>    def call(self, inputs, training=False):<br>        z_e = self.encoder(inputs)                # (B, latent_dim)<br>        z_q, losses, indices = self.quantizer(z_e, training=training)  # quantized latent<br>        recon = self.decoder(z_q)                 # reconstruct embedding<br>        return recon, z_e, z_q, losses, indices<br><br>    @property<br>    def metrics(self):<br>        return [self.recon_loss_tracker,<br>                self.codebook_loss_tracker,<br>                self.commitment_loss_tracker,<br>                self.total_loss_tracker]<br><br>    def train_step(self, data):<br>        # data is either (x,) or x<br>        if isinstance(data, tuple) or isinstance(data, list):<br>            x = data[0]<br>        else:<br>            x = data<br><br>        with tf.GradientTape() as tape:<br>            recon, z_e, z_q, losses, indices = self.call(x, training=True)<br>            recon_loss = tf.reduce_mean(tf.reduce_sum(tf.square(recon - x), axis=1))  # MSE per sample then mean<br>            codebook_loss = losses[&quot;codebook_loss&quot;]<br>            commitment_loss = losses[&quot;commitment_loss&quot;]<br><br>            total_loss = recon_loss + codebook_loss + commitment_loss<br><br>        # compute grads and apply<br>        grads = tape.gradient(total_loss, self.trainable_variables)<br>        self.optimizer.apply_gradients(zip(grads, self.trainable_variables))<br><br>        # update metrics<br>        self.recon_loss_tracker.update_state(recon_loss)<br>        self.codebook_loss_tracker.update_state(codebook_loss)<br>        self.commitment_loss_tracker.update_state(commitment_loss)<br>        self.total_loss_tracker.update_state(total_loss)<br><br>        return {<br>            &quot;loss&quot;: self.total_loss_tracker.result(),<br>            &quot;recon_loss&quot;: self.recon_loss_tracker.result(),<br>            &quot;codebook_loss&quot;: self.codebook_loss_tracker.result(),<br>            &quot;commitment_loss&quot;: self.commitment_loss_tracker.result()<br>        }<br><br>    def encode(self, inputs):<br>        z_e = self.encoder(inputs)<br>        _, _, indices = self.quantizer(z_e, training=False)<br>        return indices  # list of per-stage index tensors<br><br>    def decode_from_indices(self, indices_list):<br>        # build quantized vector from codebook indices (use first codebook as example)<br>        # This helper reconstructs the quantized latent given indices_list<br>        batch = tf.shape(indices_list[0])[0]<br>        quantized_total = tf.zeros((batch, self.latent_dim), dtype=tf.float32)<br>        for i, idx in enumerate(indices_list):<br>            cb = self.quantizer.codebooks[i]  # (K, dim)<br>            one_hot = tf.one_hot(idx, depth=self.quantizer.K, dtype=tf.float32)<br>            quantized = tf.matmul(one_hot, cb)<br>            quantized_total += quantized<br><br>        return self.decoder(quantized_total)</pre><p>Next, before training the RQ-VAE, the synthetic data needs to be converted into text embeddings. This is done by first concatenating all attributes into one single string, for example, <em>“EcoSip Stainless Steel Bottle,Matte Black,Shock and rust resistant,20 oz (600 ml),High-quality stainless steel”, </em>and vectorizing the string using a pre-trained embedding model.</p><pre>dummy_data_str = dummy_data[&#39;product_name&#39;]+&#39;,&#39;+dummy_data[&#39;color&#39;]+&#39;,&#39;+dummy_data[&#39;durability&#39;]+&#39;,&#39;+dummy_data[&#39;size&#39;]+&#39;,&#39;+dummy_data[&#39;material&#39;]<br><br>from sentence_transformers import SentenceTransformer<br>emb_model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br>embeddings = emb_model.encode(dummy_data_str, show_progress_bar=True)</pre><p>Finally, we can build the RQ-VAE and train it using the input embeddings! To make training and analysis efficient, the model is defined to have 3 levels of quantizers and 10 unique codes per level, which is simple yet sufficient considering the size of the synthetic dataset.</p><pre>K.clear_session()<br><br>embedding_dim = embeddings.shape[1]<br>latent_dim = 32<br><br>ds = tf.data.Dataset.from_tensor_slices(embeddings).shuffle(2048).batch(64)<br><br>model = RQEmbeddingVAE(<br>    embedding_dim=embedding_dim,<br>    latent_dim=latent_dim,<br>    num_quantizers=3,<br>    codebook_size=10,<br>    commitment_cost=0.25<br>)<br><br>model.compile(optimizer=keras.optimizers.Adam(1e-3))<br><br>model.fit(ds, epochs=200)</pre><h4>Perturbation Testing</h4><p>After creating the synthetic data and training the RQ-VAE, we are ready to perturb the data points and observe how Semantic IDs vary in response to the perturbation.</p><p>For every synthesized product description, one or more of its attributes, including product name, color, durability, size, and material, are perturbed by replacing the original value with a random sample from all the unique values of the corresponding attributes. Looking at the diversity of each attribute, there are 86 unique product names, 42 unique colors, 96 unique durabilities, 60 unique sizes, and 83 unique materials, providing a rich space for perturbation.</p><p>Next, the perturbed product description gets vectorized using the same pre-trained model as before, and the resulting embeddings are passed into the RQ-VAE to generate the new codes.</p><p>Lastly, the codes before and after perturbation are compared to identify which quantizer levels have code change for the given attributes.</p><p>For example, the effect of perturbing <em>color</em> is illustrated below, showing that it is captured at level 3:</p><blockquote><strong><em>Original product</em></strong><em>: “</em>EcoSip Stainless Steel Bottle,<strong>Matte Black</strong>,Shock and rust resistant,20 oz (600 ml),High-quality stainless steel<em>”</em></blockquote><blockquote><strong><em>Original Semantic IDs</em></strong><em>: [3, 5, 5]</em></blockquote><blockquote><strong><em>Perturbed product</em></strong><em>: “</em>EcoSip Stainless Steel Bottle,<strong>Emerald Green</strong>,Shock and rust resistant,20 oz (600 ml),High-quality stainless steel<em>”</em></blockquote><blockquote><strong><em>Perturbed Semantic IDs</em></strong><em>: [3, 5, 7]</em></blockquote><blockquote><strong><em>Levels with code change</em></strong><em>: [3]</em></blockquote><p>To comprehensively assess the impact, the experiment examines perturbations across all possible combinations of 1 to 5 attributes. For every selection of attributes, 5 random perturbations are performed for every synthetic product, generating 500 test results to analyze the code change.</p><p>The code below provides a reference to implement the overall process of perturbation testing.</p><pre>def get_perturb_result(perturb_columns, dummy_data=dummy_data, emb_model=emb_model, model=model, perturb_dict=perturb_dict, N_perturb = 5):<br><br>  perturb_result = {}<br><br>  for perturb_col in perturb_columns:<br><br>    key = &#39;+&#39;.join(perturb_col)<br>    print(f&#39;Purterbation: {key}&#39;)<br><br>    vae_code_change = []<br><br>    for ix in range(len(dummy_data)):<br><br>      dummy_input = dummy_data.drop(columns=[&#39;category&#39;]).iloc[ix].copy()<br>      dummy_input_str = &#39;,&#39;.join(dummy_input.values)<br>      dummy_embedding = emb_model.encode(dummy_input_str).reshape(1,-1)<br>      dummy_codes = np.array([i.numpy()[0] for i in model.encode(dummy_embedding)])<br><br>      for i in range(N_perturb):<br>        perturb_field = []<br>        mod_input_str = dummy_input_str<br>        for j in range(len(perturb_col)):<br>          mod_field = dummy_input[perturb_col[j]]<br>          perturb_field = np.random.choice(perturb_dict[perturb_col[j]])<br>          mod_input_str = mod_input_str.replace(mod_field, perturb_field)<br><br>        mod_embedding = emb_model.encode(mod_input_str).reshape(1,-1)<br>        mod_codes = np.array([i.numpy()[0] for i in model.encode(mod_embedding)])<br>        diff_codes = np.where(dummy_codes != mod_codes)[0]<br>        diff_codes += 1<br>        vae_code_change.append(diff_codes)<br><br>    perturb_result.update({key: vae_code_change})<br><br>  return perturb_result</pre><h4>Results Analysis</h4><p>To analyze how Semantic IDs relate to different attributes, I reported the percentage of code changes observed at each quantizer level when a given attribute is perturbed. For instance, “<em>perturbing color might change 20% of the codes at level 1, 50% at level 2, and 60% at level 3</em>”. It’s worth noting that the total percentage of code change across 3 levels does not necessarily sum up to 100% because multiple levels might change simultaneously for one perturbation.</p><p>Now let’s dive into the analysis. The results of perturbing 1 to 5 attributes are visualized in Figures 2 to 6 shown below. There are two major takeaways I’d like to highlight:</p><ol><li>Perturbing detail-related attributes, like <em>color</em>, <em>durability</em>, <em>size</em>, and <em>material</em>, mostly affects the Semantic IDs at level 2 and level 3, while barely impacting level 1. This observation is extremely significant as it explicitly demonstrates the potential hierarchical nature of Semantic IDs: details are more likely to be treated as residuals and captured by the later stages of the quantizers.</li><li>Any perturbation involving <em>product name</em> almost equally changes the Semantic IDs across all levels of the RQ-VAE. Looking at the data, many product names actually contain both coarse concepts and granular details, like <em>EcoSip Stainless Steel Bottle, </em>which presents the category as well as the actual material. Considering that perturbing details almost only impacts levels 2 and 3, we can infer that the code change at level 1 is mostly attributed to perturbing the categorical information in product names. In other words, coarse information is likely contained at the early stage of the quantizers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*GnjaZCMG4GuMmDU-sFcThg.png" /><figcaption>Figure 2: perturbing 1 attribute | Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*5GhWLweWFQeDF4WzIIW1RQ.png" /><figcaption>Figure 3: perturbing 2 attributes | Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*KLVEg_cUYXZwEeUEDfswLg.png" /><figcaption>Figure 4: perturbing 3 attributes | Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*2HaNqwW87f-Exagx_MqKoA.png" /><figcaption>Figure 5: perturbing 4 attributes | Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*S-wBYlRG9oTxrdbI4du2ug.png" /><figcaption>Figure 6: perturbing 5 attributes | Image by author</figcaption></figure><h4>Final Takeaways</h4><p>In this article, I demonstrated how perturbation testing and synthetic data generation can be leveraged to explore the hierarchical behavior of Semantic IDs. This analysis could open new use cases, such as providing data-driven guidance to improve taxonomy design for the business. I look forward to your feedback and learning about other approaches to enhance explainability. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e144f806e090" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/unveiling-the-secret-of-semantic-ids-e144f806e090">Unveiling the Secret of Semantic IDs</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s Happening to Embeddings During Training?]]></title>
            <link>https://medium.com/data-science-collective/whats-happening-to-embeddings-during-training-338c420705e5?source=rss-2665192d75e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/338c420705e5</guid>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Hang Yu]]></dc:creator>
            <pubDate>Tue, 06 May 2025 04:00:15 GMT</pubDate>
            <atom:updated>2025-05-06T04:00:15.065Z</atom:updated>
            <content:encoded><![CDATA[<p>A study on the spatial dynamics under different training strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jCCKbDAqS3_24j3V" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>As data scientists and machine learning engineers, many have used embeddings explicitly or implicitly to conduct predictive modeling or descriptive analysis in our day-to-day work. In most cases, we care about how embeddings could make the model more accurate for a task, but rarely take a closer look to understand the underlying process that generates those numbers. In this article, I’ll share some preliminary insights to discover what actually happens to embeddings by looking at how different training strategies impact their spatial characteristics.</p><p>The results are reproducible using <a href="https://github.com/simon19891101/ML_experiments/blob/main/embedding_eval.ipynb">this notebook</a>.</p><h4>What Are Embeddings?</h4><p>In simple terms, embeddings are numerical representations that carry certain topological information about the entities in the data. One example is the word embeddings that encode the semantic similarity among words. In practice, embeddings are multidimensional vectors composed of decimal numbers that are randomly initialized and incrementally shaped while the model is being trained.</p><p>Now the question is, how is the embedding space created during training?</p><h4>Characterize the Spatial Properties</h4><p>To start the study, we first need some indicators or metrics that characterize the spatial properties of embeddings. Among the limited literature, the following measures were selected:</p><ul><li><a href="https://en.wikipedia.org/wiki/Gini_coefficient?"><strong>Gini Index</strong></a>: Measures inequality of values, i.e., if the information in the vector is concentrated in a few dimensions.</li><li><a href="https://en.wikipedia.org/wiki/Entropy_%28information_theory%29?"><strong>Vector Entropy</strong></a>: Measures distributional uncertainty that reveals how uniformly the embedding uses its dimensions.</li><li><a href="https://www.jmlr.org/papers/volume5/hoyer04a/hoyer04a.pdf"><strong>Hoyer Sparsity</strong></a>: Measures how many dimensions are effectively utilized.</li><li><a href="https://journals.aps.org/prx/abstract/10.1103/PhysRevX.6.041062"><strong>Spectral Entropy</strong></a>: Gives a frequency-domain view that reflects how smooth or noisy the embedding is.</li></ul><p>Their Python implementation used in this work is presented below.</p><pre>import numpy as np<br><br>def gini(x):<br>    &quot;&quot;&quot;Compute the Gini coefficient of a vector.&quot;&quot;&quot;<br>    x = np.abs(x.flatten()) + 1e-12  # Avoid division by zero<br>    x_sorted = np.sort(x)<br>    n = len(x)<br>    cumulative = np.cumsum(x_sorted)<br>    gini_coeff = (n + 1 - 2 * np.sum(cumulative) / cumulative[-1]) / n<br>    return gini_coeff<br><br>def vector_entropy(x):<br>    &quot;&quot;&quot;Compute entropy of normalized absolute vector components.&quot;&quot;&quot;<br>    x = np.abs(x.flatten()) + 1e-12<br>    p = x / np.sum(x)<br>    return -np.sum(p * np.log(p))<br><br>def hoyer_sparsity(x):<br>    &quot;&quot;&quot;Compute Hoyer&#39;s sparsity measure of a vector.&quot;&quot;&quot;<br>    x = np.abs(x.flatten())<br>    n = len(x)<br>    l1 = np.sum(x)<br>    l2 = np.sqrt(np.sum(x ** 2))<br>    if l1 == 0:<br>        return 0.0<br>    return (np.sqrt(n) - (l1 / l2)) / (np.sqrt(n) - 1)<br><br>def spectral_entropy(E):<br>    &quot;&quot;&quot;Compute spectral entropy from an embedding matrix E (rows = vectors).&quot;&quot;&quot;<br>    # Compute covariance matrix<br>    cov = np.cov(E, rowvar=False)<br>    # Compute eigenvalues<br>    eigvals = np.linalg.eigvalsh(cov)<br>    eigvals = np.clip(eigvals, a_min=1e-12, a_max=None)  # avoid log(0)<br>    p = eigvals / np.sum(eigvals)<br>    return -np.sum(p * np.log(p))</pre><h4>Peek into the Embedding Space During Training</h4><p>Now that we have defined our embedding measurements. It’s time to see how they evolve over time during training. We are going to do a simple deep learning experiment: building a matrix factorization model on the MovieLens dataset and monitoring the change in embedding space.</p><p><strong>Data Collection and Processing</strong></p><p>First, the dataset was downloaded, processed, and split into training and test sets following an 80/20 ratio.</p><pre># Load the MovieLens 1M dataset (only &#39;train&#39; split is available)<br>ratings = tfds.load(&#39;movielens/100k-ratings&#39;, split=&#39;train&#39;)<br><br># Convert the dataset to a Pandas DataFrame<br>ratings_df = tfds.as_dataframe(ratings)<br><br># Preprocess the DataFrame: Convert bytes to strings and then to integers<br>ratings_df[&#39;movie_id&#39;] = ratings_df[&#39;movie_id&#39;].str.decode(&#39;utf-8&#39;).astype(np.int64)<br>ratings_df[&#39;user_id&#39;] = ratings_df[&#39;user_id&#39;].str.decode(&#39;utf-8&#39;).astype(np.int64)<br><br># Create LabelEncoders and fit on the DataFrame<br>user_encoder = LabelEncoder()<br>movie_encoder = LabelEncoder()<br><br>user_encoder.fit(ratings_df[&#39;user_id&#39;])<br>movie_encoder.fit(ratings_df[&#39;movie_id&#39;])<br><br># Transform the IDs in the DataFrame<br>ratings_df[&#39;user_id_encoded&#39;] = user_encoder.transform(ratings_df[&#39;user_id&#39;])<br>ratings_df[&#39;movie_id_encoded&#39;] = movie_encoder.transform(ratings_df[&#39;movie_id&#39;])<br>ratings_df[&#39;label&#39;] = ratings_df[&#39;user_rating&#39;].apply(lambda x: 1 if x &gt;= 4 else 0)<br><br># Split the DataFrame into train and test sets<br>train_df, test_df = train_test_split(ratings_df, test_size=0.2, random_state=42)</pre><p><strong>Model Creation</strong></p><p>Next, the model was created. It’s a simple matrix factorization that defines a user’s movie preference as the dot product between the user and item embeddings.</p><pre>def build_model(emb_dim=16, optimizer=&#39;adam&#39;):<br>  tf.keras.backend.clear_session()<br><br>  # Define the embedding dimensions<br>  user_embedding_dim = emb_dim<br>  movie_embedding_dim = emb_dim<br><br>  # Create the user embedding layer<br>  user_embedding_layer = tf.keras.layers.Embedding(<br>      input_dim=num_users,<br>      output_dim=user_embedding_dim,<br>      name=&#39;user_embedding_layer&#39;<br>  )<br><br>  # Create the movie embedding layer<br>  movie_embedding_layer = tf.keras.layers.Embedding(<br>      input_dim=num_movies,<br>      output_dim=movie_embedding_dim,<br>      name=&#39;movie_embedding_layer&#39;<br>  )<br><br>  # Define the model<br>  input_user_id = tf.keras.Input(shape=(1,), dtype=tf.int64)<br>  input_movie_id = tf.keras.Input(shape=(1,), dtype=tf.int64)<br><br>  user_embedding = user_embedding_layer(input_user_id)<br>  movie_embedding = movie_embedding_layer(input_movie_id)<br><br>  # Concatenate the embeddings<br>  concatenated_embeddings = tf.keras.layers.Concatenate()([user_embedding, movie_embedding])<br><br>  # Add a dense layer for prediction<br>  output = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(concatenated_embeddings)<br>  output = tf.keras.layers.Reshape((1,))(output)<br><br>  # Create the model<br>  model = tf.keras.Model(inputs=[input_user_id, input_movie_id], outputs=output)<br><br>  # Compile the model<br>  model.compile(optimizer=optimizer, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br>  return model</pre><p><strong>Experiment Setup</strong></p><p>To understand the dynamics of embeddings, I monitored how embedding measurements fluctuate over 20 epochs when the model is trained with different optimizers and batch sizes. To make the comparison representative, I selected two fundamentally different optimizers: Stochastic Gradient Descent (SGD) and Adam. SGD is a straightforward optimizer known for its strong generalization capabilities, whereas Adam is a more sophisticated technique that achieves rapid convergence through adaptive learning rates. Additionally, I examined various batch sizes, ranging from 1 to 32, to assess their impact on training dynamics and embedding representations.</p><ul><li><strong>Optimizers</strong>: SGD, Adam</li><li><strong>Batch sizes</strong>: 1, 8, 16, 32</li><li><strong>Metrics</strong>: training loss, test loss, Gini index, Hoyer sparsity, vector entropy, spectral entropy.</li><li><strong>Number of epochs</strong>: 20</li><li><strong>Dimensions of embeddings</strong>: 8</li></ul><pre>emb_dim = 8<br>num_epochs = 20<br><br>for optimizer in [&#39;adam&#39;, &#39;sgd&#39;]:<br>  for batch_size in [1, 8, 16, 32]:<br>    model = build_model(emb_dim=emb_dim, optimizer=optimizer)<br>    for epoch in range(num_epochs):<br>        print(optimizer, batch_size, epoch)<br>        history = model.fit(X_train, y_train, epochs=1, batch_size=batch_size, verbose=0)<br>        user_embeddings = model.get_layer(&#39;user_embedding_layer&#39;).get_weights()[0]<br>        movie_embeddings = model.get_layer(&#39;movie_embedding_layer&#39;).get_weights()[0]<br><br>        embeddings = np.concatenate([user_embeddings, movie_embeddings])<br><br>        # Evaluate the model<br>        test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)<br>        gini_score = round(float(np.mean(list(map(gini, embeddings)))),4)<br>        hoyer_sparsity_score = round(float(np.mean(list(map(hoyer_sparsity, embeddings)))),4)<br>        vector_entropy_score = round(float(np.mean(list(map(vector_entropy, embeddings)))),4)<br>        spectral_entropy_score = round(float(spectral_entropy(embeddings)),4)</pre><p><strong>Results and Discussions</strong></p><p>Figures 1 and 2 present how embeddings evolve for the SGD and Adam optimizers, respectively. In each figure, the rows represent the losses and embedding metrics over 20 epochs for a given batch size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*2fVYoQKp7wJFPdfQVWVp7g.png" /><figcaption>Figure 1: Experiment results for SGD optimizer | Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*Fwv_z_3o6682k7AgEfjYwA.png" /><figcaption>Figure 2: Experiment results for Adam optimizer | Image by author</figcaption></figure><p>After eyeballing these results comparatively, there are some key takeaways to share:</p><ul><li><strong>Gini Index and Hoyer Sparsity</strong>. Generally, the embeddings created by SGD exhibited an increased trend for Gini index and Hoyer sparsity. This is likely due to the stochastic nature that made the training noisy and failed to equalize the utilization of different dimensions of embeddings. In comparison, Adam showed the opposite thanks to its momentum term that stabilizes the gradient and fairly updates every dimension over time.</li><li><strong>Vector Entropy and Spectral Entropy.</strong> For both SGD and Adam, vector entropy tended to be inversely correlated with the Gini index and sparsity during training. This is expected because vector entropy and Gini index intrinsically point in opposite directions. What is interesting is, spectral entropy always decreased over epochs regardless of the optimizer and batch size, indicating that any training strategy eventually converges towards a more structured variation pattern across dimensions and achieves concentration in the spectrum.</li><li><strong>Special case: batch size of 1</strong>. As we see, the Gini index and Hoyer sparsity are quite different when the batch size equals 1 for both SGD and Adam. For SGD, the extremely noisy update caused the Gini index to decrease over time, which motivates a deeper exploration of the impact of batch size. Looking at Adam, the first few epochs showed the same trend as SGD with a batch size of 1, however, it quickly evolved to SGD with larger batch sizes, suggesting the potential correlation between these two optimizers.</li></ul><h4>Final Thoughts</h4><p>This study is a preliminary work to explore the dynamics of embeddings during training under different approaches.</p><p>At this stage, many aspects are not fully understood and could have a better theoretical interpretation. I look forward to initiating a broader exploration and discussion around this topic to better understand the underlying mechanism driving the observed results.</p><p>Your feedback and ideas are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=338c420705e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/whats-happening-to-embeddings-during-training-338c420705e5">What’s Happening to Embeddings During Training?</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommender Systems: From Theory to Production]]></title>
            <link>https://pub.towardsai.net/recommender-systems-from-theory-to-production-0f92bd85dcff?source=rss-2665192d75e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f92bd85dcff</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[literature-review]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Hang Yu]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 22:02:17 GMT</pubDate>
            <atom:updated>2024-11-30T22:02:17.576Z</atom:updated>
            <content:encoded><![CDATA[<h4>The guide you need to master every step of the journey.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N5sjCm5KwimmO0GW" /><figcaption>Photo by <a href="https://unsplash.com/@declansun?utm_source=medium&amp;utm_medium=referral">Declan Sun</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Driven by the rapid growth of web content and usage in the last decade, recommender systems (RS) have become one of the most eye-catching domains that rapidly embrace new technologies to achieve advancements. Both industry and academia are motivated to drive the evolution of this technique considering its significant impact on customer engagement. In this article, I’d like to provide a holistic review of RS that includes the theory and the practical experience summarised from real-world R&amp;D.</p><p><em>Despite my own experience, this article is highly motivated and inspired by the </em><a href="https://book.douban.com/subject/36701755/"><em>book</em></a><em> authored by </em><a href="https://zhuanlan.zhihu.com/p/676156556"><em>Chuanlin Zhao</em></a><em>.</em></p><h3>Overview</h3><p>From traditional websites to mobile Apps, the rise of RS is essentially driven by the growth of web content and usage. The exploded information and increasingly frequent user interactions imply great opportunities for business uplift. To achieve this goal, RS are introduced to proactively discover the content that matches users’ potential interests in a timely manner. Briefly, RS find the top candidate items that maximise the likelihood of engagement as the recommendations for every user.</p><p>The technical evolution of RS has been driven by the challenges emerging from the large volume and high diversity of user traffic. From logistic regression to transformer, from batch prediction to real-time inference, and from one single model to the multiple-stage architecture, RS nowadays have evolved into end-to-end systems that require multidisciplinary collaboration including data science, machine learning, data engineering, software engineering, UX design, business analysis, etc.</p><p>In the following sections, we will go through some key aspects including data, modelling, evaluation, practical challenges, and how Large Language Models (LLMs) are leveraged to enhance RS.</p><h3>Feature Engineering</h3><p>Fundamentally, RS aim to train one or more models to predict the matching scores between users and items. As the first step, we need to represent users and items as features that can be effectively and efficiently consumed by the training and inference process. Now, let’s understand how those features are extracted, processed, and stored in the system.</p><h4>Feature Extraction</h4><p>For a platform with mature data collection and tracking, there could exist many options to build features for users and items. Where shall we start? The good news is that there are certain types of generic features recommended as the first thing to consider. Based on how frequently the information changes, we have static and dynamic features.</p><p><strong>Static features</strong></p><ul><li><strong>User features: </strong>user ID and demographics like age, gender, occupation, location, tenure, etc. The user ID is an important categorical feature that could carry strong predictive power when we have rich interaction data between users and items. For demographics, it’s recommended to carefully consider the potential ethical and privacy policy when using these features.</li><li><strong>Item features: </strong>there are a wide range of attributes, like item ID, title, description, category, image, price, brand, specifications, labels, seller information, etc.</li></ul><p><strong>Dynamic features</strong></p><ul><li><strong>User features:</strong> the most important signal is the historical interactions like clicks. We can also utilise the aggregated statistics of interactions, cohort interest, characteristics of the interacted items, session context, etc.</li><li><strong>Item features: </strong>seller statistics like ratings, the historical statistics of interactions including reviews, ratings, click-through-rate (CTR), conversions, search, etc. Besides, we can optionally introduce debiasing factors like the position of impression to reduce the noise.</li></ul><p>It’s worth noting that these features should be adjusted to accommodate the specific domain. For instance, the average watch time of the videos shall be additionally considered for streaming platforms.</p><h4>Feature Processing</h4><p>After extracting the features, we need to appropriately process them to be consumed by the downstream model. Processing the features for RS is not much different from other tasks and there are some recommended approaches.</p><p><strong>Numeric features</strong></p><ul><li><strong>Imputation.</strong> In practice, we unavoidably have to fill up the missing values in the dataset. The simplest way is mean/median imputation. Being more advanced, we can train a model to predict missing values. Alternatively, missing values can be simply represented as a dedicated categorical class, such as “unknown”, when the numerical feature is grouped into buckets.</li><li><strong>Standardisation.</strong> For features with different scales, we usually need to transform their values into the same level to maximise the predictive power. There exist many choices but it’s highly recommended to check the statistical assumptions of each option. For example, z-score standardisation assumes the normal distribution, which requires log-norm transformation if the data doesn’t naturally meet the expectation.</li><li><strong>De-biasing. </strong>We need to minimise the bias contained in some of the features. For instance, item CTR usually suffers from small sample bias and position bias. The sample bias can be mitigated using the <a href="https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval">lower bound of Wilson score interval</a> whereas position bias is usually addressed using <a href="https://dl.acm.org/doi/10.1145/1718487.1718531">Clicks Over Expected Clicks (CoEC) </a>.</li><li><strong>Binning.</strong> In practice, it is popular to adopt categorical features for RS to model the non-linear relationship and make computation efficient. Thus, numerical features are usually discretised using different binning approaches including equal-width binning, frequency-width binning, and entropy-based binning.</li></ul><p><strong>Categorical features</strong></p><ul><li><strong>Embedding. </strong>The most popular approach to process categorical features is to represent them as embeddings to maximise the information capacity and granularity. Embeddings are trainable vectors that learn the latent meaning of categorical fields during training. For example, “dumpling” as an item gets implicitly associated with tags like “food”, “Asian”, “festival”, etc. in the vector space by learning from the user-item interactions without the need to explicitly attach these attributes. In this continuous space, we can have an extended ability of discovery beyond the exact match when finding similar entities. Typically, the categorical fields are mapped to the corresponding embeddings via either a one-to-one mapping table or a Hashing table depending on the size of the data.</li><li><strong>Feature crossing. </strong>It is widely adopted to combine<strong> </strong>different categorical features as new ones to increase predictive power. For example, a new categorical feature created based on “has historical returns” and “high seller rating” will explicitly capture the user’s attention to post-conversion service.</li></ul><h4>Data Architecture</h4><p>Depending on the traffic pattern and latency requirement, different RS normally demand different data systems to store, process, and transfer the features. A platform with low user activity might only need an offline data system that updates the features a couple of times each day in batches whereas one with frequent user interactions would definitely benefit from the high-performance real-time architecture. Amongst all, the most technically sound option is the lambda architecture that combines real-time and batch processing to achieve both recency and scalability. A typical Lambda architecture for RS includes <a href="https://netflixtechblog.com/system-architectures-for-personalization-and-recommendation-e081aa94b5d8">three layers</a>:</p><p><strong>Offline layer</strong></p><p>The offline layer aims to provide offline processing for large-scale data. For instance, computing the three-month historical CTR for every item. This is usually done in batch mode using distributed systems like HDFS so there is unavoidable latency. Besides the processing delay, the data exhibits natural latency as it takes time for the online logs to land in the offline system.</p><p><strong>Nearline layer</strong></p><p>To alleviate the I/O bottleneck, the features processed by the offline layer are then saved in the in-memory database, namely the nearline layer, for quick read and write.</p><p><strong>Online layer</strong></p><p>The most recent data is mostly missed by the offline/nearline layers, however, they are extremely important for capturing the latest user interest. Thus, we have the online layer to prepare the features based on the real-time logs using streaming technology.</p><h3>Multi-stage Modelling</h3><p>Like every other machine learning system, the models of RS also face the dilemma that we can’t maximise capability and scalability at the same time. A model with millions of parameters will offer advanced predictive power but inevitably tradeoff latency whereas a lightweight model is the opposite. As a solution, in practice, the multi-stage architecture is widely adopted to balance the tradeoff and optimise the overall performance. In detail, the system is divided into a funnel composed of <strong>retrieval</strong>, <strong>pre-ranking</strong>, <strong>ranking</strong>, and <strong>re-ranking</strong> stage. At each stage, the predictive power is gradually prioritised over scalability by adopting finer models and features to process fewer candidates. For instance, given a user, the retrieval stage roughly selects 1,000 relevant items from the overall product base and the ranking stage then picks the top 100 best options from those as the recommendations.</p><p>Next, let’s understand each step from the perspectives of the model and data.</p><h4>Retrieval stage</h4><p>Retrieval, recall, or candidate generation, is the first stage of a multi-stage RS. The task is to efficiently select a set of items from the overall product catalog for the downstream models so it literally determines the lower bound of the system accuracy. Typically, retrieval algorithms include traditional multi-channel retrieval and modern embedding-based retrieval.</p><p><strong>Multi-channel retrieval</strong></p><p>The multi-channel retrieval aims to combine the items generated by different sources including but not limited to:</p><ul><li><strong>Popular items </strong>that have high popularity on the platform.</li><li><strong>Categories of interest </strong>that explore<strong> </strong>the products with topics or categories preferred by the customers based on historical interest.</li><li><strong>Collaborative filtering </strong>that discovers<strong> </strong>the products based on the historical user-item interactions. This is usually implemented either via classic collaborative filtering or matrix factorisation.</li></ul><p>Later on, different channels interleave together to generate the top-K candidates. This approach is computationally efficient and highly flexible to manually adjust how different source channels are combined. For example, we can easily add a promotion channel and increase its visibility by prioritising this source. However, the quality of retrieval is likely compromised due to the limitation of such heuristics.</p><p><strong>Embedding-based retrieval</strong></p><p>Alternatively, embedding-based retrieval is a good option if higher predictive power is needed. The basic idea is to project users and items into the same embedding space and retrieve similar candidates. Depending on the use case, the retrieval could be 1) user-to-item (U2I) that finds a user’s preferred items; 2) item-to-item (I2I) that finds similar items for an item; and 3) user-to-user (U2U) that finds similar users for a user, etc. There are some popular retrieval models:</p><ul><li><a href="https://towardsdatascience.com/complete-guide-to-understanding-node2vec-algorithm-4e9a35e5d147"><strong>Item2Vec</strong></a><strong> </strong>that is one of the most representative I2I retrieval models inspired by Word2Vec. In Item2Vec, the sequence of item IDs in the same user session is treated as one sentence and each item ID is treated as a word. Then, the same training process as Word2Vec is adopted to create item embeddings that model the in-session similarity.</li><li><a href="https://towardsdatascience.com/factorization-machines-for-item-recommendation-with-implicit-feedback-data-5655a7c749db"><strong>Factorisation Machine (FM)</strong></a><strong> </strong>that is<strong> </strong>a popular U2I retrieval model supporting high dimensional features. The basic idea is to model the user-item interaction by learning the feature-to-feature correlation. After training, user and item embeddings can be extracted and used for similarity search.</li><li><a href="https://towardsdatascience.com/two-tower-networks-and-negative-sampling-in-recommender-systems-fdc88411601b"><strong>Two tower</strong></a>,<strong> </strong>which is<strong> </strong>known for<strong> </strong>its versatility and flexibility accommodating all the retrieval modes. As the name implies, the model is composed of two decoupled branches and aims to model the correlation of these two sides based on the rich input features. Once trained, the embedding layers will be used to extract embeddings for retrieval.</li><li><a href="https://towardsdatascience.com/an-intuitive-explanation-of-graphsage-6df9437ee64f"><strong>GraphSage</strong></a><strong>, </strong>an<strong> </strong>inductive Graph Convolutional Network that represents each entity based on the aggregated neighbour representation. Compared with other options, graph models are intuitively superior for obtaining an extended view of the relationships in the topology.</li></ul><p>Then, we will use the embeddings created by the retrieval model to find similar candidates. Depending on the adoption of dynamic features, we may need to generate embeddings on the fly or periodically. For example, generate user embeddings in real-time if historical interactions are used as a user feature whereas keep item embeddings updated regularly. Given the vast number of candidates at the retrieval stage, conducting similarity search in the embedding space could be fairly challenging in terms of performance. To solve this problem, the <a href="https://towardsdatascience.com/using-approximate-nearest-neighbor-search-in-real-world-applications-a75c351445d">Approximated Nearest Neighbour (ANN)</a> is usually recommended to quickly retrieve similar candidates without compromising much precision. It’s important to ensure that the same similarity metric, such as cosine similarity, is shared by both the ANN and the retrieval model to achieve consistency.</p><p>Embedding retrieval models have some best practices regarding training data creation and processing as discussed below.</p><ul><li><strong>Feature engineering</strong> should avoid user-item feature crossing. Decoupling user and item features will allow us to efficiently pre-compute the embeddings of each side and quickly calculate the relevance scores via similarity search.</li><li><strong>Labelling and loss </strong>should consider how the retrieval model is applied in practice.<strong> </strong>The most common way to create labels is treating interacted entities, like user-item interactions for U2I and in-session items for I2I retrieval, as the positive samples whereas randomly sampling from all other items to be the negative samples. This is to make training aligned with serving because the retrieval stage needs to select relevant items from the total product base for a user in the online environment. In practice, the in-batch negative sampling is recommended if the product base contains a large number of items. Correspondingly, the sampled softmax loss is applied to each positive sample with its negative samples. Here, softmax loss is preferred because it’s only supervised by the positive label, which fits the training data wherein only the positive signal is from user interactions whereas the negative one is approximated via the global random sampling.</li></ul><h4>Pre-ranking stage</h4><p>Depending on the size of the retrieval output, we can optionally build a pre-ranking stage to further distill the retrieved candidates before calling the sophisticated ranking model. Compared with the retrieval models, the pre-ranking stage has some similarities and differences.</p><p><strong>Models</strong></p><p>The two tower is a popular choice while FM and ranking model distillation are also widely adopted. Like the retrieval stage, we usually calculate product embeddings offline whereas generate user embeddings on the fly to reflect the change of interest. However, due to the largely reduced candidate set, the exact similarity search rather than ANN becomes applicable. Correspondingly, the similarity calculation is no longer limited and can be done by more complex options like a DNN that takes the two-tower embeddings as inputs.</p><p><strong>Labelling and loss</strong></p><p>Similar to retrieval, the actual user-item interactions are treated as positive samples. Nonetheless, the negative samples are now based on the unclicked impressions because the pre-ranking and ranking stage share the same objective that is learning the exact user interest.</p><p>In the real-world scenario, we need to be careful about two types of bias during data creation:</p><ul><li><strong>Sampling bias</strong>. The vanilla negative sampling actually only includes the hard negative samples that are the shortlisted candidates from the ranking model, which could be hugely misaligned with the retrieval output. To make the pre-ranking smoothly bridge retrieval and ranking, it’s recommended to additionally include some low-ranking samples from the ranking output to create a weak negative signal.</li><li><strong>Position bias.</strong> This means the unclicked impressions at lower positions could actually contain positive signals but are sampled to be negative. This happens quite often in practice when users are converted and no longer interact with other related items. One solution is only using the negative samples displayed above the positive interactions to increase confidence.</li></ul><p>In terms of the loss function, correspondingly, now the binary entropy loss is preferred as both the positive and negative samples reflect the true preference.</p><h4>Ranking stage</h4><p>Compared with other steps, ranking is the most eye-catching component that attracts significant attention from both academia and industry. Unlike the retrieval stage that decides the performance baseline, ranking largely influences the upper bound because the objective is to prioritise user’s strong preferences over the normal ones rather than distinguishing between likes and dislikes. Tackling such a challenging task needs advanced predictive power from the sophisticated model and features.</p><p><strong>Models</strong></p><p>The ranking models can be classified into two categories:</p><ul><li><strong>Feature-crossing models </strong>which<strong> </strong>focus on learning the correlation among features so as to memorise the known pattern and generalise to the new one. Typical examples include the classic FM and the deep learning models like <a href="https://arxiv.org/abs/1606.07792">wide&amp;deep</a>, <a href="https://arxiv.org/abs/1703.04247">DeepFM</a>, <a href="https://www.tensorflow.org/recommenders/examples/dcn">DCN</a>, and <a href="https://arxiv.org/abs/1810.11921">AutoInt</a>. The evolution demonstrates two important directions: 1) the increased order of feature combinations and 2) the reduced dependency on manually designed feature combinations. Obviously, the complexity and capability of these models are sufficiently high to maximise the utilization of big training data and modern compute resource.</li><li><strong>Sequential models </strong>that<strong> </strong>capture the upcoming interest using users’ interaction sequences. Basically, the previously interacted items of customers are used as the input sequence to predict the next item in the line. In practice, every element in the sequence is usually the ID embedding concatenated with features like the recency of the interaction and product attributes. The sequential models include naive approaches like embedding pooling, sophisticated solutions like the <a href="https://arxiv.org/abs/1706.06978">Deep Interest Network</a> that adopts attention mechanism to enable dynamic representations, and <a href="https://arxiv.org/abs/2006.05639">Search-based Interest Model</a> that explores the value of both short interest and long interest.</li></ul><p>Unlike retrieval whereby we extract and store embeddings, most of the ranking models are deployed online to dynamically calculate the relevance scores on the fly. This highly likely imposes computational pressure due to the algorithmic complexity. Thus, optimising the system design is essential to achieve the expected performance.</p><p><strong>Labelling and loss</strong></p><p>Data creation for ranking stage is as same as pre-ranking. Positive samples are the actual interactions whereas negative samples are constructed using unclicked impressions. Similarly, the sigmoid activation with binary cross entropy loss is adopted because:</p><ul><li>Ranking focuses on the absolute positive/negative accuracy.</li><li>The probability output presents the CTR that benefits interpretability and business-oriented optimisation task e.g. maximising the expected revenue.</li></ul><h4>Re-ranking stage</h4><p>The above-mentioned steps all aim to maximise one objective: the point-wise relevance between every product and user. However, this doesn’t necessarily optimise the final experience because the users are actually presented with a list of items and its quality is crucial. For example, the ranking output likely contains similar items positioned next to each other due to the similar matching scores, which results in poor diversity that harms conversion. To solve this problem, re-ranking is introduced. Briefly, it treats the recommendation list as a whole, explores the contextual relationship among individual elements, and maximises the list-wise user interaction.</p><p>There are three popular re-ranking mechanisms:</p><ul><li><strong>Heuristics </strong>that<strong> </strong>use pre-defined rules to improve the diversity in specific aspects like category, price, etc. For example, applying a sliding window to the ranking output and swapping the duplicated categories for the next out-of-window candidate with a different category. A more advanced option could be using a function that balances relevance and diversity to add every candidate one by one to the re-ranked list .</li><li><strong>Determinantal point process (DPP) </strong>that is<strong> </strong>a statistical approach to model the probability of drawing a certain subset from a given set. DPP naturally fits the re-ranking task because re-ranking essentially aims to pick the optimal sublist from the full list returned by ranking. In practice, <a href="https://arxiv.org/abs/2004.06390">re-ranking DPP</a> is usually configured to generate the optimum that balances relevance and diversity.</li><li><strong>Contextual re-ranking </strong>that trains<strong> </strong>a specific re-ranking model based on the historical data. The most typical solution is the Context-aware Learning-to-Rank. Compared with previous stages, such re-ranking models take the full list as one input sample and consider the contextual features like the relative ranks at ranking stage. One example is the <a href="https://dl.acm.org/doi/10.1145/3298689.3347000">Personalised Re-ranking Model</a>.</li></ul><h3>Special Challenges</h3><p>The above-mentioned methodology is sufficient to satisfy most of the real-world requirements for building a proper RS, however, there are some additional challenges to be addressed to further optimise the solution. Next, I’ll focus on cold start problem and multi-task/multi-scenario modelling.</p><h4><strong>Cold start problem</strong></h4><p>The most famous challenge in the world of RS is the cold start problem. In practice, it’s not uncommon that some users or items have few or even no interactions. As a result, the corresponding data points are sparse and it’s extremely challenging to learn high-quality embeddings from such information.</p><p>The R&amp;D to tackle this issue has achieved substantial outcomes. Some popular methods include:</p><ul><li><strong>Simple heuristics</strong> e.g. representing individuals by the groups and conducting group-level recommendations.</li><li><strong>Content-based filtering and hybrid model</strong> that leverages the attributes of users and items.</li><li><strong>Bandit algorithms</strong> that quickly collect feedback signals.</li><li><strong>Meta learning</strong> that optimises the initial embeddings to achieve fast training convergence.</li><li><strong>Contrastive learning</strong> that maximally squeezes the existing information via data argumentation in a self-supervised fashion.</li><li><strong>Transfer learning</strong> that leverages the pre-trained embeddings to initialise the training for cold entities.</li></ul><h4>Multi-task learning</h4><p>In most cases, modelling CTR using clicks is the most popular task to build a RS. However, driven by the real-world demand, multi-task learning that jointly models multiple objectives simultaneously has also been explored. For example, we might want to recommend products that maximise CTR while minimising the time-to-sell, which needs the model to learn two tasks at the same time. Learning such multiple tasks would benefit the diversity of recommendations to comprehensively capture the interests of customers.</p><p>There are two reasons why it’s recommended to train one model with multiple tasks rather than individual task-wise models:</p><ul><li>It’s cheaper to have one model considering the cost of training and maintenance.</li><li>We hope to make the knowledge transferred across multiple tasks to benefit the ones that suffer from data sparsity.</li></ul><p>It’s worth noting that ultimately we need to combine multiple objectives as one final score for ranking purpose. Typically, this is done by assigning weights to individual tasks and associating them. In practice, such weights are usually decided iteratively via online experiments either in a human-in-the-loop manner or fully automated like hyper-parameter tuning.</p><h4>Multi-scenario learning</h4><p>In practice, it’s likely that the business expects to deploy the existing RS to a new scenario like a new region or language. Similar to multi-task learning, training a new model faces the challenge of cost and data sparsity. Therefore, multi-scenario learning is introduced to share knowledge across scenarios. A good representative is <a href="https://arxiv.org/pdf/2303.06095">HiNet</a>. There are some best practices to make the modelling process reliable and effective:</p><ul><li>The input features should contain scenario indicators like region and language and such indicators should be separately fed to the final output to avoid information loss during propagation.</li><li>The model architecture should contain a shared bottom and independent scenario-specific modules like the mixture of experts to balance the knowledge transfer and isolation.</li></ul><h3>Evaluation</h3><p>It is extremely important to measure the performance of the RS before the production launch. Like every other production-level machine learning tasks, the evaluation for RS also includes the offline and online stages with their corresponding objectives and metrics.</p><h4>Offline Evaluation</h4><p>The purpose of offline evaluation is to measure if the model is fitted correctly. This is achieved by checking if the model effectively learns from the training data and generalises to the test data for certain accuracy metrics in comparison with a baseline. The popular offline metrics include two classes:</p><ul><li><strong>Ranking metrics</strong> like AUC, Group-wise AUC, NDCG. Those metrics are designed to measure the orders or positions of the results against the ideal status.</li><li><strong>Retrieval metrics</strong> like precision, recall, PR-AUC, and Hit Ratio that measures the presence of true positives despite the ranks.</li></ul><p>It’s worth noting that compared with classification metrics that focus on positives, the ranking metrics, which are more sensitive to subtle noise, demand high confidence for both positives and negatives to ensure reliability. Hence, for the retrieval stage, only the classification metrics are recommended because the negative signal is approximated by sampling from the total base.</p><h4>Online Evaluation</h4><p>Online evaluation aims to assess how much the RS impacts the key business metrics like click-through rate in real life. In an ideal world, this is achieved by comparing the user group that uses the RS and the counterfactual viz. the same group if this RS had not been applied. However, the counterfactual never exists in the real world so we use two alternatives to approximate: hypothesis testing and causal inference.</p><p>Hypothesis testing, or A/B experiment, is the first choice for quantifying the business impact. Briefly, we randomly split users into a control group receiving the baseline and a treatment group receiving the new RS. Here, the control group serves as the counterfactual. Then, we can attribute any post-experiment difference in the business metric between the two groups to the RS. There are some best practices to maximise statistical power:</p><ul><li>Check if the experiment is configured with the correct sample size using <a href="https://www.evanmiller.org/ab-testing/">statistical tools</a>.</li><li>Prior to A/B experiment, conduct A/A experiment to detect any pre-existing differences and increase the group size to achieve equality if necessary.</li></ul><p>Sometimes, it might not be feasible to conduct A/B experiment due to operational limitations. In this case, <a href="https://medium.com/towards-data-science/towards-reliable-synthetic-control-156106a1a7cb">causal inference</a> is the recommended alternative that doesn’t need the equally split groups.</p><h4>Offline-online Discrepancy</h4><p>For RS evaluation, it is not uncommon to observe the discrepancy between offline and online experiments. For instance, the offline AUC is increased by 10% but no CTR uplift is observed. There are a couple of reasons:</p><ul><li><strong>Representation gap</strong>. The offline test data and metrics fail to comprehensively represent the real-world online environment. For example, the new model amplifies the effect of festival events in the test data but the online experiment is only across regular days.</li><li><strong>Feature time travel</strong>. In detail, the future states of features are leaked to the training data but online prediction is based on the historical features. This is a common mistake when the model aims to predict the future label using historical statistics.</li><li><strong>Old soup effect</strong>. Sometimes, the existing control variant running online has experienced many iterations of incremental training, like a pot of old soup, but its offline version is only trained using the pre-selected training data. This implies that the online control has much more sophisticated and comprehensive knowledge than its offline equivalent. As a result, the new model might win the offline game but lose the online comparison. One approach to achieve an unbiased online experiment is to let the new model undergo several incremental updates before the comparison starts.</li><li><strong>System inconsistency</strong>. During online experiments, it is possible that the upstream and downstream modules are not correctly configured to support the new model, especially when they are independently managed by different business units. Consequently, the treatment effect is discounted.</li></ul><h3>In the era of LLMs</h3><p>Recently, the research and development of RS have quickly embraced Large Language Models (LLMs) to leverage its embedded knowledge and reasoning capability. There are some popular ways to build LLM-based RS:</p><ul><li><strong>Building RS via the LLMs prompt</strong>. Typical examples are the <a href="https://arxiv.org/abs/2305.08845">Zero-shot Ranker</a>, <a href="https://arxiv.org/html/2407.17115v1">Reinforced Prompt Personalisation</a>, and <a href="https://www.researchgate.net/publication/369557235_Chat-REC_Towards_Interactive_and_Explainable_LLMs-Augmented_Recommender_System">ChatRec</a>. They more or less just simply leverage the prompt interface to let LLMs process the injected context to generate recommendations based on its embedded knowledge.</li><li><strong>Leveraging LLMs embeddings and fine-tuning</strong>. This approach aims to leverage the advanced model architecture of LLMs to fit the local user-item interactions either by extracting embeddings or fine-tuning the LLMs. Typical examples include <a href="https://arxiv.org/abs/2403.01744">NoteLLM</a>, <a href="https://arxiv.org/abs/2409.12740">HLLM</a>, and <a href="https://arxiv.org/abs/2310.15950">RLMRec</a>.</li><li><strong>Data augmentation via LLMs</strong>. The rich internal knowledge of LLMs can be leveraged to generate new information to enrich the local dataset. There are two representatives: <a href="https://arxiv.org/pdf/2310.15950">RLMRec</a> that creates user-item profiling and <a href="https://arxiv.org/pdf/2402.11724">LLMs data augmenter</a> that generates samples for cold-start items.</li></ul><h3>Conclusions</h3><p>Building a recommender system is always an exciting journey combining both challenges and opportunities. The knowledge shared in this article is just a foundation to begin with. Beyond these technical insights, what’s more important is understanding the business problem, knowing the real demand of customers, and tailoring the methodology to address the unique requirements of each specific task. Reaching these goals definitely needs a product mindset, user empathy, and expansive thinking. I hope my writing is helpful and would love to hear your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f92bd85dcff" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/recommender-systems-from-theory-to-production-0f92bd85dcff">Recommender Systems: From Theory to Production</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards Reliable Synthetic Control]]></title>
            <link>https://medium.com/data-science/towards-reliable-synthetic-control-156106a1a7cb?source=rss-2665192d75e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/156106a1a7cb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[campaign-measurement]]></category>
            <category><![CDATA[synthetic-control]]></category>
            <dc:creator><![CDATA[Hang Yu]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 06:14:25 GMT</pubDate>
            <atom:updated>2024-04-16T06:14:25.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making the estimated treatment effect close to the truth</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cjzgSOfcgLh4aS0f" /><figcaption>Photo by <a href="https://unsplash.com/@jhaland?utm_source=medium&amp;utm_medium=referral">Jørgen Håland</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>In recent years, the Synthetic Control (SC) approach has gained increasing adoption in industry for measuring the the Average Treatment Effect (ATE) of interventions when Randomized Control Trials (RCTs) are not available. One such example is measuring the financial impact of outdoor advertisements on billboards whereby we cannot conduct random treatment assignment in practice.</p><p>The basic idea of SC is to estimate ATE by comparing the treatment group against the predicted counterfactual. However, applying SC in practice is usually challenged by the limited knowledge of its validity due to the absence of the true counterfactual in the real world. To mitigate the concern, in this article, I would like to discuss the actionable best practices that help to maximise the reliability of the SC estimation.</p><p>The insights and conclusions are obtained through experiments based on diverse synthetic data. The code for data generation, causal inference modeling, and analysis is available in the Jupyter notebook hosted on <a href="https://github.com/simon19891101/ML_experiments/blob/main/sc_reliability.ipynb">Github</a>.</p><h4>Synthetic Control in a Nutshell</h4><p>The key to measure the ATE of such events is to identify the counterfactual of the treatment group, which is the treatment group in the absence of the treatment, and quantify the post-treatment difference between the two. It is simple for RCTs as the randomised control statistically approximates the counterfactual. However, it’s challenging otherwise due to the unequal pre-experiment statistics between the treatment and control.</p><p>As a causal inference technique, SC represents the counterfactual by a synthetic control group created based on some untreated control units. This synthetic control group statistically equals the treatment group pre treatment and is expected to approximate the untreated behaviour of the treatment group post treatment. Mathematically presented below, it is created using the function <em>f</em> whose parameters are obtained by minimising the pre-treatment difference between the treated group and the control synthesised by <em>f </em>[1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*jbq-R6qdOY_uSybA" /><figcaption>In the experiment, there are J groups whereby group 1 is the treatment group and others are controls. Each group has its observed outcome at time t denoted by Yjt. f is the model and Y1t^N refers to the counterfactual. Image by author.</figcaption></figure><p>In practice, the popular options for the function <em>f </em>include but are not limited to<em> </em>the<em> </em>weighted sum [1], Bayesian Structural Time Series (BSTS) [2], etc.</p><h4>Actions towards Reliable Synthetic Control</h4><p>Despite the solid theoretical foundation, applying SC in practice usually faces the challenge that we don’t know how accurate the estimated ATE is because there exists no post-treatment counterfactual in reality to validate the synthesised one. However, there are some actions we can take to optimise the modeling process and maximise the reliability. Next, I will describe these actions and demonstrate how they influence the estimated ATE via a range of experiments based on the synthetic time-series data with diverse temporal characteristics.</p><p><strong>Experiment Setup</strong></p><p>All the experiments presented in this article are based on synthetic time-series data. These data are generated using the <em>timeseries-generator</em> package that produces time series capturing the real-world factors including GDP, holidays, weekends, and so on.</p><p><a href="https://github.com/Nike-Inc/timeseries-generator/tree/master">GitHub - Nike-Inc/timeseries-generator: A library to generate synthetic time series data by easy-to-use factors and generator</a></p><p>The data generation aims to simulate the campaign performance of the stores in New Zealand from 01/01/2019 to 31/12/2019. To make the potential conclusions statistically significant, 500 time series are generated to represent the stores. Each time series has the statistically randomised linear trend, white noise, store factor, holiday factor, weekday factor, and seasonality. A random sample of 10 stores are presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxf_dqEb3U8beKgahQza6A.png" /><figcaption>Randomly sampled synthetic time series for 10 stores in New Zealand. Image by author.</figcaption></figure><p>Store1 is selected to be the treatment group whereas others play the role of control groups. Next, the outcome of store1 is uplifted by 20% from 2019-09-01 onwards to simulate the treated behaviour whereas its original outcome serves as the real counterfactual. This 20% uplift establishes the actual ATE to validate the actions later on.</p><pre>cutoff_date_sc = &#39;2019-09-01&#39;<br>df_sc.loc[cutoff_date_sc:] = df_sc.loc[cutoff_date_sc:]*1.2</pre><p>The figure below visualises the simulated treatment effect and the true counterfactual of the treatment group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*IexTm89DztpI3pnIIqT1ew.png" /><figcaption>The simulated ATE of +20% and the true counterfactual of store1. Image by author.</figcaption></figure><p>Given the synthetic data, the BSTS in Causalimpact is adopted to estimate the synthesised ATE. Then, the estimation is compared against the actual ATE using Mean Absolute Percentage Error (MAPE) to evaluate the corresponding action.</p><p><a href="https://github.com/jamalsenouci/causalimpact/tree/master">GitHub - jamalsenouci/causalimpact: Python port of CausalImpact R library</a></p><p>Next, let’s go through the actions along with the related experiments to see how to produce reliable ATE estimation.</p><p><strong>Treatment-control Correlation</strong></p><p>The first action to achieve reliable ATE estimation is selecting the control groups that exhibit high pre-treatment correlations with the treatment group. The rationale is that a highly correlated control is likely to consistently resemble the untreated treatment group over time.</p><p>To validate this hypothesis, let’s evaluate the ATE estimation produced using every single control with its full data since 01/01/2019 to understand the impact of correlation. Firstly, the correlation coefficients between the treatment group (store1) and the control groups (store2 to 499) are calculated [3].</p><pre>def correlation(x, y):<br>    shortest = min(x.shape[0], y.shape[0])<br>    return np.corrcoef(x.iloc[:shortest].values, y.iloc[:shortest].values)[0, 1]</pre><p>As shown in the figure below, the distribution of the correlations range from -0.1 to 0.9, which provides a comprehensive understanding about the impact across various scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*zuP4LlHyVMCL12ZsCeg0qw.png" /><figcaption>Distribution of the pre-treatment correlation. Image by author.</figcaption></figure><p>Then, every individual control is used to predict the counterfactual, estimate the ATE, and report the MAPE. In the figure below, the averaged MAPE of ATE with its 95% confidence interval is plotted against the corresponding pre-treatment correlation. Here, the correlation coefficients are rounded to one decimal place to facilitate aggregation and improve the statistical significance in the analysis. Looking at the results, it is obvious that the estimation shows a higher reliability when the control gets more correlated with the treatment group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*1XkPFXT-0hkCll8c94VR3w.png" /><figcaption>The MAPE of ATE for different correlation levels. Image by author.</figcaption></figure><p>Now let’s see some examples that demonstrate the impact of pre-treatment correlation: store88 with a correlation of 0.88 delivers a MAPE of 0.12 that is superior to 0.62 given by store3 with a correlation of 0.43. Besides the promising accuracy, the probabilistic intervals are correspondingly narrow, which implies high prediction certainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*myWb-vCI67b2Sf35s8LlOQ.png" /><figcaption>Example to demonstrate the impact of correlation. Image by author.</figcaption></figure><p><strong>Model Fitting Window</strong></p><p>Next, the fitting window, which is the length of the pre-treatment interval used for fitting the model, needs to be properly configured. This is because too much context could result in a loss of recency while insufficient context might lead to overfitting.</p><p>To understand how fitting window impacts the accuracy of ATE estimation, a wide range of values from 1 month to 8 months before the treatment date are experimented. For each fitting window, every single unit of the 499 control groups is evaluated individually and then aggregated to calculate the averaged MAPE with the 95% confidence interval. As depicted in the figure below, there exists a sweet spot nearby 2 and 3 months that optimise the reliability. Identifying the optimal point is outside the scope of this discussion but it’s worth noting that the training window needs to be carefully selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*l4oPLAk1eMOH6jtjFfiTGw.png" /><figcaption>The MAPE of ATE for different training windows. Image by author.</figcaption></figure><p>The figure shows two examples: the MAPE of control group 199 is reduced from 0.89 to 0.68 when its fitting window is increased from 1 month to 3 months because the short window contains insufficient knowledge to produce the counterfactual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*AnmpXi5fCa3RdiG38elHfw.png" /><figcaption>Example to demonstrate the impact of training window. Image by author.</figcaption></figure><p><strong>Number of Control Units</strong></p><p>Lastly, the number of the selected control groups matters.</p><p>This hypothesis is validated by investigating the estimation accuracy for different numbers of controls ranging from 1 to 10. In detail, for each control count, the averaged MAPE is calculated based on the estimations produced by 50 random control sets with each containing the corresponding number of control groups. This operation avoids unnecessarily enumerating every possible combination of controls while statistically controls for correlation. In addition, the fitting window is set to 3 months for every estimation.</p><p>Looking at the results below, increasing the number of controls is overall leading towards a more reliable ATE estimation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*r_BN6BYLZ5hOnPT3lD8Q1g.png" /><figcaption>The MAPE of ATE for different number of controls. Image by author.</figcaption></figure><p>The examples below demonstrate the effect. The first estimation is generated using store311 whereas the second one further adds store301 and store312.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*lM8T8rRwvT2fEGB4ReQGdA.png" /><figcaption>Example to demonstrate the impact of number of controls. Image by author.</figcaption></figure><h4>Conclusions</h4><p>In this article, I discussed the possible actions that make the SC estimation more reliable. Based on the experiments with diverse synthetic data, the pre-treatment correlation, fitting window, and number of control units are identified as compelling directions to optimise the estimation. Finding the optimal value for each action is out of the scope of this discussion. However, if you feel interested, parameter search using an isolated blank period for validation [4] is one possible solution.</p><p><em>All the images are produced by the author unless otherwise noted. The discussions are inspired by the great work “Synthetic controls in action” [1].</em></p><h4>References</h4><p>[1] Abadie, Alberto, and Jaume Vives-i-Bastida. “Synthetic controls in action.” <em>arXiv preprint arXiv:2203.06279</em> (2022).</p><p>[2]Brodersen, Kay H., et al. “Inferring causal impact using Bayesian structural time-series models.” (2015): 247–274.</p><p>[3]https://medium.com/@dreamferus/how-to-synchronize-time-series-using-cross-correlation-in-python-4c1fd5668c7a</p><p>[4]Abadie, Alberto, and Jinglong Zhao. “Synthetic controls for experimental design.” <em>arXiv preprint arXiv:2108.02196</em> (2021).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156106a1a7cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/towards-reliable-synthetic-control-156106a1a7cb">Towards Reliable Synthetic Control</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LLMs to Build Explainable Recommender Systems]]></title>
            <link>https://pub.towardsai.net/using-llms-to-build-explainable-recommender-systems-e0b44365a46d?source=rss-2665192d75e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0b44365a46d</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <dc:creator><![CDATA[Hang Yu]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 12:30:22 GMT</pubDate>
            <atom:updated>2024-01-12T12:30:54.699Z</atom:updated>
            <content:encoded><![CDATA[<h4>LLMs can go beyond the traditional recommender systems by generating recommendations with explanations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p-AE0aRnL0lPyGXM" /><figcaption>Photo by <a href="https://unsplash.com/@seanbenesh?utm_source=medium&amp;utm_medium=referral">Sean Benesh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In recent days, there’s no doubt that LLMs have become the most eye-catching superhero in the spotlight. While this powerful technique has raised a range of ethical concerns, there are more benefits and value being explored to either enhance the existing use cases or discover new opportunities. In this blog, I’ll demonstrate how LLMs can be used to improve recommender systems in two ways at the same time:</p><ol><li>Increase the predictive power. This is achieved by ranking the candidates generated by the upstream model.</li><li>Provide explainability. Leveraging the rich knowledge compressed, each recommendation will have a context-based explanation. This will largely benefit use cases that need to interpret model behaviors.</li></ol><p>For the sake of clarity, only the most essential code is displayed in this article. However, this experiment can be reproduced and extended based on the <a href="https://github.com/simon19891101/ML_experiments/blob/main/llm_recs_clean.ipynb">code hosted on Github</a>.</p><h3>Recommender system</h3><p>First, let’s recap what a personalized recommender system looks like from an architectural perspective. As depicted below, it’s generally a multi-stage funnel whereby each stage has a decreased number of candidate items with an increased relevance. It consists of two essential stages, which are recall (or matching) and ranking [1]. For a target person, the recall stage retrieves the top items that are potentially of interest from a wide range of channels, including interactions, promotions, etc., and those candidates are then ordered by the ranking stage to prioritize the best ones. The ranking stage is usually a model trained based on the fine-grained user and item knowledge.</p><p>In modern days, the funnel can optionally have modules like the pre-ranking and re-ranking stages before and after ranking, respectively, to accommodate large candidate sets, high model complexity, and business-specific rules based on the needs of platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*srLM-6XIfzO8aUdYMg1W2Q.png" /><figcaption>A multi-stage recommender system | Image by author</figcaption></figure><h3>LLM-based recommender system</h3><p>This work mainly focuses on <strong>applying LLM in the ranking stage</strong> because of the following reasons:</p><ol><li>LLMs’ rich external knowledge, which is complementary to the original dataset, would better identify the relative relationships among items.</li><li>LLMs are limited by the token lengths. The ranking stage has a smaller number of candidates to be processed, so it would mitigate the impact of the token limitation.</li></ol><p>Briefly, the system is a two-stage architecture whereby the recall stage is implemented using Matrix Factorization (MF) followed by an LLM-based ranking module generating ranks and explanations. Next, I’ll describe the dataset used, and how the recall and ranking stages are implemented and evaluated.</p><h4>Dataset</h4><p>The dataset used is the publicly available <a href="https://grouplens.org/datasets/movielens/100k/">MovieLens 100k</a>. This popular benchmark dataset contains 100k movie ratings from 1000 users and 1700 movies. The ratings are then transformed to binary implicit feedback as these are more common in the real world.</p><pre>ratings[&#39;like&#39;] = ratings[&#39;rating&#39;] &gt; 3</pre><p>The processed dataset is shown below. The new column ‘like’ is transformed implicit signal from the original ratings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45faad0d00f8e5b2bb7bf98d214db6f8/href">https://medium.com/media/45faad0d00f8e5b2bb7bf98d214db6f8/href</a></iframe><p>Next, the dataset is split into a training set and a test set with a split ratio of 0.9.</p><pre>train_ratio = 0.9<br>train_size = int(len(ratings)*train_ratio)<br>ratings_train = ratings.sample(train_size, random_state=42)<br>ratings_test = ratings[~ratings.index.isin(ratings_train.index)]</pre><p>Now, we have the data prepared. Let’s build the recall stage!</p><h4>Recall stage</h4><p>The recall stage is implemented using the widely adopted Matrix Factorization, which is a type of collaborative filtering. The basic idea is to project users and items into the same embedding space and model the similarity based on the binary user-item interactions. In terms of implementation, a fast version that is <a href="https://github.com/benfred/implicit?tab=readme-ov-file">Alternating Least Squares</a> is adopted.</p><p>Firstly, the data needs to be transformed into a sparse matrix with the row indices representing user ID and column indices representing item ID. It’s worth noting that the “ID minus 1” operation transforms actual IDs to indices that start from 0.</p><pre>from scipy.sparse import csr_matrix<br><br>n_users = ratings_train[&#39;user id&#39;].max()<br>n_item = ratings_train[&#39;item id&#39;].max()<br>ratings_train_pos = ratings_train[ratings_train[&#39;like&#39;]]<br>ratings_test_pos = ratings_test[ratings_test[&#39;like&#39;]]<br><br><br>row=ratings_train_pos[&#39;user id&#39;].values - 1<br>col=ratings_train_pos[&#39;item id&#39;].values - 1<br>data=np.ones(len(ratings_train_pos))<br>user_item_data = csr_matrix((data, (row, col)), shape=(n_users, n_item))</pre><p>Now we simply use the interaction matrix to train the MF model using the default parameters.</p><pre>import implicit<br><br># initialize a model<br>model = implicit.als.AlternatingLeastSquares(factors=50, random_state=42)<br><br># train the model on a sparse matrix of user/item/confidence weights<br>model.fit(user_item_data)</pre><p>As shown by the following function, retrieving the top-N candidate items for a given user is pretty simple. Here, the movies already watched are filtered out as we aim to recommend new ones.</p><pre>def recall_stage(model, user_id, user_item_data, ratings_train, N):<br>  filter_items = ratings_train[ratings_train[&#39;user id&#39;]==user_id][&#39;item id&#39;].values<br>  filter_items = filter_items - 1<br>  user_id = user_id - 1<br><br>  recs, scores = model.recommend(user_id, <br>                                 user_item_data[user_id], <br>                                 filter_items=filter_items,<br>                                 N=N_recall)<br>  recs = recs.flatten() + 1<br>  return recs</pre><h4>Ranking stage</h4><p>Now, it’s time to build the ranking stage using LLM. Briefly, the idea is that we let LLM tell us if the user likes each item returned by the recall stage based on the user preference in the training data and its own knowledge. This is implemented as a typical few-shot prompt shown below.</p><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain.chains import LLMChain<br>import openai<br>import os<br>from google.colab import userdata<br><br>if &quot;OPENAI_API_KEY&quot; not in os.environ:<br>    os.environ[&quot;OPENAI_API_KEY&quot;] = userdata.get(&#39;OPENAI_API_KEY&#39;)<br><br>llm_model = &quot;gpt-3.5-turbo&quot;<br>llm = ChatOpenAI(temperature=0.0, model=llm_model)<br><br>prompt = ChatPromptTemplate.from_template(<br>&quot;&quot;&quot;The person has a list of liked movies: {movies_liked}. \<br>The person has a list of disliked movies: {movies_disliked}. \<br>Tell me if this person likes each of the candidate movies: {movies_candidates}.\<br>Return a list of boolean values and explain why the person likes or dislikes.<br><br>&lt;&lt; FORMATTING &gt;&gt;<br>Return a markdown code snippet with a list of JSON object formatted to look like:<br>{{<br>    &quot;title&quot;: string \ the name of the movie in candidate movies<br>    &quot;like&quot;: boolean \ true or false<br>    &quot;explanation&quot;: string \ explain why the person likes or dislikes the candidate movie<br>}}<br><br><br>REMEMBER: Each boolean and explanation for each element in candidate movies.<br>REMEMBER: The explanation must relate to the person&#39;s liked and disliked movies.<br>&quot;&quot;&quot;<br>)<br><br>chain = LLMChain(llm=llm, prompt=prompt)</pre><p>This prompt requires three input parameters:</p><ol><li>movies_liked: a list of titles of the movies liked by the user.</li><li>movies_disliked: a list of titles of the movies disliked by the user.</li><li>movies_candidates: a list of titles of the candidate movies to be judged by the LLM based on the few-shot user preference and its compressed knowledge.</li></ol><p>Specifically, movies_liked and movies_disliked are extracted from the training data, whereas movies_candidates is the output of the recall stage. The LLM is instructed to provide both the binary decision and explanation about the user’s feedback to each candidate movie. Moreover, it is expected to associate the explanation with user preference to make it contextual.</p><p>The OpenAI GPT 3.5 Turbo is adopted; however, this can be changed to other LLMs. It’s also encouraged to explore and refine the prompt template as it plays an important role for generating recommendations.</p><p>This prompt is then utilized by the ranking function below to generate binary judgments.</p><pre>def ranking_stage(chain, user_id, ratings_train, pre_recs, movie, batch_size=10):<br><br>  few_shot = ratings_train[(ratings_train[&#39;user id&#39;]==user_id)]<br>  if len(few_shot) &gt;= 300:<br>    few_shot = few_shot.sample(300, random_state=42)<br>  recall_recs = movie.set_index(&#39;item id&#39;).loc[pre_recs].reset_index()<br><br>  movies_liked = &#39;,&#39;.join(few_shot[few_shot[&#39;like&#39;]][&#39;title&#39;].values.tolist())<br>  movies_disliked = &#39;,&#39;.join(few_shot[~few_shot[&#39;like&#39;]][&#39;title&#39;].values.tolist())<br><br>  n_batch = int(np.ceil(len(recall_recs)/batch_size))<br>  candidates = recall_recs[[&#39;item id&#39;, &#39;title&#39;]]<br>  result_json = []<br><br>  for i in range(n_batch):<br>    candidates_batch = candidates.iloc[i*batch_size: (i+1)*batch_size]<br>    movies_candidates = &#39;,&#39;.join(candidates_batch[&#39;title&#39;].values.tolist())<br>    result = chain.run(movies_liked=movies_liked, movies_disliked=movies_disliked, movies_candidates=movies_candidates)<br>    result_list = result.replace(&#39;\n&#39;, &#39;&#39;).replace(&#39;},&#39;, &#39;}\n,&#39;).split(&#39;\n,&#39;)<br>    result_json_batch = [json.loads(i) for i in result_list]<br>    result_json = result_json + result_json_batch<br><br>  result_rank = pd.DataFrame.from_dict(result_json)<br>  result_rank[&#39;item id&#39;] = recall_recs[&#39;item id&#39;].values<br>  result_rank = pd.concat([result_rank[result_rank[&#39;like&#39;]], result_rank[~result_rank[&#39;like&#39;]]])<br><br>  return result_rank</pre><p>In detail, for a given user, the ranking function first prepares the prompt inputs based on the training data and the results of the recall stage. For a user, the number of movie preferences is limited to a maximum of 300 to minimize the risk of token length violation.</p><p>Next, it calls the LLM with these inputs in batch mode to avoid violating the token length. For each batch, the full movies_liked and movies_disliked are passed as one piece to keep the complete context, whereas the candidate movies are injected in batches.</p><p>Finally, the candidate list with binary decisions is re-ordered to prioritize the preferred items. As illustrated below, to accommodate the binary signals, the candidate items classified as ‘dislikes’ are de-ranked in the way that they are pulled out of the candidate list and appended to the liked ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_tFOBX0hJXLz6ukZYk38g.png" /><figcaption>Ranking operation for binary signals | Image by author</figcaption></figure><h4>Evaluation</h4><p>To have a sense of the effect of the LLM-based ranking stage, an ablation study has been conducted to compare the architecture that only has the recall stage, viz. MF and the one adding the ranking stage called MF+GPT.</p><p>The metrics adopted are Precision@K [2], Recall@K [2], and DCG@K [3], which are popular options for evaluating recommender systems. Here, the values of K include 5, 10, 15, and 20. To balance validity and compute speed, 20 users are randomly sampled to calculate the average value for each metric. For each user, 30 candidates are generated by the recall stage and the top K movies are compared against the corresponding liked movies in the user’s test data.</p><p>The results shown below look promising! MF+GPT is superior to MF based on the uplift of these metrics, which demonstrates the success of the LLM-based ranking stage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8b7890be698723f7c42e037d1d06724/href">https://medium.com/media/d8b7890be698723f7c42e037d1d06724/href</a></iframe><h4>Explainability</h4><p>Besides the accuracy uplift, another advantage of the LLM ranking module is the generated explanations for each recommendation. Now, let’s eyeball some examples to sense and check the explainability.</p><p>The table below shows the ranking results for one user in the test set. The columns from left to right are the movie titles, explanations, and ranks. After a rough investigation, the explanations make sense in most cases and LLM pretty much meets my expectation.</p><p>As instructed, the reasoning is considering both user preference and LLM’s external knowledge that characterizes candidates&#39; movies from various angles. One good example is Hoop Dreams (1994): “The person dislikes ‘Hoop Dreams (1994)’ because it is a <strong><em>documentary</em></strong> film, and the person has not shown a preference for this genre. The person’s favorite movies are primarily <strong><em>narrative fiction</em></strong> films, such as ‘Secrets &amp; Lies (1996)’ and ‘L.A. Confidential (1997)’. Additionally, ‘Hoop Dreams (1994)’ focuses on <strong><em>basketball</em></strong>, which may not be a subject of interest for the person based on their movie preferences.”.</p><p>It associates the candidate movie with two others via the genre and storyline that are far beyond the movie titles injected! Feel free to browse more examples to get a better understanding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7138f51a7a4bd342b73d135a7d00c77/href">https://medium.com/media/c7138f51a7a4bd342b73d135a7d00c77/href</a></iframe><h3>Final thoughts</h3><p>Based on the experiment, LLM-based ranking has demonstrated its value in improving the quality of a recommender system. However, there are some limitations identified during the R&amp;D:</p><ol><li>Latency. The time consumed to generate recommendations makes it infeasible to enable real-time response to adapt to the user’s latest interest. This is likely to harm the online user experience.</li><li>Token length limit. The maximal token length largely limits the context and prior knowledge injected. As a result, the features need to be either carefully engineered or even omitted.</li><li>Knowledge recency and validity. The ranking and reasoning rely on the compressed knowledge of LLMs, so they only make sense when such knowledge is up-to-date and correct. For instance, an LLM is unlikely to make good suggestions if the title of a candidate movie is new and not recognized.</li></ol><p>As an emerging topic, more ideas are expected to be proposed and experimented with to marry LLMs and recommender systems. I’m eager to receive your feedback and collaborate to make things better.</p><p>Thanks for your time, and I hope you like this work.</p><h3>References</h3><p>[1] <a href="https://www.alibabacloud.com/blog/getting-started-with-recommendation-system_597740">https://www.alibabacloud.com/blog/getting-started-with-recommendation-system_597740</a></p><p>[2] <a href="https://medium.com/@m_n_malaeb/recall-and-precision-at-k-for-recommender-systems-618483226c54">https://medium.com/@m_n_malaeb/recall-and-precision-at-k-for-recommender-systems-618483226c54</a></p><p>[3] <a href="https://medium.com/@maeliza.seymour/discounted-cumulative-gain-the-ranking-metrics-you-should-know-about-e1d1623f8cd9">https://medium.com/@maeliza.seymour/discounted-cumulative-gain-the-ranking-metrics-you-should-know-about-e1d1623f8cd9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b44365a46d" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/using-llms-to-build-explainable-recommender-systems-e0b44365a46d">Using LLMs to Build Explainable Recommender Systems</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing E-commerce product search using LLMs]]></title>
            <link>https://pub.towardsai.net/enhancing-e-commerce-product-search-using-llms-30d5a2117f71?source=rss-2665192d75e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d5a2117f71</guid>
            <category><![CDATA[search-query-optimization]]></category>
            <category><![CDATA[product-search]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Hang Yu]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 16:01:52 GMT</pubDate>
            <atom:updated>2023-08-10T16:01:52.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing E-commerce Product Search Using LLMs</h3><h4>Applying LLMs to make E-commerce search engines robust to colloquial queries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lmNKn-Q2L83YZyf4" /><figcaption>Photo by <a href="https://unsplash.com/@veryinformed?utm_source=medium&amp;utm_medium=referral">Oberon Copeland @veryinformed.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In recent years, web search engines have been quickly embracing Large Language Models (LLMs) to increase their search capability. One of the most successful examples is Google search powered by BERT [1]. Comparatively, many E-commerce platforms are relatively more conservative in applying this emerging technique in their product search. In this article, I will demonstrate how LLMs can be applied to benefit the understanding capability of E-commerce product search when it encounters search queries that are colloquial and implicit.</p><h3>Problem Statement</h3><p>Despite the pioneers like Amazon [2], many E-commerce platforms are still heavily relying on traditional retrieval techniques like TFIDF and BM25 for product search. Such sparse methods usually require customers to type explicit queries that match the product information and mostly struggle to achieve good relevance for queries that are colloquial and implicit. In consequence, the search engine either returns no result or results with low relevance ignoring the existence of the relevant ones, which harms the customer experience and business metrics.</p><p>For instance, Ebay is returning “No exact matches found” for the query “What are the best gifts for boys under 5?”. Although the “Results matching fewer words” solution avoids the “no result” situation, its search relevance has got the obvious potential to be improved.</p><figure><img alt="Ebay search results for query “What are the best gifts for boys under 5?”" src="https://cdn-images-1.medium.com/max/1024/1*ssV1Gep-FJcdkSd_Fo3xfw.png" /><figcaption>Figure 1. Ebay search results for the query “What are the best gifts for boys under 5?” | Source: Ebay.com</figcaption></figure><p>People might argue that it’s rare for such queries to occur. However, it’s not uncommon that many opportunities and advancements are actually driven by the use cases that are underestimated in the beginning.</p><h3>LLM-based Solution</h3><p>Today, thanks to the fast development of LLMs, one can quickly build prototypes without worrying about the effort needed to build in-house solutions from scratch. This enables my quick discovery to tackle the problem.</p><p>As depicted in the image below, the idea is pretty straightforward. The LLM is leveraged to translate the raw query to an enhanced query that aims to contain the explicit product information for search. Potentially, the product range covered in the enhanced query could be broad for the raw query that is implicit and fuzzy. In consequence, sending the enhanced query directly to the keyword-based search engine will likely lead to poor results due to its ambiguity and uncertainty. As a solution, LLM embedding is adopted to address the semantic complexity. Specifically, the enhanced query is projected into the embedding space that contains the preprocessed product embeddings. Next, the product retrieval is done by comparing the similarity between the query embedding and product embeddings, which then generates the top-k products as search results.</p><figure><img alt="The workflow of the proposed solution" src="https://cdn-images-1.medium.com/max/1024/1*YY-agry69CwIb2fhNOjRXw.png" /><figcaption>Figure 2. The workflow of the proposed solution | Image by author</figcaption></figure><p>There is a wide range of techniques to implement the idea as there exist many options for each step. Here, I provide one example implementation based on Hugging Face and LangChain. The actual code is hosted on the Github repo below, with the details explained as follows.</p><p><a href="https://github.com/simon19891101/ML_experiments/blob/main/LLM_search_exp.ipynb">ML_experiments/LLM_search_exp.ipynb at main · simon19891101/ML_experiments</a></p><h4><strong>Generate the enhanced query</strong></h4><p>First, the recently announced Llama 2 is adopted as the LLM to generate the enhanced query for a given raw query. As demonstrated below, the Hugging Face pipeline is used, considering its simplicity. It’s worth noting that the pipeline itself is enough to accomplish the task so the use of LangChain is totally optional. The prompt template adopted here aims to generate relevant and diverse product names to address the fuzziness of the raw query.</p><pre>from transformers import AutoTokenizer<br>import transformers<br>import torch<br><br>model = &quot;meta-llama/Llama-2-7b-chat-hf&quot;<br><br>tokenizer = AutoTokenizer.from_pretrained(model, use_auth_token=True)<br><br>pipeline = transformers.pipeline(<br>    &quot;text-generation&quot;,<br>    model=model,<br>    torch_dtype=torch.float16,<br>    device_map=&quot;auto&quot;,<br>    do_sample=False,<br>    top_k=1,<br>    num_return_sequences=1,<br>    eos_token_id=tokenizer.eos_token_id,<br>    max_length=200<br>)<br><br><br>from langchain.llms import HuggingFacePipeline<br>from langchain import PromptTemplate, LLMChain<br><br>template=&#39;&#39;&#39;[INST] &lt;&gt;<br>Only tell me the product names. The answer should only include ten names.<br>&lt;&gt;<br><br>{prompt}[/INST]&#39;&#39;&#39;<br><br>prompt_template = PromptTemplate(template=template, input_variables=[&quot;prompt&quot;])<br><br>llm = HuggingFacePipeline(pipeline=pipeline)<br><br>llm_chain = LLMChain(prompt=prompt_template, llm=llm)</pre><h4><strong>Create product embeddings</strong></h4><p>Next, the sentence transformer and FAISS in LangChain are used to create and store the product embeddings based on the product titles in the inventory. Here, due to the lack of access to actual search engines, the offline Ebay product dataset “products.csv” is adopted as the mockup of the E-commerce product inventory. This dataset contains approximately 3,000 products covering a wide range of categories.</p><p><a href="https://data.world/opensnippets/ebay-uk-products-dataset">Ebay UK products dataset - dataset by opensnippets</a></p><pre>import pandas as pd<br>products = pd.read_csv(&#39;products.csv&#39;, usecols=[&#39;name&#39;])<br><br>from langchain.vectorstores import FAISS<br>from langchain.embeddings import HuggingFaceEmbeddings<br><br>embeddings = HuggingFaceEmbeddings(model_name=&#39;sentence-transformers/all-MiniLM-L6-v2&#39;,<br>                                   model_kwargs={&#39;device&#39;: &#39;cpu&#39;})<br><br><br>product_names = products[&#39;name&#39;].values.astype(str)<br>product_embeddings = FAISS.from_texts(product_names, embeddings)</pre><h4><strong>Product retrieval</strong></h4><p>When it comes to retrieval, the same sentence transformer model that encodes the products is used again to generate the query embedding for the enhanced query. Finally, the top-10 products are retrieved based on the similarity between the query embedding and product embeddings.</p><pre>raw_query = &#39;example query&#39;<br>enhanced_query = llm_chain.run(raw_query)<br>product_embeddings.similarity_search_with_score(enhanced_query, k=10)</pre><h4>Showcase</h4><p>To demonstrate the effectiveness of this approach, let’s look at the above-mentioned query “What are the best gifts for boys under 5?” and compare the LLM enhancement with the original Ebay search results presented in Figure 1.</p><p>First, after receiving the raw query, Llama 2 generates 10 products as instructed by the prompt template. They look pretty impressive for boys’ gift ideas although a better product-level granularity is expected.</p><figure><img alt="LLM Enhanced query" src="https://cdn-images-1.medium.com/max/1024/1*al_TT7NXxvRW5u2rl8F2Ng.png" /><figcaption>Figure 3. LLM Enhanced query | Image by author</figcaption></figure><p>Next, let’s have a look at the similarity match in the embedding space. What are retrieved from the product inventory mockup are not bad at all in comparison with the results of the real-world Ebay search engine in Figure 1. Due to the limited product range of the inventory mockup, the comparison is somewhat unfair but we are still able to observe the significant difference before and after applying LLM. Overall, the retrieval in embedding space achieves both relevance and diversity.</p><figure><img alt="LLM-enhanced search results" src="https://cdn-images-1.medium.com/max/1024/1*9LvEXJ1ryJW3kM4EX94OSw.png" /><figcaption>Figure 4. LLM-enhanced search results | Image by author</figcaption></figure><h3>Final thoughts</h3><p>After conducting the initial discovery, it is obvious that LLMs are a powerful tool to enhance the product search of E-commerce platforms. For this task, there are many future explorations to conduct, including prompt engineering for generating queries, product embeddings with enriched attributes, online latency optimization for LLM query enhancement, etc. Hope this blog could inspire the E-commerce platforms that need solutions to improve product search.</p><h3>References</h3><p>[1] Nayak, P. (2019) <em>Understanding searches better than ever before</em>, <em>Google</em>. Available at: https://blog.google/products/search/search-language-understanding-bert/ (Accessed: 09 August 2023).<br>[2] Muhamed, A. <em>et al.</em> (no date) <em>Web-scale semantic product search with large language models</em>, <em>Amazon Science</em>. Available at: <a href="https://www.amazon.science/publications/web-scale-semantic-product-search-with-large-language-models">https://www.amazon.science/publications/web-scale-semantic-product-search-with-large-language-models</a> (Accessed: 09 August 2023).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d5a2117f71" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/enhancing-e-commerce-product-search-using-llms-30d5a2117f71">Enhancing E-commerce product search using LLMs</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Hyperparameter Tuning in Vertex AI Pipeline]]></title>
            <link>https://medium.com/data-science/distributed-hyperparameter-tuning-in-vertex-ai-pipeline-2f3278a1eb64?source=rss-2665192d75e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f3278a1eb64</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[vertex-pipeline]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[machine-learning-pipeline]]></category>
            <dc:creator><![CDATA[Hang Yu]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 04:50:07 GMT</pubDate>
            <atom:updated>2023-03-29T04:50:07.727Z</atom:updated>
            <content:encoded><![CDATA[<h4>A path to enable the distributed hyperparameter tuning in GCP Vertex AI pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XA6RxTs9taeBulaQ" /><figcaption>Photo by <a href="https://unsplash.com/@marsha_reid?utm_source=medium&amp;utm_medium=referral">Marsha Reid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Vertex AI pipelines offer a handy way to implement end-to-end ML workflows from data collection to endpoint monitoring with extremely low effort. For new users, the easiness of development and deployment is largely thanks to the <a href="https://github.com/GoogleCloudPlatform/professional-services/tree/main/examples/vertex_pipeline"><strong>V</strong>ertex AI pipeline example</a> offered by GCP.</p><p><a href="https://github.com/GoogleCloudPlatform/professional-services/tree/main/examples/vertex_pipeline">professional-services/examples/vertex_pipeline at main · GoogleCloudPlatform/professional-services</a></p><p>Despite the comprehensive demonstration of the essential components, the official example also exposes the feasibility for users to customize and enhance the pipeline based on their own needs. Amongst all, one of the most exciting components is the distributed Hyperparameter Tuning (HPT) that is capable of exploring a huge search space to identify the best hyperparameters in a short time. For the time being, GCP recommends leveraging <strong>cloudml-hypertune </strong>and<strong> google_cloud_pipeline_components </strong>for this purpose and presents the corresponding tutorials:</p><p><a href="https://codelabs.developers.google.com/vertex-training-200#0">GCP HPT task tutorial</a></p><p><a href="https://codelabs.developers.google.com/vertex-training-200#0">Vertex AI: Distributed hyperparameter tuning | Google Codelabs</a></p><p><a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">HPT pipeline sample</a></p><p><a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">vertex-ai-samples/get_started_with_hpt_pipeline_components.ipynb at cad623ef84882f410fcc0dc39527be25a5e5f584 · GoogleCloudPlatform/vertex-ai-samples</a></p><p>However, the limitation of the tutorials is that the distributed HPT is presented as a standalone HPT task/pipeline and it doesn’t explicitly present the approach to integrate into the existing Vertex AI pipeline shown in the <a href="https://github.com/GoogleCloudPlatform/professional-services/tree/main/examples/vertex_pipeline"><strong>V</strong>ertex AI pipeline example</a>, which motivates me to share my successful attempt that bridges the gap. I believe this will benefit many businesses who have built or will build their ML workflows based on Vertex AI pipeline.</p><p><strong>The major contribution of this blog is the integration of the distributed HPT into the Vertex AI pipelines. Specifically, it demonstrates how to:</strong></p><ol><li>Chain data collection and preprocessing of a Vertex AI pipeline to the distributed HPT. In comparison, the <a href="https://codelabs.developers.google.com/vertex-training-200#0">GCP HPT task tutorial</a> and <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">HPT pipeline sample</a> simplify data collection and processing via loading a static tensorflow dataset in the training step.</li><li>Optimize HPT results collection to avoid docker arg length limit. In the <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">HPT pipeline sample</a>, the complete HPT results of all trials are encoded as a string that’s passed to a docker task as an input argument for further processing. However, the risk is that the string might violate the length limit of docker input argument in case of a large search space. Thus, a simple solution that combines those two components is explored in this article.</li><li>Save the best parameters in firestore. In the <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">HPT pipeline sample</a>, HPT runs the trials, saves the models, and deploys the best one whereas it’s unclear how to visit the best parameters afterwards. This doesn’t suit the scenario that HPT and training is expected to be decoupled. Thus, the firestore option is explored to save the best hyperparameters for the later training jobs.</li><li>Chain the distributed HPT to the training component and train the model using the best parameters. Instead of saving the model of every HPT trial as shown in the <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">HPT pipeline sample</a>, an alternative that re-trains and only saves the best model is explored though it’s open to debate if this approach offers a better storage-compute tradeoff depending on the specific scenario.</li></ol><h3>Integrating distributed HPT into Vertex AI pipeline</h3><p>Now, let’s go through the major steps mentioned above. It is worth noting that the ML pipeline demonstrated here is largely based on the <a href="https://github.com/GoogleCloudPlatform/professional-services/tree/main/examples/vertex_pipeline"><strong>V</strong>ertex AI pipeline example</a> and only the minimum changes are made to enable HPT. For the purpose of demonstration, only two hyperparameters are tuned via grid search as shown below.</p><pre>SEARCH_SPACE={&quot;num_boost_round&quot;: [100, 200],<br>             &quot;min_data_in_leaf&quot;: [5, 10]}</pre><p>The jupyter notebook of this work, which contains the end-to-end process to deploy the distributed HPT, is hosted in the <a href="https://github.com/simon19891101/professional-services/blob/distributed-hpt-demo/examples/vertex_pipeline/notebook/hpt_pipeline_development.ipynb">repo</a> below.</p><p><a href="https://github.com/simon19891101/professional-services/blob/distributed-hpt-demo/examples/vertex_pipeline/notebook/hpt_pipeline_development.ipynb">professional-services/hpt_pipeline_development.ipynb at distributed-hpt-demo · simon19891101/professional-services</a></p><h4>1. Chain data preprocessing to HPT</h4><p>The first challenge I encountered is that the <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb"><strong>vertex-ai-samples</strong></a><strong> </strong>tutorial<strong> </strong>hard coded the data collection in the HPT container image that is called by the HyperparameterTuningJobRunOp class of google_cloud_pipeline_components.v1.hyperparameter_tuning_job whereas in practice we may want to use the data collection and processing pipeline component in the pipeline.</p><pre>data, info = tfds.load(name=&#39;horses_or_humans&#39;, as_supervised=True, with_info=True)</pre><p>However, currently the HyperparameterTuningJobRunOp doesn’t support input data as an argument, which motivates me to find an alternative way to pass the data source. Fortunately, it turns out that HyperparameterTuningJobRunOp consumes worker_pool_specs that contains the HPT container specification which supports the input args to the HPT container.</p><pre>worker_pool_specs = [<br>    {<br>        &quot;machine_spec&quot;: {<br>            &quot;machine_type&quot;: &quot;n1-standard-4&quot;,<br>        },<br>        &quot;replica_count&quot;: 1,<br>        &quot;container_spec&quot;: {&quot;image_uri&quot;: hpt_container_image_uri, &quot;args&quot;: CMDARGS},<br>    }<br>    ]</pre><p>Intuitively, it implies the feasibility to pass the input data source as a part of the args of the container_spec and it’s validated to be a successful attempt.</p><p>The code example of such operation is shown below. Specifically, a new pipeline component called worker_pool_specs is created to receive the input_dataset from the data processing component and generate the worker_pool_specs that’s passed to HyperparameterTuningJobRunOp. In this way, data preprocessing and the core HPT module is associated as depicted in the screenshot below. It’s worth noting training_data_schema, label, and features are also passed as they are required by the training script of <a href="https://github.com/GoogleCloudPlatform/professional-services/tree/main/examples/vertex_pipeline"><strong>V</strong>ertex AI pipeline example</a>.</p><pre>@component<br>def worker_pool_specs(project_id: str,<br>    data_region: str,<br>    data_pipeline_root: str,<br>    hpt_container_image_uri: str,<br>    custom_job_service_account: str,<br>    input_dataset: Input[Dataset],<br>    input_data_schema: str) -&gt; list:<br>    &quot;&quot;&quot;<br>    Pass the preprocessed data uri to hpt as a worker pool argument. The vanilla hpt API <br>    doesn&#39;t support &#39;input data&#39; so it&#39;s done this way.<br>    <br>    data_preprocess -&gt; dataset.uri -&gt; CMDARGS -&gt; worker_pool_specs -&gt; hpt<br>    &quot;&quot;&quot;<br>    <br>    display_name = &#39;hpt-pipeline-template&#39;<br>    fields = [field.split(&#39;:&#39;)[0] for field in input_data_schema.split(&#39;;&#39;)]<br>    label = fields[-1]<br>    features = &#39;,&#39;.join(fields[0:-1])<br>    CMDARGS = [<br>    &quot;--training_data_uri=&quot;+str(input_dataset.uri),<br>    &quot;--training_data_schema=&quot;+input_data_schema,<br>    &quot;--label=&quot;+label,<br>    &quot;--features=&quot;+features<br>]<br><br>    # The spec of the worker pools including machine type and Docker image<br>    worker_pool_specs = [<br>    {<br>        &quot;machine_spec&quot;: {<br>            &quot;machine_type&quot;: &quot;n1-standard-4&quot;,<br>        },<br>        &quot;replica_count&quot;: 1,<br>        &quot;container_spec&quot;: {&quot;image_uri&quot;: hpt_container_image_uri, &quot;args&quot;: CMDARGS},<br>    }<br>    ]<br>    <br>    return worker_pool_specs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*z4vS6bAStZW_ZgU1vi1u5w.png" /><figcaption>Chain preprocess to HPT via worker-pool-specs component</figcaption></figure><h4>2. Optimize HPT results collection</h4><p>In the original <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">HPT pipeline sample</a>, the output of the HPT module, which is the resource name of the HPT job, is passed to the GetTrialsOp module to retrieve all the hyperparameters and their scores so as to let the GetBestTrialOp module find the best, as shown below.</p><pre>tuning_op = HyperparameterTuningJobRunOp(<br>    display_name=display_name,<br>    project=project,<br>    location=region,<br>    worker_pool_specs=worker_pool_specs,<br>    study_spec_metrics=study_spec_metrics,<br>    study_spec_parameters=study_spec_parameters,<br>    max_trial_count=max_trial_count,<br>    parallel_trial_count=parallel_trial_count,<br>    base_output_directory=base_output_directory,<br>)<br><br>trials_op = hyperparameter_tuning_job.GetTrialsOp(<br>    gcp_resources=tuning_op.outputs[&quot;gcp_resources&quot;]<br>)<br><br>best_trial_op = hyperparameter_tuning_job.GetBestTrialOp(<br>    trials=trials_op.output, study_spec_metrics=study_spec_metrics<br>)</pre><p>Currently, GetTrialsOp module encodes the results of all HPT trials into a string as presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYGC-Y_RcRBJVnFYCElbDw.png" /><figcaption>Sample output of GetTrialsOp</figcaption></figure><p>When the search space is large, one risk observed in practice is that this long string may violate the input argument length of the following docker container that is GetBestTrialOp.</p><blockquote>job_spec.worker_pool_specs[0].container_spec.args; Message: Container args should contain less than 100k characters</blockquote><p>To avoid this limitation, a hacky but effective approach is attempted though there may be some better options. Basically, the source code of GetTrialsOp (see <a href="https://github.com/kubeflow/pipelines/tree/master/components/google-cloud/google_cloud_pipeline_components/experimental/hyperparameter_tuning_job">hyperparameter_tuning_job</a>) is injected into that of GetBestTrialOp so that those two pipeline components merge into one to avoid passing the long string as a docker input.</p><pre>@component(<br>    packages_to_install=[&#39;google-cloud-aiplatform&#39;, <br>                         &#39;google-cloud-pipeline-components&#39;,<br>                         &#39;protobuf&#39;], base_image=&#39;python:3.7&#39;)<br>def GetBestTrialOp(gcp_resources: str, study_spec_metrics: list) -&gt; str:<br><br>    from google.cloud import aiplatform<br>    from google_cloud_pipeline_components.proto.gcp_resources_pb2 import GcpResources<br>    from google.protobuf.json_format import Parse<br>    from google.cloud.aiplatform_v1.types import study<br><br>    api_endpoint_suffix = &#39;-aiplatform.googleapis.com&#39;<br>    gcp_resources_proto = Parse(gcp_resources, GcpResources())<br>    gcp_resources_split = gcp_resources_proto.resources[0].resource_uri.partition(<br>      &#39;projects&#39;)<br>    resource_name = gcp_resources_split[1] + gcp_resources_split[2]<br>    prefix_str = gcp_resources_split[0]<br>    prefix_str = prefix_str[:prefix_str.find(api_endpoint_suffix)]<br>    api_endpoint = prefix_str[(prefix_str.rfind(&#39;//&#39;) + 2):] + api_endpoint_suffix<br><br>    client_options = {&#39;api_endpoint&#39;: api_endpoint}<br>    job_client = aiplatform.gapic.JobServiceClient(client_options=client_options)<br>    response = job_client.get_hyperparameter_tuning_job(name=resource_name)<br>    <br>    trials = [study.Trial.to_json(trial) for trial in response.trials]<br><br>    if len(study_spec_metrics) &gt; 1:<br>        raise RuntimeError(&#39;Unable to determine best parameters for multi-objective&#39;<br>                       &#39; hyperparameter tuning.&#39;)<br>    trials_list = [study.Trial.from_json(trial) for trial in trials]<br>    best_trial = None<br>    goal = study_spec_metrics[0][&#39;goal&#39;]<br>    best_fn = None<br>    if goal == study.StudySpec.MetricSpec.GoalType.MAXIMIZE:<br>        best_fn = max<br>    elif goal == study.StudySpec.MetricSpec.GoalType.MINIMIZE:<br>        best_fn = min<br>    best_trial = best_fn(<br>      trials_list, key=lambda trial: trial.final_measurement.metrics[0].value)<br><br>    return study.Trial.to_json(best_trial)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*-Zt_DG1u7bAOHR0O6-_0FQ.png" /><figcaption>GetTrialsOp injected into GetBestTrialOp to be one component</figcaption></figure><h4>3. Save the best parameters in firestore</h4><p>In the <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/cad623ef84882f410fcc0dc39527be25a5e5f584/notebooks/community/ml_ops/stage3/get_started_with_hpt_pipeline_components.ipynb">HPT pipeline sample</a>, each HPT trial saves its trained model and the best one gets deployed later on. However, this approach, which couples HPT and model training, exposes some limitations:</p><ol><li>The model deployed is trained during one of the HPT trials. However, not every training needs HPT in practice. One such example is the recommender system built using matrix factorization. The model needs to be trained frequently using the latest user-item interactions but HPT is not always needed. Therefore, the option that decouples training and HPT is expected.</li><li>Deploying the model of HPT directly could lead to a biased evaluation as HPT is based on the validation data.</li></ol><p>To this end, instead of saving the trained models, it is preferred to save the best HPT result to a database like firestore for later use. After storing the best hyperparameters, model training and HPT are decoupled. The best parameters can be re-used to train models until a new round of HPT is needed. Besides, model evaluation can be improved by adding a seperate test set when a model is trained.</p><p>The code below demonstrates how the best HPT result is saved to firestore. Specifically, a pipeline component called best_hpt_to_args is defined to consume the best hyperparameters found by the GetBestTrialOp step discussed previously. The storage structure of firestore is to be decided case by case. Here, the timestamp is used to label a HPT pipeline. Lastly, this function returns a string “true”, which is preferred by the pipeline condition, to kick off the conditional model training that’s discussed later on. The validation accuracy is also logged for the sake of observability but this is totally optional.</p><pre>@component(packages_to_install=[&#39;google-cloud-firestore==2.3&#39;])<br>def best_hpt_to_args(hpt_best: str,<br>                    project_id: str,<br>                    solution_name: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Write the best hpt params to firestore. <br>    We keep the output to chain this component to the conditional training<br>    &quot;&quot;&quot;<br>    <br>    import json<br>    from datetime import datetime<br>    from google.cloud import firestore<br>    hpt_best = json.loads(hpt_best.replace(&quot;&#39;&quot;, &#39;&quot;&#39;))<br><br>    hpt_best_dict = {}<br>    <br>    for i in hpt_best[&#39;parameters&#39;]:<br>        hpt_best_dict.update({i[&#39;parameterId&#39;]: i[&#39;value&#39;]})<br>    <br>    for i in hpt_best[&#39;finalMeasurement&#39;][&#39;metrics&#39;]:<br>        hpt_best_dict.update({i[&#39;metricId&#39;]: i[&#39;value&#39;]})<br>    <br>    db = firestore.Client(project=project_id)<br>    task_flag=datetime.now().strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>    db.collection(solution_name).document(task_flag).set(hpt_best_dict,merge=True)<br>    <br>    return &quot;true&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXDyfArwgOQdLeHFOTREYQ.png" /><figcaption>Firestore example of the saved HPT result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*ieuRca7I8L5ne-KAOIXKdA.png" /><figcaption>Save best HPT result to firestore</figcaption></figure><h4>4. Train models using the best hyperparameters</h4><p>Finally, the HPT is finished. The last improvement I made is appending a conditional training task so that the latest HPT so that the best hyperparameters are utilized to update the model in production immediately. This step is totally optional and subject to the specific use case. It’s worth noting that this condition is receiving hpt_op.output that’s a function that wraps all HPT components from worker_pool_specs to best_hpt_to_args so its output equals that of best_hpt_to_args. Please see the details in the notebook.</p><pre>with dsl.Condition(<br>        hpt_op.output==&quot;true&quot;,<br>        name=&quot;train_model&quot;<br>    ):<br><br>    train_task = train_op(<br>      project_id=project_id,<br>      data_region=data_region,<br>      data_pipeline_root=data_pipeline_root,<br>      input_data_schema=training_data_schema,<br>      training_container_image_uri=training_container_image_uri,<br>      train_additional_args=train_additional_args,<br>      serving_container_image_uri=serving_container_image_uri,<br>      custom_job_service_account=custom_job_service_account,<br>      input_dataset=preprocess_task.outputs[&#39;output_dataset&#39;],<br>      machine_type=machine_type,<br>      accelerator_count=accelerator_count,<br>      accelerator_type=accelerator_type,<br>      hptune_region=hptune_region,<br>      hp_config_max_trials=hp_config_max_trials,<br>      hp_config_suggestions_per_request=hp_config_suggestions_per_request,<br>      vpc_network=vpc_network)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*-wFgqdnXNTjby2AL9hiJ4w.png" /><figcaption>Conditional training</figcaption></figure><p>In the training script (<a href="https://github.com/simon19891101/professional-services/blob/distributed-hpt-demo/examples/vertex_pipeline/images/training/app.py">images/training/app.py</a>), a function called get_best_param_values is implemented to collect the latest HPT result by querying firestore. Based on different ways to label the HPT pipelines, there might be different approaches to collect the HPT result of interest. The collected hyperparameters are in the form of a dictionary so they can easily get used to train the model.</p><pre>def get_best_param_values(project_id, solution_name=&#39;hpt-pipeline-template&#39;):<br>    db = firestore.Client(project=project_id)<br><br>    docs = db.collection(solution_name).list_documents()<br>    doc_latest = max([doc.id for doc in docs])<br>    <br>    params_latest = db.collection(solution_name).document(doc_latest).get().to_dict()<br>    <br>    logging.info(f&#39;Latest doc id {doc_latest}: {params_latest}&#39;)<br><br>    return params_latest</pre><pre>best_param_values = get_best_param_values(project_id=args.hp_config_gcp_project_id)</pre><h3>Summary</h3><p>Vertex AI pipelines on GCP provides a great platform to productionize ML solutions with high performance and flexibility. However, the existing tutorials show a limited coverage regarding how distributed HPT can be achieved. To fill up the gap, this article demonstrates the successful attempt to integrate the distributed GCP HPT module into the existing Vertex AI pipeline. Specifically, four limitations that are overlooked by the existing tutorials have been addressed:</p><ol><li>Data input. This would allow users to use the data preprocessed on the fly for the purpose of HPT.</li><li>HPT results collection. The optimized result collection enables the capacity to explore a large search space.</li><li>HPT results storage. Saving HPT results in firestore means training and HPT could be decoupled.</li><li>Model training using the best HPT result. Now we can train new models using the saved HPT result.</li></ol><p>It’s believed that the improvements discussed above would largely benefit the industrial use cases of Vertex AI pipelines for the scenarios that need to involve a fully automated distributed HPT to optimize the predictive power of the ML solutions running in production. For the detailed end-to-end implementation, please visit the notebook hosted in the <a href="https://github.com/simon19891101/professional-services/blob/distributed-hpt-demo/examples/vertex_pipeline/notebook/hpt_pipeline_development.ipynb">repo</a> and feel free to get in touch with me on <a href="https://www.linkedin.com/in/hang-yu-0242ac120002/">LinkedIn</a>.</p><p>Thank you for reading!</p><p><em>All images unless otherwise noted are by the author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f3278a1eb64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/distributed-hyperparameter-tuning-in-vertex-ai-pipeline-2f3278a1eb64">Distributed Hyperparameter Tuning in Vertex AI Pipeline</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>