<?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 Aicha Bokbot on Medium]]></title>
        <description><![CDATA[Stories by Aicha Bokbot on Medium]]></description>
        <link>https://medium.com/@aichabokbot?source=rss-50566ce7e21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jJAsvCE_o2AHOXeWdjseKQ.jpeg</url>
            <title>Stories by Aicha Bokbot on Medium</title>
            <link>https://medium.com/@aichabokbot?source=rss-50566ce7e21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:59:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aichabokbot/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[What Happens When Most Content Online Becomes AI-Generated?]]></title>
            <link>https://medium.com/data-science/what-happens-when-most-content-online-becomes-ai-generated-684dde2a150d?source=rss-50566ce7e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/684dde2a150d</guid>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Aicha Bokbot]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 18:47:06 GMT</pubDate>
            <atom:updated>2023-10-17T18:47:06.716Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how generative models deteriorate when trained on the data they generate, and what to do about it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WrXjKi1AwLcGGqm6" /><figcaption>Spiral — Photo by <a href="https://unsplash.com/@luddelorentz?utm_source=medium&amp;utm_medium=referral">Ludde Lorentz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>The recent breakthroughs in Generative AI have introduced publicly available AI models capable of producing highly realistic and complex text, image, and sound that revolutionize content creation.</p><p>These models were trained on large datasets scraped from the Internet. In the case of text data for instance, Large Language Models (LLMs) like ChatGPT were mostly trained on human-generated text found online.</p><p>Generative models have gained wide notoriety and fast adoption in society, to the extent that more and more AI-generated content ends up on the Internet, which is the major source of their training data.</p><p>We see a loop forming here: generative models will inevitably be trained on synthetic data produced by Generative AI and not by humans. Which brings us to the question: if that happens, how will the models behave?</p><h3>Generative models and degeneration</h3><blockquote>What will happen to GPT-{n} once LLMs contribute much of the language found online?</blockquote><p>That is the question asked by a team of researchers that published the paper <a href="https://browse.arxiv.org/pdf/2305.17493v2.pdf?"><em>The Curse of Recursion: Training on Generated Data Makes Models Forget</em></a> (I. Shumailov et al., 2023).</p><p>The authors experiment with making models learn from the data they generate over several iterations. They apply this on Gaussian Mixture Models (GMMs), Variational Autoencoders (VAE) and Large Language models (LLMs). For the three types of models, this leads to a phenomenon they call “<em>model collapse</em>”:</p><blockquote>a degenerative process whereby, over time, models forget the true underlying data distribution, even in the absence of a shift in the distribution over time.</blockquote><p><em>Model collapse</em> characterizes the behavior of models forgetting the tails of real distributions (i.e. the improbable, less frequent and yet important events) and over-representing the center of the distribution. As the process repeats, models converge to a distribution that has little similarity with the original one.</p><p>In the paper <a href="https://arxiv.org/abs/2307.01850"><em>Self-Consuming Generative Models Go MAD</em></a> (S. Alemohammad et al., 2023), other researchers similarly describes this gradual divergence away from original distributions as “<em>Model Autophagy Disorder</em>”<em> (MAD)</em>:</p><blockquote>[…] without enough fresh real data in each generation, future generative models are doomed to Model Autophagy Disorder (MAD), meaning that either their quality (measured in terms of precision) or their diversity (measured in terms of recall) will progressively degrade.</blockquote><p>The conclusion is clear: generative models tend to deteriorate when they are primarily trained on the content they generate. Given that the majority of their training data comes from the Internet, how much of a risk does this degenerative process represent?</p><h3>When human-generated content grows scarce</h3><p>If the proportion of human- vs. AI-generated content remains as it is today, with a clear majority of online content created by humans, the situation should not be worrying and the performance of Generative models should not face the degeneration described earlier.</p><p>However, there is a legitimate concern over the prospect of an Internet dominated by AI-generated content. If we focus on text generation, the main argument supporting this projection is the convenience offered by LLMs like GPT. These tools address real pain points when it comes to writing: finding the right words, improving style, getting inspiration. Those who have tried them can attest how tempting and addictive it is to rely on these tools: why struggle when we can effortlessly prompt an LLM to generate content that is better both in style and time-efficiency?</p><p>So if human-generated content becomes less prevalent, what measures can be taken to mitigate the risk of exposing Generative models to AI-generated content? One possible approach is to attempt to counter the trend by encouraging content creation without AI tools. Another approach involves developing methods to detect AI-generated data and filtering it out during the model training process.</p><p>The idea of the first approach is to find ways to incentivize creators to use generative models less frequently or in fewer contexts. However, the feasibility of this approach may be limited. Even if we could find such incentives (e.g. a reward or a sanction), the challenge lies in verifying whether a piece of content is genuinely human-generated or not. This leads us to the second approach, which also relies on the ability to distinguish human-generated from AI-generated data.</p><h3>How to detect AI-generated data</h3><p>In 2023, the company AI21 Labs led the largest Turing test to date: over 1.5 million users engaged in an online chat with either a human or an AI chatbot and were asked to guess who they spoke to. The task proves to be non-trivial as 68% of people guessed correctly, showing how well generative AI can mimic humans.</p><p>With that in mind, let’s review some available techniques to identify AI-generated data.</p><h4>Watermarking</h4><p>The main approach discussed in the literature to distinguish human-generated from AI-generated data is <em>watermarking</em>. Watermarking is the process of adding hidden signals in the data that are invisible to humans but detectable by algorithms.</p><p>Watermarking would enable to easily detect AI-generated data, but it only works if Generative AI providers add it to their products. This is not the case today, and it might be too optimistic to expect that any time soon.</p><p>In his open letter <a href="https://www.deeplearning.ai/the-batch/watermarking-is-a-no-go/?ref=dl-staging-website.ghost.io">Watermarking is a No-Go</a>, Andrew Ng is not optimistic about the adoption of watermarking. He explains how, in the current GenAI race, watermarking appears like a competitive disadvantage for AI companies.</p><h4>Using ML classifiers</h4><p>An alternative to watermarking would be to train a Machine Learning classifier that learns to label whether a content is AI-generated or human-generated.</p><p>Systems performing this task already exist, such as <a href="https://gptzero.me/?ref=the-batch-deeplearning-ai">GPTzero</a>. However they show a high error rate and fall short of offering a robust solution. Detecting AI-generated data proves to be a difficult task, even for machine learning models.</p><h4>A zero-shot approach</h4><p>Another approach discussed in the paper <a href="https://arxiv.org/abs/2301.11305">DetectGPT: Zero-Shot Machine-Generated Text Detection using Probability Curvature</a> (E. Mitchell et al., 2023) does not require any training and is based on observing the curvature of the log probability function of LLMs.</p><p>The criterion discovered by the authors is that AI-generated text tends to occupy regions with negative log probability curvature, as opposed to human-written text.</p><p>This seems like a promising technique, although we may have doubts concerning its scalability: it is not model-agnostic (it detects whether a content was generated by a specific LLM, not by any given LLM) and requires to have access to the model’s log probabilities.</p><h3>Conclusion</h3><p>We’ve learned about the importance of training generative models on human-generated data to avoid the decline of their performance. This poses a significant challenge, particularly as the Internet is their primary source of training data, and as more an more content online is AI-generated.</p><p>There are two approaches to address this issue: reversing the trend by promoting human content creation, and preventing models from being trained on synthetic data. However both solutions raise complex, open-ended questions. How can we incentivize online content creators to rely less on AI? How can we establish reliable, scalable methods for detecting AI-generated content?</p><p>On a promising note, the White House made a noteworthy <a href="https://www.whitehouse.gov/briefing-room/statements-releases/2023/07/21/fact-sheet-biden-harris-administration-secures-voluntary-commitments-from-leading-artificial-intelligence-companies-to-manage-the-risks-posed-by-ai/?utm_campaign=The%20Batch&amp;utm_source=hs_email&amp;utm_medium=email&amp;_hsenc=p2ANqtz-_KWnjJMok4p7lxxBJgIa1f-qA07jSWCt3GXAPWGm9rOoVgsUvfcPNMlM5GrOOOH3knocHJ">announcement</a> in July 2023. Seven major AI companies — Amazon, Anthropic, Google, Inflection, Meta, Microsoft, and OpenAI — agreed to respect a list of responsible-AI commitments which include watermarking. The future will reveal whether these commitments are upheld.</p><h4>To go further</h4><ul><li><a href="https://www.ai21.com/blog/human-or-not-results">Publication of AI21 Labs</a> where they analyze the results of their “Human or Not?” experiment and explain their methodology</li><li><a href="https://arxiv.org/abs/2303.12712">Sparks of Artificial General Intelligence: Early experiments with GPT-4</a>, a thorough investigation on GPT-4 and an interesting discussion about AGI, by a team of researchers at Microsoft</li><li><a href="https://www.deeplearning.ai/the-batch/watermarking-is-a-no-go/?ref=dl-staging-website.ghost.io">Watermarking is a No-Go</a>, a letter by Andrew Ng about how financial “incentives in the competitive market for generative AI make [watermarking] adoption challenging”</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=684dde2a150d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-happens-when-most-content-online-becomes-ai-generated-684dde2a150d">What Happens When Most Content Online Becomes AI-Generated?</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[4 ways to encode categorical features with high cardinality]]></title>
            <link>https://medium.com/data-science/4-ways-to-encode-categorical-features-with-high-cardinality-1bc6d8fd7b13?source=rss-50566ce7e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bc6d8fd7b13</guid>
            <category><![CDATA[categorical-data]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[high-cardinality]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[target-encoding]]></category>
            <dc:creator><![CDATA[Aicha Bokbot]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 15:18:33 GMT</pubDate>
            <atom:updated>2023-09-12T14:13:09.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>4 Ways to Encode Categorical Features with High Cardinality — with Python Implementation</h3><h4>Learn to apply target encoding, count encoding, feature hashing and Embedding using scikit-learn and TensorFlow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aEXyWbbzYXxPfQz0" /><figcaption>“Click” — Photo by <a href="https://unsplash.com/@cleovermij?utm_source=medium&amp;utm_medium=referral">Cleo Vermij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will go through 4 popular methods to encode categorical variables with high cardinality: <strong>(1) Target encoding, (2) Count encoding, (3) Feature hashing </strong>and <strong>(4) Embedding</strong>.</p><p>We will explain how each method works, discuss its pros and cons and observe its impact on the performance of a classification task.</p><h4><strong>Table of content</strong></h4><p>— <a href="#8744">Introducing categorical features</a><br> <em>(1) </em><a href="#2429"><em>Why do we need to encode categorical features?</em></a><em><br> (2) </em><a href="#b13b"><em>Why one-hot encoding is not suited to high cardinality?</em></a><br> — <a href="#706a">Application on an AdTech dataset</a><br> — <a href="#a959">Overview of each encoding method</a><br> <em>(1) </em><a href="#ffbc"><em>Target encoding</em></a><em><br> (2) </em><a href="#fbd1"><em>Count encoding</em></a><em><br> (3) </em><a href="#e278"><em>Feature hashing</em></a><em><br> (4) </em><a href="#99d8"><em>Embedding</em></a><br> — <a href="#892c">Benchmarking the performance to predict CTR</a><br> — <a href="#033c">Conclusion</a><br> — <a href="#3bd1">To go further</a></p><h3><strong>Introducing categorical features</strong></h3><p><strong>Categorical features</strong> are a type of variables that describe categories or groups (e.g. gender, color, country), as opposed to <strong>numerical features</strong> that measure a quantity (e.g. age, height, temperature).</p><p>There are two types of categorical data: <strong>ordinal features </strong>which categories can be ranked and sorted (e.g. sizes of T-shirt or restaurant ratings from 1 to 5 star) and <strong>nominal features</strong> which categories don’t imply any meaningful order (e.g. name of a person, of a city).</p><h4>Why do we need to encode categorical features?</h4><p>Encoding a categorical variable means finding a mapping that converts a category to a numerical value.</p><p>While some algorithms can work with categorical data directly (like decision trees), <strong>most machine learning models cannot handle categorical features</strong> and were designed to operate with numerical data only. Encoding categorical variables is a necessary step.</p><p>Besides, some machine learning libraries require all data to be numerical. This is the case of scikit-learn for example.</p><h4>Why one-hot encoding is not suited to high cardinality?</h4><p>A common approach to encoding categorical features is to apply <strong>one-hot encoding</strong>. This method encodes categorical variables by adding one binary variable for each unique category.</p><p>If a feature describing colors has three categories [red, blue, green], a one-hot encoder would transform it into three binary variables, one for each category.</p><p>If a categorical feature has hundreds or thousands of categories, applying one-hot encoding would add hundreds or thousands of binary variables to the features vector. Models struggles with large sparse data as they face the the <a href="https://www.quora.com/What-is-the-curse-of-dimensionality">curse of dimensionality</a>: it is more difficult to search in a solution space with more dimensions, easier to overfit, computational time is increased, as well as space complexity.</p><p>So how to to encode highly cardinal categorical features without increasing the dimensionality of feature vectors?</p><h3>Application on an AdTech dataset</h3><p>We will answer that question by applying four encoding techniques on the dataset of <a href="https://www.kaggle.com/competitions/criteo-display-ad-challenge/data"><strong>Criteo’s Display Advertising Challenge</strong></a> to predict click-through rates on display ads.</p><p>It is a famous Kaggle challenge launched in 2014 by <strong>Criteo</strong>, a French online advertising company specialized in programmatic advertising and real time bidding. <strong>Click through rate (CTR)</strong> of an ad is the number of times it was clicked divided by the number of times it was displayed on a page.</p><p><strong>Datasets in AdTech usually contain ID variables with high cardinality</strong>, such as <em>site_id</em> (ID of the website on which an ad is displayed), <em>advertiser_id</em> (ID of the brand behind the ad), <em>os_id</em> (ID of operating system of the user for whom the ad is displayed).</p><p>The <strong>Criteo dataset consists of 1 million rows, 39 anonymized columns</strong>: 13 numerical variables and 26 categorical variables. Their cardinality is in the table below. We see that <strong>many features have very high cardinalities (above 10k)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUoiECPiYhCnBO3Rsyhz3g.png" /><figcaption>Cardinaliy of categorical features in the Criteo dataset</figcaption></figure><p>The dataset contains 241,338 categories overall. <strong>Applying one hot encoding would mean transforming the feature space from 39 dimensions to 241,351 dimensions. </strong>It is clear that applying computations to a sparse matrix of over 241k columns is very costly and inefficient.</p><p>Let us split the dataset into training and testing set and explore the encoding methods.</p><pre>from sklearn.model_selection import train_test_split<br><br>features = df.columns[1:]<br>categorical_features = [feature for feature in features if feature[0] == &quot;C&quot; ]<br>x_train, x_test, y_train, y_test = train_test_split(df[features], df[&quot;label&quot;])</pre><h3>Overview of each encoding method</h3><h4>(1) Target encoding</h4><p>We use the target encoder of the library <a href="https://contrib.scikit-learn.org/category_encoders/targetencoder.html">category_encoder</a>, which is defined as follows:</p><blockquote>Features are replaced with a blend of the expected value of the target given particular categorical value and the expected value of the target over all the training data.</blockquote><pre>from category_encoders.target_encoder import TargetEncoder<br><br>enc = TargetEncoder(cols = categorical_features).fit(x_train, y_train)<br>X_train_encoded = enc.transform(x_train)<br>X_test_encoded = enc.transform(x_test)</pre><p>Note that we only fit the encoder on the training dataset and then use the fitted encoder to transform both training and testing set. As we do not have access to y_test in real life, it would be cheating to use it to fit the encoder.</p><ul><li><strong>DIMENSION OF ENCODED FEATURES SPACE: </strong>39 columns, X_train_encoded and X_test_encoded have the same shape as x_train and y_train.</li><li><strong>PROS: <br>- </strong>parameter free<br>- no increase in feature space</li><li><strong>CONS: <br>- </strong>risk of <em>target leakage</em> (target leakage means using some information from target to predict the target itself)<br>- When categories have few samples, the target encoder would replace them by values very close to the target which makes the model prone to overfitting the training set<br>- does not accept new values in testing set</li></ul><h4>(2) Count encoding</h4><p>With count encoding, <strong>also called Frequency encoding</strong>, categories are replaced by their frequency in the dataset. If the ID <em>3f4ec687</em> appears 957 times in the column C7, then we would replace the <em>3f4ec687 </em>by 957.</p><p>If two categories appear the same amount of times in the dataset, such a method encodes them with the same value although they do not hold the same information. This <strong>creates what we call a collision</strong>: two distinct categories are encoded with the same value.</p><pre>from category_encoders.count import CountEncoder<br><br>enc = CountEncoder(cols = categorical_features).fit(x_train, y_train)<br>X_train_encoded = enc.transform(x_train)<br>X_test_encoded = enc.transform(x_test)</pre><ul><li><strong>DIMENSION OF ENCODED FEATURES SPACE: </strong>39 columns, X_train_encoded and X_test_encoded have the same shape as x_train and y_train.</li><li><strong>PROS:</strong> <br>- easy to understand and implement<br>- parameter free<br>- no increase in feature space</li><li><strong>CONS:</strong> <br>- risk of information loss when collision happens<br>- can be too simplistic (the only information we keep from the categorical features is their frequency)<br>- does not accept new values in testing set</li></ul><h4>(3) Feature hashing</h4><p>Feature hashing <strong>projects categorical features into a feature vector of fixed dimension </strong>that is smaller than the original feature space. The dimension of that feature vector needs to be defined beforehand. This is done by using the <strong>hashing trick which applies a hash function to the features </strong>and uses their hash values as indices in the feature vector.</p><p>There are <strong>two ways to implement feature hashing</strong>:</p><ul><li>either we <strong>apply hashing feature by feature </strong>(there one feature space per feature and we therefore need to choose one dimension parameter per feature)</li><li>or <strong>we hash all features together </strong>(there one single feature space for all features, one parameter to choose, but collisions can happen between features).</li></ul><p>This method is not parameter free, we need to choose the size of the hashing space. We follow the advice of the great article <a href="https://booking.ai/dont-be-tricked-by-the-hashing-trick-192a6aae3087">Don’t get tricked by the hashing trick</a> and choose the hashing size = 20*<em>k</em> where <em>k</em> is the number of categorical features (in our case <em>k</em>=26).</p><pre>from category_encoders.hashing import HashingEncoder<br><br>enc = HashingEncoder(<br>    cols = categorical_features, <br>    n_components=20*len(categorical_features)<br>).fit(x_train, y_train)<br>X_train_encoded = enc.transform(x_train)<br>X_test_encoded = enc.transform(x_test)</pre><ul><li><strong>DIMENSION OF ENCODED FEATURES SPACE: </strong>533 columns</li><li><strong>PROS:</strong> <br>- limited increase of feature space (as compared to one hot encoding)<br>- does not grow in size and accepts new values during inference as it does not maintain a dictionary of observed categories<br>- captures interactions between features when feature hashing is applied on all categorical features combined to create a single hash</li><li><strong>CONS:</strong> <br>- need to tune the parameter of hashing space dimension<br>- risk of collision when the dimension of hashing space is not big enough</li></ul><h4>(4) Embedding</h4><p>Embeddings is a popular encoding technique from Deep Learning and natural language processing (NLP). It consists on <strong>building a trainable lookup table that maps categories to a a fixed-length vector representation</strong>. During the training, the weights in the table are updated to better describe the similarities between categories.</p><p>We will follow this <a href="https://keras.io/examples/structured_data/classification_with_tfdf/#experiment-3-decision-forests-with-trained-embeddings">Keras tutorial</a> to “<strong>build an encoder model that codes the categorical features to embeddings</strong>, where the size of the embedding for a given categorical feature is the square root to the size of its vocabulary. We train these embeddings in a simple NN model through back-propagation.”</p><pre>import tensorflow as tf<br><br>def build_input_layers(features):<br>    input_layers = {}<br>    for feature in features:<br>        if feature in categorical_features:<br>            input_layers[feature] = tf.keras.layers.Input(<br>                shape=(1,),<br>                name=feature,<br>                dtype=tf.string<br>            )<br>        else:<br>            input_layers[feature] = tf.keras.layers.Input(<br>                shape=(1,),<br>                name=feature,<br>                dtype=tf.float32<br>            )<br>    return input_layers<br><br>def build_embeddings(size=None):<br>    input_layers = build_input_layers(features)<br>    embedded_layers = []<br>    <br>    for feature in input_layers.keys():<br>        if feature in categorical_features:<br>            # Get the vocabulary of the categorical feature<br>            vocabulary = sorted(<br>                    [str(value) for value in list(x_train[feature].unique())]<br>                )<br>            # convert the string input values into integer indices<br>            cardinality = x_train[feature].nunique()<br>            pre_processing_layer = tf.keras.layers.StringLookup(<br>              vocabulary=vocabulary, <br>              num_oov_indices=cardinality,<br>              name=feature+&quot;_preprocessed&quot;<br>            )<br>            pre_processed_input = pre_processing_layer(input_layers[feature])<br>            # Create an embedding layer with the specified dimensions<br>            embedding_size = int(math.sqrt(cardinality))<br>            embedding_layer = tf.keras.layers.Embedding(<br>                input_dim=2*cardinality+1,<br>                output_dim=embedding_size,<br>                name=feature+&quot;_embedded&quot;,<br><br>            )<br>            embedded_layers.append(embedding_layer(pre_processed_input))   <br>        else:<br>            # return numerical feature as it is<br>            embedded_layers.append(input_layers[feature])<br>    <br>    # Concatenate all the encoded features.<br>    encoded_features = tf.keras.layers.Concatenate()([<br>                tf.keras.layers.Flatten()(layer) for layer in embedded_layers<br>            ])<br>    <br>    # Apply dropout.<br>    encoded_features = tf.keras.layers.Dropout(rate=0.25)(encoded_features)<br><br>    # Perform non-linearity projection.<br>    encoded_features = tf.keras.layers.Dense(<br>        units=size if size else encoded_features.shape[-1], activation=&quot;gelu&quot;<br>    )(encoded_features)<br>    return tf.keras.Model(inputs=input_layers, outputs=encoded_features)<br><br>def build_neural_network_model(embedding_encoder):<br>    input_layers = build_input_layers(features)<br>    embeddings = embedding_encoder(input_layers)<br>    output = tf.keras.layers.Dense(units=1, activation=&quot;sigmoid&quot;)(embeddings)<br><br>    model = keras.Model(inputs=input_layers, <br>                        outputs=output)<br>    <br>    model.compile(<br>        optimizer=tf.keras.optimizers.Adam(),<br>        loss=tf.keras.losses.BinaryCrossentropy(),<br>        metrics=[tf.keras.metrics.AUC()]<br>    )<br>    <br>    return model<br><br>embedding_encoder = build_embeddings(64)<br>neural_network_model = build_neural_network_model(embedding_encoder)<br><br># Training<br>def build_dataset(x, y):<br>    dataset = {}<br>    for feat in features:<br>        if feat in categorical_features:<br>            dataset[feat] = np.array(x[feat]).reshape(-1,1).astype(str)<br>        else:<br>            dataset[feat] = np.array(x[feat]).reshape(-1,1).astype(float)<br><br>    return dataset, np.array(y).reshape(-1,1)<br><br>x_train, y_train = build_dataset(x_train, y_train)<br>x_test, y_test = build_dataset(x_test, y_test)<br>history = neural_network_model.fit(x_train, y_train, batch_size=1024, epochs=5)<br><br>X_train_encoded = embedding_encoder.predict(x_train, batch_size=1024)<br>X_test_encoded = embedding_encoder.predict(x_test, batch_size=1024)</pre><ul><li><strong>DIMENSION OF ENCODED FEATURES SPACE: </strong>64 columns</li><li><strong>PROS:</strong> <br>- limited increase of feature space (as compared to one hot encoding)<br>- accepts new values during inference<br>- captures interactions between features and learns the similarities between categories</li><li><strong>CONS:</strong> <br>- need to tune the parameter of embedding size<br>- the embeddings and a logistic regression model cannot be trained synergically in one phase, since logistic regression do not train with backpropagation. Rather, embeddings has to be trained in an initial phase, and then used as static inputs to the decision forest model.</li></ul><h3>Benchmarking the performance to predict CTR</h3><p>We fit a simple logistic regression to predict the CTR and generate predictions with each encoding method.</p><pre>from sklearn.linear_model import LogisticRegression<br>model = LogisticRegression(max_iter=10000)<br>model.fit(X_train_encoded, y_train)<br>y_pred = model.predict(X_test_encoded)</pre><p>We compute the log loss, AUC, recall and average of the predict CTR. The results are in the table below. <strong>The</strong> <strong>average CTR in the dataset is 22.6%.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*rdlaqK8A8TvRh5cClFLK1Q.png" /></figure><p>We first notice that the AUC is pretty low for all encoding methods, which is mostly due to the fact that we used a very simple model, a more complex model than Logistic Regression would be more suited for this task.</p><p>The first three methods (target, count and hashing encoding) <strong>did not allow the model to capture enough signals to predict the CTR</strong>: the average predicted CTR is very low compared to the true average, the recall is also very close to zero and the AUC close 0.5 informs us that the model is almost random. The <strong>model with embedding shows the highest AUC and recall</strong>, and an average predicted CTR close to the target.</p><h3>Conclusion</h3><p>We’ve explored four techniques to encode categorical data with high cardinality: target encoding, count encoding, feature hashing and embedding. Specifically, we learned:</p><ul><li>The challenge of working with high-cardinality categorical data</li><li>The advantages and limitations of each of the four techniques</li><li>How to implement each technique as part of a classification task to predict Click Trough Rate</li></ul><h3>To go further</h3><ul><li>Notebook with the code in this article: <a href="https://www.kaggle.com/aichabokbot/encoding-high-cardinality-categorical-features">Encoding high cardinality categorical features</a></li><li>Cheat-sheet on how to choose the most relevant encoding technique: <a href="https://innovation.alteryx.com/encode-smarter/">Encode Smarter: How to Easily Integrate Categorical Encoding into Your Machine Learning Pipeline</a></li><li>More on the concept of collision: <a href="https://booking.ai/dont-be-tricked-by-the-hashing-trick-192a6aae3087">Don’t be tricked by the Hashing Trick</a></li><li>More on categorical embedding: <a href="https://www.kaggle.com/code/dustyturner/dense-nn-with-categorical-embeddings">Dense NN with Categorical Embeddings</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bc6d8fd7b13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/4-ways-to-encode-categorical-features-with-high-cardinality-1bc6d8fd7b13">4 ways to encode categorical features with high cardinality</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>