<?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 Federico Bianchi on Medium]]></title>
        <description><![CDATA[Stories by Federico Bianchi on Medium]]></description>
        <link>https://medium.com/@fede-bianchi?source=rss-2aff872fe60e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tLPtXZ4rbHi1ld4mG8FL1A.jpeg</url>
            <title>Stories by Federico Bianchi on Medium</title>
            <link>https://medium.com/@fede-bianchi?source=rss-2aff872fe60e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:27:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fede-bianchi/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[A Foundation Model for Medical AI]]></title>
            <link>https://medium.com/data-science/a-foundation-model-for-medical-ai-7b97e3ab3893?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b97e3ab3893</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 07:10:13 GMT</pubDate>
            <atom:updated>2023-09-19T15:31:11.235Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introducing PLIP, a foundation model for pathology</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsF94d9Si6SYN1IpOuaVCQ.jpeg" /><figcaption>Photo by Tara Winstead: <a href="https://www.pexels.com/photo/person-reaching-out-to-a-robot-8386434/">https://www.pexels.com/photo/person-reaching-out-to-a-robot-8386434/</a></figcaption></figure><h4>Introduction</h4><p>The ongoing AI revolution is bringing us innovations in all directions. OpenAI GPT(s) models are leading the development and showing how much foundation models can actually make some of our daily tasks easier. From helping us write better to streamlining some of our tasks, every day we see new models being announced.</p><p>Many opportunities are opening up in front of us. AI products that can help us in our work life are going to be one of the most important tools we are going to get in the next years.</p><p>Where are we going to see the most impactful changes? Where can we help people accomplish their tasks faster? One of the most exciting avenues for AI models is the one that brings us to Medical AI tools.</p><p>In this blog post, I describe <a href="https://github.com/PathologyFoundation/plip"><strong>PLIP</strong></a> (Pathology Language and Image Pre-Training) as one of the first foundation models for pathology. PLIP is a vision-language model that can be used to embed images and text in the same vector space, thus allowing multi-modal applications. PLIP is derived from the original <a href="https://openai.com/research/clip">CLIP</a> model proposed by OpenAI in 2021 and has been recently published in Nature Medicine:</p><p>Huang, Z., Bianchi, F., Yuksekgonul, M., Montine, T., Zou, J., <a href="https://rdcu.be/djLSK"><strong>A visual–language foundation model for pathology image analysis using medical Twitter.</strong></a><strong> </strong>2023, Nature Medicine.</p><p>Some useful links before starting our adventure:</p><ul><li><a href="https://huggingface.co/vinid/plip">HuggingFace Weights</a>;</li><li><a href="https://rdcu.be/djLSK">Nature Medicine Paper</a>;</li><li><a href="https://github.com/PathologyFoundation/pathology-language-image-pretraining/">GitHub Repository</a>.</li></ul><p>All images, unless otherwise noted, are by the author.</p><h3>Contrastive Pre-Training 101</h3><p>We show that, through the use of data collection on social media and with some additional tricks, we can build a model that can be used in Medical AI pathology tasks with good results — and without the need for annotated data.</p><p>While introducing CLIP (the model from which PLIP is derived) and its contrastive loss is a bit out of the scope of this blog post, it is still good to get a first intro/refresher. The very simple idea behind CLIP is that we can build a model that puts images and text in a vector space in which “images and their descriptions are going to be close together”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmWkwM3prULZ8_Tjuw6acA.gif" /><figcaption>A contrastive model — like PLIP/CLIP — puts images and text in the same vector space to be compared. The description in the yellow box matches the image in the yellow box and thus they are also close in the vector space.</figcaption></figure><p>The GIF above also shows an example of how a model that embeds images and text in the same vector space can be used for classification: by putting everything in the same vector space we can associate each image with one or more labels by considering the distance in the vector space: the closer the description is to the image, the better. We expect the closest label to be the real label of the image.</p><p>To be clear: Once CLIP is trained you can embed <strong>any</strong> image or <strong>any</strong> text you have. Consider that this GIF shows a 2D space, but in general, the spaces used in CLIP are of much higher dimensionality.</p><p>This means that once images and text are in the same vector spaces, there are many things we can do: from <em>zero-shot classification</em> (<strong>find which text label is more similar to an image</strong>) to <em>retrieval</em> (<strong>find which image is more similar to a given description</strong>).</p><p>How do we train CLIP? To put it simply, the model is fed with <strong>MANY</strong> image-text pairs and tries to put similar matching items close together (as in the image above) and all the rest far away. The more image-text pairs you have, the better the representation you are going to learn.</p><p>We will stop here with the CLIP background, this should be enough to understand the rest of this post. I have a more in-depth blog post about CLIP on Towards Data Science.</p><p><a href="https://towardsdatascience.com/how-to-train-your-clip-45a451dcd303">How to Train your CLIP</a></p><p>CLIP has been trained to be a very general image-text model, but it does not work as well for specific use cases (e.g., <a href="https://www.nature.com/articles/s41598-022-23052-9">Fashion</a> (Chia et al., 2022)) and there are also cases in which CLIP underperforms and domain-specific implementations perform better (Zhang et al., 2023).</p><h3>Pathology Language and Image Pre-Training (PLIP)</h3><p>We now describe how we built PLIP, our fine-tuned version of the original CLIP model that is specifically designed for Pathology.</p><h4>Building a Dataset for Pathology Language and Image Pre-Training</h4><p>We need data, and this data has to be good enough to be used to train a model. <strong>The question is how do we find these data?</strong> What we need is images with relevant descriptions — like the one we saw in the GIF above.</p><p>Although there is a significant amount of pathology data available on the web, it is often lacking annotations and it may be in non-standard formats such as PDF files, slides, or YouTube videos.</p><p>We need to look somewhere else, and this somewhere else is going to be social media. By leveraging social media platforms, we can potentially access a wealth of pathology-related content. Pathologists use social media to share their own research online and to ask questions to their fellow colleagues (see Isom et al., 2017, for a discussion on how pathologists use social media). There is also a <a href="https://www.symplur.com/healthcare-hashtags/ontology/pathology/">set</a> of generally recommended <strong>Twitter hashtags</strong> that pathologists can use to communicate.</p><p>In addition to Twitter data, we also collect a subset of images from the <strong>LAION dataset </strong>(Schuhmann et al., 2022), a vast collection of 5B image-text pairs. LAION has been collected by scraping the web and it is the dataset that was used to train many of the popular OpenCLIP models.</p><p><strong>Pathology Twitter</strong></p><p>We collect more than 100K tweets using pathology Twitter hashtags. The process is rather simple, we use the API to collect tweets that relate to a set of specific hashtags. We remove tweets that contain a question mark because these tweets often contain requests for other pathologies (e.g., “Which kind of tumor is this?”) and not information we might actually need to build our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6x_T7DzVYyEM3iYr5_XVA.jpeg" /><figcaption>We extract tweets with specific keywords and we remove sensitive content. In addition to this, we also remove all the tweets that contain question marks, which appear in tweets used by pathologists to ask questions to their colleagues about some possible rare cases.</figcaption></figure><p><strong>Sampling from LAION</strong></p><p>LAION contains 5B image-text pairs, and our plan to collect our data is going to be as follows: we can use our own images that come from Twitter and find similar images in this large corpus; in this way, we should be able to get reasonably similar images and hopefully, these similar images are also pathology images.</p><p>Now, doing this manually would be infeasible, embedding and searching over 5B embeddings is a very time-consuming task. Luckily there are pre-computed vector indexes for LAION that we can query with actual images using APIs! We thus simply embed our images and use K-NN search to find similar images in LAION. Remember, each of these images comes with a caption, something that is perfect for our use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpHpuYVo1135OzlGvwWcmw.jpeg" /><figcaption>Very simple setup of how we extend our dataset by using K-NN search on the LAION dataset. We start with our own image from our original corpus and then search for similar images on the LAION dataset. Each of the images we get comes with an actual caption.</figcaption></figure><p><strong>Ensuring Data Quality</strong></p><p>Not all the images we collect are good. For example, from Twitter, we collected lots of group photos from Medical conferences. From LAION, we sometimes got some fractal-like images that could vaguely resemble some pathology pattern.</p><p>What we did was very simple: we trained a classifier by using some pathology data as positive class data and ImageNet data as negative class data. This kind of classifier has an incredibly high precision (it’s actually easy to distinguish pathology images from random images on the web).</p><p>In addition to this, for LAION data we apply an English language classifier to remove examples that are not in English.</p><h4>Training Pathology Language and Image Pre-Training</h4><p>Data collection was the hardest part. Once that is done and we trust our data, we can start training.</p><p>To train PLIP we used the original OpenAI code to do training — we implemented the training loop, added a cosine annealing for the loss, and a couple of tweaks here and there to make everything ran smoothly and in a verifiable way (e.g. <a href="https://www.comet.com/">Comet ML</a> tracking).</p><p>We trained many different models (hundreds) and compared parameters and optimization techniques, Eventually, we were able to come up with a model we were pleased with. There are more details in the paper, but one of the most important components when building this kind of contrastive model is making sure that the batch size is as large as possible during training, this allows the model to learn to distinguish as many elements as possible.</p><h3>Pathology Language and Image Pre-Training for Medical AI</h3><p>It is now time to put our PLIP to the test. Is this foundation model good on standard benchmarks?</p><p>We run different tests to evaluate the performance of our PLIP model. The three most interesting ones are zero-shot classification, linear probing, and retrieval, but I’ll mainly focus on the first two here. I’ll ignore experimental configuration for the sake of brevity, but these are all available in the manuscript.</p><h4><strong>PLIP as a Zero-Shot Classifier</strong></h4><p>The GIF below illustrates how to do zero-shot classification with a model like PLIP. We use the dot product as a measure of similarity in the vector space (the higher, the more similar).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyCLuCSl_IdgxvpJWGeYvw.gif" /><figcaption>The process to do zero-shot classification. We embed an image and all the labels and find which labels are closer to the image in the vector space.</figcaption></figure><p>In the following plot, you can see a quick comparison of PLIP vs CLIP on one of the dataset we used for zero-shot classification. There is a significant gain in terms of performance when using PLIP to replace CLIP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVZoK-yHXUZ1ZyC4YlfLMA.jpeg" /><figcaption>PLIP vs CLIP performance (Weighted Macro F1) on two datasets for zero-shot classification. Note that y-axis stops at around 0.6 and not 1.</figcaption></figure><h4><strong>PLIP as a Feature Extractor for Linear Probing</strong></h4><p>Another way to use PLIP is as a feature extractor for pathology images. During training, PLIP sees many pathology images and learns to build vector embeddings for them.</p><p>Let’s say you have some annotated data and you want to train a new pathology classifier. You can extract image embeddings with PLIP and then train a logistic regression (or any kind of regressor you like) on top of these embeddings. This is an easy and effective way to perform a classification task.</p><p>Why does this work? The idea is that to train a classifier PLIP embeddings, being pathology-specific, should be better than CLIP embeddings, which are general purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lsnc5_pXBb8NVDImrvzv7A.jpeg" /><figcaption>PLIP Image Encoder allows us to extract a vector for each image and train an image classifier on top of it.</figcaption></figure><p>Here is an example of the comparison between the performance of CLIP and PLIP on two datasets. While CLIP gets good performance, the results we get using PLIP are much higher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6iqrjFrboY-EAihoBA0ow.jpeg" /><figcaption>PLIP vs CLIP performance (Macro F1) on two datasets for linear probing. Note that y-axis starts from 0.65 and not 0.</figcaption></figure><h3>Using Pathology Language and Image Pre-Training</h3><p>How to use PLIP? here are some examples of how to use PLIP in Python and a Streamlit demo you can use to play a bit with the mode.</p><h4>Code: APIs to Use PLIP</h4><p>Our GitHub repository offers a couple of additional examples you can follow. We have built an API that allows you to interact with the model easily:</p><pre>from plip.plip import PLIP<br>import numpy as np<br><br>plip = PLIP(&#39;vinid/plip&#39;)<br><br># we create image embeddings and text embeddings<br>image_embeddings = plip.encode_images(images, batch_size=32)<br>text_embeddings = plip.encode_text(texts, batch_size=32)<br><br># we normalize the embeddings to unit norm (so that we can use dot product instead of cosine similarity to do comparisons)<br>image_embeddings = image_embeddings/np.linalg.norm(image_embeddings, ord=2, axis=-1, keepdims=True)<br>text_embeddings = text_embeddings/np.linalg.norm(text_embeddings, ord=2, axis=-1, keepdims=True)</pre><p>You can also use the more standard HF API to load and use the model:</p><pre>from PIL import Image<br>from transformers import CLIPProcessor, CLIPModel<br><br>model = CLIPModel.from_pretrained(&quot;vinid/plip&quot;)<br>processor = CLIPProcessor.from_pretrained(&quot;vinid/plip&quot;)<br><br>image = Image.open(&quot;images/image1.jpg&quot;)<br><br>inputs = processor(text=[&quot;a photo of label 1&quot;, &quot;a photo of label 2&quot;],<br>                   images=image, return_tensors=&quot;pt&quot;, padding=True)<br><br>outputs = model(**inputs)<br>logits_per_image = outputs.logits_per_image <br>probs = logits_per_image.softmax(dim=1)  </pre><h4>Demo: PLIP as an Educational Tool</h4><p>We also believe PLIP and future models can be effectively used as educational tools for Medical AI. PLIP allows users to do zero-shot retrieval: a user can search for specific keywords and PLIP will try to find the most similar/matching image. We built a simple web app in Streamlit that you can find <a href="https://huggingface.co/spaces/vinid/webplip">here</a>.</p><h3>Conclusions</h3><p>Thanks for reading all of this! We are excited about the possible future evolutions of this technology.</p><p>I will close this blog post by discussing some very important limitations of PLIP and by suggesting some additional things I have written that might be of interest.</p><h4>Limitations</h4><p>While our results are interesting, PLIP comes with lots of different limitations. Data is not enough to learn all the complex aspects of pathology. We have built data filters to ensure data quality, but we need better evaluation metrics to understand what the model is getting right and what the model is getting wrong.</p><p>More importantly, PLIP does not solve the current challenges of pathology; PLIP is not a perfect tool and can make many errors that require investigation. The results we see are definitely promising and they open up a range of possibilities for future models in pathology that combine vision and language. However, there is still lots of work to do before we can see these tools used in everyday medicine.</p><h4>Miscellanea</h4><p>I have a couple of other blog posts regarding CLIP modeling and CLIP limitations. For example:</p><ul><li><a href="https://towardsdatascience.com/teaching-clip-some-fashion-3005ac3fdcc3">Teaching CLIP Some Fashion</a></li><li><a href="https://towardsdatascience.com/your-vision-language-model-might-be-a-bag-of-words-30b1beaef7f8">Your Vision-Language Model Might Be a Bag of Words</a></li></ul><h4>References</h4><p>Chia, P.J., Attanasio, G., Bianchi, F., Terragni, S., Magalhães, A.R., Gonçalves, D., Greco, C., &amp; Tagliabue, J. (2022). Contrastive language and vision learning of general fashion concepts. <em>Scientific Reports, 12</em>.</p><p>Isom, J.A., Walsh, M., &amp; Gardner, J.M. (2017). Social Media and Pathology: Where Are We Now and Why Does it Matter? <em>Advances in Anatomic Pathology</em>.</p><p>Schuhmann, C., Beaumont, R., Vencu, R., Gordon, C., Wightman, R., Cherti, M., Coombes, T., Katta, A., Mullis, C., Wortsman, M., Schramowski, P., Kundurthy, S., Crowson, K., Schmidt, L., Kaczmarczyk, R., &amp; Jitsev, J. (2022). LAION-5B: An open large-scale dataset for training next generation image-text models. <em>ArXiv, abs/2210.08402</em>.</p><p>Zhang, S., Xu, Y., Usuyama, N., Bagga, J.K., Tinn, R., Preston, S., Rao, R.N., Wei, M., Valluri, N., Wong, C., Lungren, M.P., Naumann, T., &amp; Poon, H. (2023). Large-Scale Domain-Specific Pretraining for Biomedical Vision-Language Processing. <em>ArXiv, abs/2303.00915</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b97e3ab3893" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-foundation-model-for-medical-ai-7b97e3ab3893">A Foundation Model for Medical AI</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[RecList 2.0: Open-Source Systematic Testing of ML Models]]></title>
            <link>https://medium.com/data-science/reclist-2-0-open-source-systematic-testing-of-ml-models-9c62b654170c?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c62b654170c</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[evaluation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 23:43:48 GMT</pubDate>
            <atom:updated>2023-08-09T00:21:55.856Z</atom:updated>
            <content:encoded><![CDATA[<h4>A new RecList to provide more flexibility and better support for evaluation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYsF9BHQYe06um-qf-9cAQ.jpeg" /><figcaption><a href="https://www.pexels.com/photo/black-telescope-under-blue-and-blacksky-2034892/">Photo by Lucas Pezeta</a></figcaption></figure><h3>Introduction</h3><p>Evaluation is a complex matter. It is often hard to manage the different components that are involved in writing evaluation pipelines, you have your model somewhere, you need to load it, then get the test, then run the tests, and so on and so forth.</p><p>And then? well, you have to save results somewhere and maybe log outputs online so you can keep track of them.</p><p>As this is always a hard procedure, we recently tried to provide a more structured way to do testing. In this blog post, we introduce and show how to use <a href="https://github.com/RecList/reclist">RecList</a> beta, our open-source package for evaluation; RecList is a general plug-and-play approach to scale-up testing, with an easy-to-extend interface for custom use cases. RecList is an open-source project freely available on <a href="https://github.com/RecList/reclist">GitHub</a>.</p><p>Reclist allows you to separate the evaluation portion of your code and encapsulate it in a class that handles several other things (e.g., storage and logging) automatically for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUAsDBkC74FB-5FzuYgobg.jpeg" /><figcaption>Reclist offers a simple way to systematize testing and save all the information you need after you trained your own model.</figcaption></figure><p>We started working on RecList a couple of years ago and the alpha version of RecList came out a bit more than a year ago. Since then, RecList has collected over 400 GitHub stars.</p><p>We have used RecList and stress-tested it to run a RecSys challenge at CIKM in 2022 and currently preparing for an upcoming one at KDD 2023. RecList allowed us to systematize the evaluation for all the participants. The idea is that, once everybody is provided with the same RecList, comparing different evaluations becomes easy. A summary of our experience appears in our <a href="https://www.nature.com/articles/s42256-022-00606-0">Nature Machine Intelligence</a> comment piece.</p><p>RecList was originally introduced in an academic paper, but we also had a general overview that was presented in a Towards Data Science publication you can read here:</p><p><a href="https://towardsdatascience.com/ndcg-is-not-all-you-need-24eb6d2f1227">NDCG Is Not All You Need</a></p><blockquote>Chia, P. J., Tagliabue, J., Bianchi, F., He, C., &amp; Ko, B. (2022, April). Beyond nDCG: Behavioral Testing of Recommender Systems with Reclist. In <em>Companion Proceedings of the Web Conference 2022</em> (pp. 99–104).</blockquote><p>While we originally designed RecList for recommender system testing, nothing prevents using RecList for testing other machine learning models. So, why there is a new blog post? well, after developing the first version we realized it needed some updates.</p><h4>What Did We Learn: Rethinking an API</h4><p>It is often only after you build something that you realize how to improve it.</p><p>For those that used RecList 1.0, we have made major updates to the RecList API. Originally, we had harder constraints on code structure and input/output pairs.</p><p>Indeed, when we implemented Reclist we intended to provide a more general API for the evaluation of Recommender Systems that offered several out-of-the-box functionalities. However, to do this we had to create several abstract interfaces that users had to implement.</p><p>For example, the <strong>original Reclist 1.0</strong> required users to wrap their own models and dataset into pre-defined abstract classes (i.e., RecModel and RecDataset). This allowed us to implement a common set of behaviors that were connected by these abstractions. However, we soon realized that this might often complicate flows and requires a lot of additional work that some people might not like.</p><p>In <strong>RecList 2.0</strong> we decided to make these constraints optional: we made testing much more flexible. Users define their own evaluation use case, wrap it around a handy decorator, and they get metadata storage and logging already implemented. Users can then share the test interface with other people and they can run your very same experiments.</p><p><strong>Summary of this</strong>: we realized how important flexibility is when we build software that other people have to use.</p><h3>RecList 2.0 In Action</h3><p>Now, let’s explore a simple use case on how to use RecList to write and run an evaluation pipeline. We are going to use very simple models that output numbers at random to reduce the complexity that is involved in making a machine learning project.</p><h4>A Simple Use Case</h4><p>Let’s create a very simple use case with a very simple dataset. Let’s assume we have a target sequence of integers, each with an associated category. We are simply going to generate some random data.</p><pre>n = 10000<br><br>target = [randint(0, 1) for _ in range(n)]<br>metadata = {&quot;categories&quot;: [choice([&quot;red&quot;, &quot;blue&quot;, &quot;yellow&quot;]) <br>                          for _ in range(n)]}</pre><p>Our very simple dataset should look something like this:</p><pre>&gt;&gt;&gt; target<br><br>[0, 1, 0, 1, 1, 0]<br><br>&gt;&gt;&gt; metadata<br><br>{&quot;categories&quot; : [&quot;red&quot;, &quot;blue&quot;, &quot;yellow&quot;, &quot;blue&quot;, &quot;yellow&quot;, &quot;yellow&quot;]}</pre><h4>A Simple Model</h4><p>Let’s now assume we have a DummyModel that outputs integers at random. Of course, as we said, this is not a “good” model, but it’s a good abstraction we can use to see an entire evaluation pipeline.</p><pre>class DummyModel:<br>  def __init__(self, n):<br>          self.n = n<br><br>      def predict(self):<br>          from random import randint<br>          return [randint(0, 1) for _ in range(self.n)]<br><br>simple_model = DummyModel(n)<br><br># let&#39;s run some predictions<br>predictions = simple_model.predict()</pre><p>Now, how do we run evaluations?</p><h4>A Simple RecList</h4><p>A RecList is a Python class that inherits functionalities from our RecList abstract class. RecList implements RecTests, simple abstractions that allow you to systematize evaluation. For example, this could be a possible accuracy test.</p><pre>@rec_test(test_type=&quot;Accuracy&quot;, display_type=CHART_TYPE.SCALAR)<br>def accuracy(self):<br>    &quot;&quot;&quot;<br>    Compute the accuracy<br>    &quot;&quot;&quot;<br>    from sklearn.metrics import accuracy_score<br><br>    return accuracy_score(self.target, self.predictions)</pre><p>We are taking sklearn accuracy metric and wrapping it in another method. What makes this different from a simple accuracy function? well, the decorator allows us to bring over some additional features: for example, the rectest will <strong>now automatically store information in a local folder</strong>. Also, defining a type of chart<strong> allows us to create some visualizations for these results.</strong></p><p>What if we wanted a more sophisticated test? For example, what if we want to see how stable is our accuracy across the different categories (e.g., is the accuracy computed on red objects higher than for yellow objects?)</p><pre>@rec_test(test_type=&quot;SlicedAccuracy&quot;, display_type=CHART_TYPE.SCALAR)<br>def sliced_accuracy_deviation(self):<br>    &quot;&quot;&quot;<br>    Compute the accuracy by slice<br>    &quot;&quot;&quot;<br>    from reclist.metrics.standard_metrics import accuracy_per_slice<br>    <br>    return accuracy_per_slice(<br>        self.target, self.predictions, self.metadata[&quot;categories&quot;])</pre><p>Let’s now look at an example of a complete RecList!</p><pre>class BasicRecList(RecList):<br><br>    def __init__(self, target, metadata, predictions, model_name, **kwargs):<br>        super().__init__(model_name, **kwargs)<br>        self.target = target<br>        self.metadata = metadata<br>        self.predictions = predictions<br><br>    @rec_test(test_type=&quot;SlicedAccuracy&quot;, display_type=CHART_TYPE.SCALAR)<br>    def sliced_accuracy_deviation(self):<br>        &quot;&quot;&quot;<br>        Compute the accuracy by slice<br>        &quot;&quot;&quot;<br>        from reclist.metrics.standard_metrics import accuracy_per_slice<br><br>        return accuracy_per_slice(<br>            self.target, self.predictions, self.metadata[&quot;categories&quot;]<br>        )<br><br>    @rec_test(test_type=&quot;Accuracy&quot;, display_type=CHART_TYPE.SCALAR)<br>    def accuracy(self):<br>        &quot;&quot;&quot;<br>        Compute the accuracy<br>        &quot;&quot;&quot;<br>        from sklearn.metrics import accuracy_score<br><br>        return accuracy_score(self.target, self.predictions)<br><br>    @rec_test(test_type=&quot;AccuracyByCountry&quot;, display_type=CHART_TYPE.BARS)<br>    def accuracy_by_country(self):<br>        &quot;&quot;&quot;<br>        Compute the accuracy by country<br>        &quot;&quot;&quot;<br>        # TODO: note that is a static test, <br>        # used to showcase the bin display<br><br>        from random import randint<br>        return {&quot;US&quot;: randint(0, 100), <br>                &quot;CA&quot;: randint(0, 100), <br>                &quot;FR&quot;: randint(0, 100)}</pre><p>Few lines of code are needed to put all we need in one single place. We can reuse this piece of code for new models, or add tests and re-run past models.</p><p>As long as your metrics return some values, you can implement them in any way you like. For example, this BasicRecList evaluates a specific model in a specific context. But nothing prevents you from generating more model-specific reclists (e.g., GPT-RecList) or dataset-specific reclists (e.g., IMDB-Reclist). If you want to see an example of a deep model on RecList, you can <a href="https://colab.research.google.com/drive/1Ftl2B7BVFMfFjyjWweFCP_gA_LdCl7-a?usp=sharing">check out this colab</a>.</p><h4>Running and Getting The Outputs</h4><p>Let’s run the RecList. We need our target data, the metadata, and the predictions. We can also specify a logger and a metadata store.</p><pre>rlist = BasicRecList(<br>    target=target,<br>    metadata=metadata,<br>    predictions=predictions,<br>    model_name=&quot;myRandomModel&quot;,<br>)<br><br># run reclist<br>rlist(verbose=True)</pre><p>What’s the output of this procedure? What we are going to see in our command line is the following set of results: for each test, we have an actual score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPkE9QlUtIlhIMDYeyvxkA.png" /></figure><p>The metrics are also automatically plotted. For example, the AccuracyByCountry should show something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0staWKkUWeg1E8mKc0r5YA.png" /><figcaption>Example of plot generated by a RecTest.</figcaption></figure><p>In addition to this, RecList saves a JSON file that contains all the information from the experiments we have just run:</p><pre>{<br>  &quot;metadata&quot;: {<br>    &quot;model_name&quot;: &quot;myRandomModel&quot;,<br>    &quot;reclist&quot;: &quot;BasicRecList&quot;,<br>    &quot;tests&quot;: [<br>      &quot;sliced_accuracy&quot;,<br>      &quot;accuracy&quot;,<br>      &quot;accuracy_by_country&quot;<br>    ]<br>  },<br>  &quot;data&quot;: [<br>    {<br>      &quot;name&quot;: &quot;SlicedAccuracy&quot;,<br>      &quot;description&quot;: &quot;Compute the accuracy by slice&quot;,<br>      &quot;result&quot;: 0.00107123176804103,<br>      &quot;display_type&quot;: &quot;CHART_TYPE.SCALAR&quot;<br>    },<br>...<br>}</pre><p>The nice thing is that with a few lines of additional code, most of the logging is taken care of for us!</p><h4>Using Online Loggers and Metadata Storages</h4><p>By default, the RecList runner is going to use the following logger and metadata setup.</p><pre>logger=LOGGER.LOCAL,<br>metadata_store= METADATA_STORE.LOCAL,</pre><p>However, nothing prevents us from using online and cloud solutions. For example, we wrap around both CometML and Neptune APIs so that you can directly use them in your evaluation pipeline. We also offer support for S3 data storage.</p><p>For example, adding a couple of parameters to the BasicReclist will allow us to log information on <a href="https://www.loom.com/share/e2db2a15d77741f08fc84e2284bed8e2?sid=83290789-98d3-4d3e-9271-2f8e91d980e9">Neptune</a> (we offer similar support for <a href="https://www.loom.com/share/870d1b256a0e4bd18b98f5f7c9a78759?sid=3161eb5b-5ab1-4863-ba50-373757d5e0cc">Comet.ml</a>)!</p><pre>rlist = BasicRecList(<br>    target=target,<br>    model_name=&quot;myRandomModel&quot;,<br>    predictions=predictions,<br>    metadata=metadata,<br>    logger=LOGGER.NEPTUNE,<br>    metadata_store= METADATA_STORE.LOCAL,<br>    NEPTUNE_KEY=os.environ[&quot;NEPTUNE_KEY&quot;],<br>    NEPTUNE_PROJECT_NAME=os.environ[&quot;NEPTUNE_PROJECT_NAME&quot;],<br>)<br><br># run reclist<br>rlist(verbose=True)</pre><p>In a very similar way, adding the following:</p><pre>bucket=os.environ[&quot;S3_BUCKET&quot;]</pre><p>will allow us to use an S3 Bucket to store metadata (of course, you will need to set some environment keys even for this).</p><h3>Conclusion</h3><p>That’s all! We have created RecList to make the evaluation in Recommender Systems more systematic and organized. We hope this large API refactoring can help people build more reliable evaluation pipelines!</p><h4>Acknowledgments</h4><p>Between June and December 2022, the development of our beta has been supported by the awesome folks at Comet, Neptune, Gantry, and developed with the help of Unnati Patel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c62b654170c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reclist-2-0-open-source-systematic-testing-of-ml-models-9c62b654170c">RecList 2.0: Open-Source Systematic Testing of ML Models</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[Your Vision-Language Model Might Be a Bag of Words]]></title>
            <link>https://medium.com/data-science/your-vision-language-model-might-be-a-bag-of-words-30b1beaef7f8?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/30b1beaef7f8</guid>
            <category><![CDATA[vision]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 13:44:34 GMT</pubDate>
            <atom:updated>2023-03-23T19:08:26.453Z</atom:updated>
            <content:encoded><![CDATA[<h4>We explore the limits of what vision-language models get about language in our Oral Paper at ICLR 2023</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGMde9uuUeHNIRShrkBRSA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/photo/code-projected-over-woman-3861969/">ThisIsEngineering</a>.</figcaption></figure><p>Multimodal AI is the talk of the town. With the recent release of GPT-4, we are seeing myriads of new possible applications and future technologies that were unthinkable six months ago. Indeed, vision-language models in general are very useful for many different tasks. For example, with <a href="https://github.com/openai/CLIP">CLIP</a> you can do zero-shot image classification on unseen datasets, often getting reliable performance without the need of training anything.</p><p>At the same time, vision-language models are also not perfect. Here, we explore the limits of these models, highlighting where and why they might fail. This blog post is a short/high-level description of our recent paper that will be presented as an <a href="https://openreview.net/forum?id=KRLUvxh8uaX">ICLR 2023 oral</a>. If you want to take a look at the code, just click <a href="https://github.com/mertyg/vision-language-models-are-bows">here</a>.</p><blockquote>Yuksekgonul, M., Bianchi, F., Kalluri, P., Jurafsky, D., &amp; Zou, J. (2023). When and why vision-language models behave like bags-of-words, and what to do about it?. ICLR.</blockquote><h3>Introduction</h3><h4><strong>What’s a vision-language model?</strong></h4><p>Vision-Language models have revolutionized the field by leveraging the synergy between visual and linguistic data to perform various tasks. While many vision-language models have been introduced in the literature, CLIP is the most well-known and widely adopted model.</p><p>Through the embedding of images and captions in the same vector space, CLIP allows cross-modal reasoning, enabling users to perform tasks such as zero-shot image classification, and text-to-image retrieval with good accuracy. CLIP uses a contrastive learning approach to learn embeddings for images and captions.</p><h4>A short introduction to contrastive learning</h4><p>Contrastive learning makes it so that CLIP can learn to associate images with their corresponding captions by minimizing the distance between them in a shared vector space. This approach has proven highly effective, as demonstrated by the impressive results achieved by CLIP and other contrastive-based models.</p><p>Contrastive loss is used to compare pairs of images and captions in a batch and optimizes the model to maximize the similarity between embeddings of matching image-text pairs and to decrease the similarity between other pairs in the batch.</p><p>An example of a possible batch and training step is seen in the image below:</p><ul><li><strong>Purple squares</strong> contain embeddings for all the captions, and <strong>green squares</strong> contain embeddings for all the images.</li><li>The squares of the matrix contain the dot product (read as “cosine similarity”, since the embeddings are normalized) of all the image embeddings in the batch and all the text embeddings.</li><li><strong>Blue squares</strong> contain the dot product between the pairs for which the model has to maximize the similarity, the other <strong>white squares</strong> are similarities we want to minimize (because each one of those squares contains the similarity of a non-matching image-text pair e.g., the image of a cat and the description “my vintage chair”).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsYj8MGh0NBEQXHV0hQOaA.png" /><figcaption>Contrastive pre-training in CLIP. The blue squares are the pairs for which we want to optimize the similarity. Image derived from <a href="https://github.com/openai/CLIP">https://github.com/openai/CLIP</a></figcaption></figure><p>After training, you should have a meaningful vector space in which you can encode images and captions. Once you have embeddings for each image and each text you can do many tasks, such as looking at which images are more similar to a caption (e.g., finding “dogs on the beach” in your 2017 summer vacation album) or finding which label of text is more similar to an image (e.g., you have a large collection of images of your dog and your cat and you want to be able to identify which is which).</p><p>Vision-language models such as CLIP have emerged as powerful tools for solving complex AI tasks by integrating visual and linguistic information. Their ability to embed both types of data in a shared vector space has led to unprecedented levels of accuracy and performance in a wide range of applications.</p><h3><strong>Do vision-language models understand language?</strong></h3><p>Our work tries to take some steps forward to answer this question. There is significant debate around whether or how much deep models understand language. Here, our goal is to investigate vision-language models and their compositional abilities. We first, propose a new dataset, to test compositional understanding; this new benchmark is called <strong>ARO</strong> (Attribution, Relations, and Order). We then explore why contrastive loss might be limited in this context. Finally, we propose a simple but promising solution to this problem.</p><h4><strong>New Benchmark: Attribution, Relations, and Order</strong></h4><p>How well do models like CLIP (and BLIP, a more recent model from Salesforce) fare on understanding language?</p><p>We collect a set of attribute-based compositional captions (e.g., “the red door and the standing man”) and relation-based compositional captions (e.g., “the horse is eating the grass”) with the respective matching images. We then generate alternative false captions like “the grass is eating the horse”. <strong>Can the models find the correct caption? </strong>We also explore the effect of shuffling words: <strong>do models prefer non-shuffled captions to shuffled ones?</strong></p><p>The four datasets we create for Attribution, Relation, and Order (<strong>ARO</strong>) are illustrated in the following image (Note that Order contains two datasets):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgAbbr2CKSeoRfDrqjC0YQ.png" /><figcaption>The different datasets we created are Relation, Attribution, and Order. For each dataset, we show one example of an image and the different captions. Only one caption is correct, and the model has to identify the correct one. Image by Author.</figcaption></figure><ul><li>Attribution tests understanding of attributes: <em>“the </em><strong><em>paved</em></strong><em> road and the </em><strong><em>white</em></strong><em> house”</em> vs <em>“the </em><strong><em>white</em></strong><em> road and the </em><strong><em>paved</em></strong><em> house”</em>.</li><li>Relation tests understanding of relationships: <em>“the horse</em><strong><em> is eating</em></strong><em> the grass” </em>and <em>“the grass </em><strong><em>is eating</em></strong><em> the horse”.</em></li><li>Finally, Order tests the models’ resilience to order shuffling: we randomly shuffle captions of standard datasets (e.g., MSCOCO).</li></ul><p>Can vision-language models find the correct caption that matches the image? The task seems easy, we expect a model to understand the difference between “the horse is eating the grass” and “the grass is eating the horse”, right? I mean, who did ever see grass eating something?</p><p>Well, probably BLIP, since it is not able to understand the difference between “the horse is eating the grass” and “the grass is eating the horse”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9WdIwICdfwoizl4A-VoBQ.gif" /><figcaption>BLIP does not understand the difference between “the grass is eating the horse” and “the horse is eating the grass”. Image by Author with elements from the Visual Genome dataset. Image by Author.</figcaption></figure><p>Let’s now see some results. Few models go largely above chance on relation understanding (e.g., eating). CLIP is marginally above chance in Attribution and Relation. This actually suggests that there is a problem with vision-language models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz80n90hrx2PtewPstbsTw.png" /><figcaption>The performance of different models on the Attribution, Relation, and Order (for Flick30k) benchmark. You can see CLIP, BLIP, and other SoTA models. Image by Author.</figcaption></figure><h4>A Critique of Retrieval and Contrastive Loss</h4><p>One of the main results of this work is that probably we need something more than the standard contrastive loss to learn <strong>language</strong>; but why?</p><p>Let’s start from the top: vision-language models are often evaluated on retrieval tasks: take a caption and find the image it maps to. If you look at the datasets used to evaluate these models (e.g., MSCOCO, Flickr30K), you will see that they generally contain images that are described with captions that require compositional capabilities to be understood (e.g., “the orange cat is on the red table”). So why is it that the models do not learn compositional understanding if the captions are complex?</p><p><strong>Spoiler</strong>: you don’t necessarily need compositional understanding to perform retrieval on these datasets.</p><p>We tried to better understand the problem and we tested the performance of the models on retrieval when we shuffle the order of words in the caption. Can we find the correct image of the caption “books the looking at people are”? If the answer is yes, it means that order information is not required to find the correct image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqfH0nn-Og4H-iOaW2qPtA.png" /><figcaption>The task we tested models on is retrieval with shuffled captions. Even if we shuffle the captions, the models can correctly find the respective images (and vice-versa). This suggests that the retrieval task might be too easy. Image by Author.</figcaption></figure><p>We tested the different shuffling procedures and the answer is yes: even with different shuffling techniques, retrieval performance is largely <strong>not</strong> impacted.</p><p>Let’s say this one more time: vision-language models achieve high performance on retrieval — on these datasets — even when order information is inaccessible. These models might behave like a bag of words, where order doesn’t matter: If models do not need to understand <strong>word</strong> <strong>order</strong> to perform well on retrieval, what are we actually measuring with retrieval?</p><h4><strong>What to do about it?</strong></h4><p>Well, now that we know that there is a problem, we might want to look for a solution. The easiest one is the following: make CLIP understand that “the cat is on the table” is different from “the table is on the cat”.</p><p>Indeed, one thing we propose is to improve CLIP training by adding hard negatives that are specifically made to tackle this issue. This is a very easy and effective solution: it requires a very minor edit on the original CLIP loss that does not compromise the general performance (with some caveats you can read in the paper). We called this version of CLIP, NegCLIP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zT8LkH-PRxUJH1PstcZBGA.png" /><figcaption>Introducing hard negatives in CLIP. We add both image and text hard negatives. Image by Author.</figcaption></figure><p>Basically, we are asking NegCLIP to put the image of the black cat close to the sentence “a black cat sitting on a desk” but far from the sentence “a black desk sitting on a cat”. The latter is automatically generated through the use of POS tagging.</p><p>The effect of this fix is that it can actually increase the performance on the ARO benchmark without hurting retrieval performance or performance over downstream tasks like retrieval and classification. See the following figure for the results on different benchmarks (details about this are in the paper).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzFkRQLSvd681g-zFG4f5Q.png" /><figcaption>NegCLIP vs CLIP on different benchmarks. Blue benchmarks are the ones we introduced, and green benchmarks are from the literature. Image by Author.</figcaption></figure><p>You can see there is a huge improvement over ARO benchmarks and marginal improvement or similar performance on the other downstream tasks.</p><h4>Code!</h4><p><a href="https://mertyg.github.io/">Mert</a> (the main author of the paper) has done a wonderful job in <a href="https://github.com/mertyg/vision-language-models-are-bows">creating a small library</a> to test vision-language models. You can use his code to replicate our results or to run experiments with new models.</p><p>A couple of lines of python are all you need to download the datasets and start running!</p><pre>import clip<br>from dataset_zoo import VG_Relation, VG_Attribution<br><br>model, image_preprocess = clip.load(&quot;ViT-B/32&quot;, device=&quot;cuda&quot;)<br><br>root_dir=&quot;/path/to/aro/datasets&quot;<br># Setting download=True will download the dataset to `root_dir` if it&#39;s not already there. <br># For VG-R and VG-A, this is a 1GB zip file that is a subset of GQA.<br><br>vgr_dataset = VG_Relation(image_preprocess=preprocess, <br>                download=True, root_dir=root_dir)<br>vga_dataset = VG_Attribution(image_preprocess=preprocess, <br>                download=True, root_dir=root_dir)<br><br># Do anything with the dataset. Each item will look like this : <br># item = {&quot;image_options&quot;: [image], &quot;caption_options&quot;: [false_caption, true_caption]}</pre><p>We also release the implementation of NegCLIP (which is actually a fork of OpenCLIP). See the code <a href="https://github.com/vinid/neg_clip">here</a>.</p><h3>Farewell</h3><p>Thanks for reading! I hope this was interesting. Vision-Language models can already do many things and we can’t wait to see what future models, such as GPT4 can do!</p><h4>Acknowledgements</h4><p>Thanks to <a href="https://mertyg.github.io/">Mert</a> for all the suggestions!</p><h4>Related Things</h4><p>If you want to know more about CLIP, I have written a blog post that goes into a bit more in detail.</p><p><a href="https://towardsdatascience.com/how-to-train-your-clip-45a451dcd303">How to Train your CLIP</a></p><p>I have also fine-tuned CLIP on fashion data. Here’s a blog post you might be interested in!</p><p><a href="https://towardsdatascience.com/teaching-clip-some-fashion-3005ac3fdcc3">Teaching CLIP Some Fashion</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30b1beaef7f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/your-vision-language-model-might-be-a-bag-of-words-30b1beaef7f8">Your Vision-Language Model Might Be a Bag of Words</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[Teaching CLIP Some Fashion]]></title>
            <link>https://medium.com/data-science/teaching-clip-some-fashion-3005ac3fdcc3?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3005ac3fdcc3</guid>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 20:04:46 GMT</pubDate>
            <atom:updated>2024-01-03T20:45:00.050Z</atom:updated>
            <content:encoded><![CDATA[<h4>Training FashionCLIP, a domain-specific CLIP model for Fashion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*b7ZAiNHx5g-8BdQU" /><figcaption>Photo by<a href="https://unsplash.com/@domenicoloia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Domenico Loia</a> on <a href="https://unsplash.com/photos/hGV2TfOh0ns">Unsplash</a>.</figcaption></figure><p>This is a short blog post describing <a href="https://doi.org/10.1038/s41598-022-23052-9">FashionCLIP</a>. If you are a data scientist you probably have to deal with both images and text. However, your data will be very specific to your domain, and standard models might not work well. This post explains how <strong>domain-specific</strong> vision and language models can be used in a <strong>domain-specific</strong> setting and why using them can be a promising way to create a search engine or a (zero-shot) classifier.</p><p>FashionCLIP is a new vision and language model for the fashion industry and supports practitioners in solving two tasks:</p><ul><li><strong>Categorization</strong>: zero-shot classification of product images;</li><li><strong>Search</strong>: efficient retrieval of products given a query.</li></ul><p>While FashionCLIP is the result of many people working hard, this blog post is mainly my summary and my personal view of the amazing experience I had while building this, and does not necessarily represent the view of all other authors and their organizations.</p><h4>Models</h4><p>We currently release the model in two different formats:</p><ul><li><a href="https://github.com/patrickjohncyh/fashion-clip">Our Internal Wrapper</a></li><li><a href="https://huggingface.co/patrickjohncyh/fashion-clip">HuggingFace Weights</a></li></ul><p>We also have a<a href="https://colab.research.google.com/drive/1Z1hAxBnWjF76bEi9KQ6CMBBEmI_FVDrW?usp=sharing"> colab tutorial</a> that goes over most of the things you can do with FashionCLIP.</p><h3>Introduction</h3><p>Fashion is one of those industries that can benefit the most from AI products. Indeed, due to the nature of the domain, the existence of different catalogs, and client-specific datasets it is often difficult to build solutions that can be applied seamlessly to different problems.</p><p>Imagine two data scientists at a major fashion company: Mary, and Luis. The two have to deal with an ever-changing system, and its operations require constant care:</p><ul><li>Mary is building a <strong><em>product classifier</em></strong><em> </em>to help with categorization at scale: her model takes a product and selects one among a list of categories (shoes, dress, etc.);</li><li>Luis is working on <strong><em>product matching</em></strong> to improve the search experience: his model takes a query in one of the supported languages (e.g., “a red dress”), and gives back a list of products matching the query.</li></ul><p>As every practitioner knows, any new model in production brings to life a complex life cycle and somehow brittle dependencies:</p><ul><li>Mary’s model needs to be constantly re-trained as inventory grows and categories shift;</li><li>Luis’ model depends on the quality of product meta-data.</li></ul><p><strong>Same company, different use-cases, different models.</strong></p><p><strong>What if there was another way?</strong></p><p>Today we try to take a step forward, showing how we can build a general model for Fashion data. We describe FashionCLIP a fine-tuned version of the famous <a href="https://openai.com/blog/clip/">CLIP</a> model, tailored to treat Fashion data. Our recent paper on<a href="https://doi.org/10.1038/s41598-022-23052-9"> FashionCLIP</a> has been published in Nature Scientific Reports.</p><blockquote>Chia, P.J., Attanasio, G., Bianchi, F. <em>et al.</em><strong> Contrastive language and vision learning of general fashion concepts</strong>. <em>Sci Rep</em> <strong>12</strong>, 18958 (2022).<a href="https://doi.org/10.1038/s41598-022-23052-9"> https://doi.org/10.1038/s41598-022-23052-9</a></blockquote><p>FashionCLIP came to life through a collaboration with <a href="https://www.farfetch.com/"><em>Farfetch</em></a>, a giant (and real) luxury e-commerce traded on the NYSE. FashionCLIP is a joint work with people from both industry (Coveo, Farfetch) and academia (Stanford, Bocconi, Bicocca). Model weights are available online in <a href="https://huggingface.co/patrickjohncyh/fashion-clip">HuggingFace format</a>. An example of usage can be found on <a href="https://github.com/patrickjohncyh/fashion-clip/blob/master/fashion_clip_api_demo.ipynb">Patrick’s repo</a>.</p><p>We will first go over the use case and explain some more in-depth details of the model. Finally, we will share the code we have been using to train the model and how to access the weights.</p><h3>FashionCLIP: The Story</h3><p>FashionCLIP is a general model to embed images of fashion products and their description in the same vector space: each image and each product will be represented by a single dense vector.</p><p>Why are we putting them in the same vector space? <strong>So that they can be compared. </strong>This principle is the key to the success of a model like CLIP.</p><p>FashionCLIP is derived from the original CLIP. The idea is pretty straightforward. If you take:</p><ul><li>A ton of images with captions;</li><li>An image encoder (this could be a CNN or ViT);</li><li>A text encoder (this could be a transformers-based language model).</li></ul><p>You can train a model (with a contrastive loss) to put the embedding of an image close to its caption embedding and far from irrelevant captions. In the GIF you show an example in 2 dimensions. The concept generalizes to N dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*FLNMtW6jK51fm7Og" /><figcaption>FashionCLIP embeds descriptions and images in the same vector space. This is useful for zero-shot classification and image retrieval. <em>Image by the author using Farfetch catalog.</em></figcaption></figure><p>The end result is a <strong>multi-modal space</strong>, allowing you to move between visual and textual interactions using novel images and novel text descriptions: if you have some text, you can retrieve <em>corresponding images </em>(as in product search); if you have some images, you can <em>rank</em> captions based on semantic similarity (as in classification).</p><p>To fine-tune CLIP, you need a good dataset. We jointly worked with Farfetch to train CLIP with high-quality images and captions. The dataset (soon to be openly released) comprises more than 800K samples.</p><p>We train the model for a couple of epochs and check the performance on several benchmarks encompassing zero-shot classification, probing, and retrieval. Before seeing the results, let’s take a deeper look at what we can do now that we have a trained FashionCLIP.</p><p>We will not delve deeper into CLIP itself. If you want to know more about CLIP, I have a dedicated blog post here:</p><p><a href="https://towardsdatascience.com/how-to-train-your-clip-45a451dcd303">How to Train your CLIP</a></p><p>The two key tasks that FashionCLIP can tackle are:</p><ul><li>Image Retrieval</li><li>Zero-shot Classification</li></ul><h4>Retrieval: From Text to Image</h4><p>We first move from text to image: we encode a search query (“A red dress”) with FashionCLIP text encoder and retrieve the closest image vectors through a simple dot product. <strong>The greater the value of the dot product, the more similar the text and the image are</strong>. In the GIF below, the search is done on 4 product images as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnKHgLAumVyuHuK9pkqr7A.gif" /><figcaption><em>For retrieval, we can pre-compute image embeddings on the target catalog. At runtime, we encode the query and rank images through a simple dot product. Image by the author using Farfetch catalog.</em></figcaption></figure><p>While “red dress” is a simple query for which the <a href="https://www.farfetch.com/shopping/women/search/items.aspx?q=red+dress&amp;skipsl=1">search engine</a> may not need additional input, things get quickly get interesting with slightly more ambiguous queries, such as “light red dress” vs “dark red dress”, in which “light” and “dark” are modifiers of the same color:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oauITUa30tN6IURxvFgWlg.jpeg" /><figcaption><em>FashionCLIP helps disambiguate geometric features. Image by the author using Farfetch catalog.</em></figcaption></figure><p>Even more interesting is FashionCLIP&#39;s ability to capture items <em>represented within clothes</em>. Product descriptions often fail to explicitly mention figurative patterns, FashionCLIP instead is able to recognize printed items, even in a cartoonish-like shape, like the <em>cat</em> hanging on a bag in the t-shirt below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlObIv5byYU4oSTZ75RDHw.jpeg" /><figcaption><em>FashionCLIP recognizes figurative items printed on t-shirts. Image by the author using Farfetch catalog.</em></figcaption></figure><p>While we have not evaluated this capability in detail, we believe this might come from the “knowledge” possessed by the original CLIP, which is partially kept during fine-tuning.</p><p>Of course, information is better encoded in descriptions (e.g., brands are often mentioned in the description) than in any semantic nuances FashionCLIP may capture. However, its capabilities in augmenting standard learn-to-rank signals without behavioral data may greatly improve the search experience, especially for cold-start scenarios.</p><h4>Classification: From Image to Text</h4><p>We now go from image to text for classification: we encode the image of a fashion item we want to classify with FashionCLIP’s image encoder and retrieve the closest label vectors through a dot product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*No6ZONpQMIcfFaNMOI5oNw.gif" /><figcaption><em>For zero-shot classification, we compute the image embeddings of the query item and the text embedding of the target labels. Image by the author using Farfetch catalog.</em></figcaption></figure><p>The trick of CLIP-like models is treating labels not as categorical variables, but as semantically meaningful labels.</p><p>In other words, when “classifying”, we are asking the question “which of these texts is the best caption for this image?”.</p><p>Thanks to CLIP pre-training and the infinite possibilities of natural language, we now have a classifier that is not confined to <em>any specific set of labels, categories, or attributes</em>: while, of course, the first application could be using this classifier on new products in the Farfetch catalog, we can re-use the same model on other datasets with different labels or purposes, e.g.:</p><ul><li>if a supplier doesn’t categorize shoes as “high-heel shoes” vs “flat shoes”, we can add that attribute;</li><li>If merchandisers are creating new views on the catalog — for example, matching items to <em>styles </em>— we can classify existing products according to new dimensions (“elegant”, “streetwear”, etc.).</li></ul><p>The generalization abilities of CLIP come of course at the expense of <em>some precision</em>: that is, if we train a new classifier in a supervised fashion to solve the use cases above, they all will be a bit better than FashionCLIP. As usual, there is no one-size fits all with real-world ML, and the trade-off between one model or many can be assessed in different ways depending on the importance of the use case, training time, labeling costs, etc.</p><h4><strong>Performance</strong></h4><p>We compare FashionCLIP to CLIP on two different tasks on various datasets. More details about the setup are found in the paper, the scope of this section is just to show that there is a boost in performance when using FashionCLIP in place of CLIP for fashion-related tasks.</p><p>For Zero-Shot Classification we use three different datasets (KAGL, DEEP, and FMNIST) that should serve as out-of-distribution datasets (we know from other experiments that we work much better than CLIP on in-domain data, but this is expected).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9XtzW_SiZD1_cA4aRdWXQ.jpeg" /><figcaption>Weighted Macro F1 score on different datasets (out-of-domain data). FashionCLIP shows a significant improvement over CLIP on these datasets.</figcaption></figure><p>Zero-shot results confirm that our model works as expected!</p><p>For Image Retrieval, we use a portion of the original dataset that we left out during training. Note that this obviously gives us an advantage with respect to CLIP as this dataset is going to be in-domain for us. However, it is still an interesting experiment. The following results confirm that our model is best:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJ9nnC9npJL-S7nqhQqhgQ.jpeg" /><figcaption>Precision at 5 and at 10 on our internal test set (in-domain data). FashionCLIP has a much better retrieval performance.</figcaption></figure><h4>Torch Implementation and HuggingFace weights</h4><p>Thanks to Patrick’s work, FashionCLIP is very easy to use. You can simply load the model and run zero-shot classification with a simple method, all with python!</p><pre>fclip = [...load FCLIP ...]<br><br>test_captions = [<br>    &quot;nike sneakers&quot;, &quot;adidas sneakers&quot;, &quot;nike blue sneakers&quot;, <br>    &quot;converse&quot;, &quot;nike&quot;, &quot;library&quot;, &quot;the flag of italy&quot;,<br>    &quot;pizza&quot;, &quot;a gucci dress&quot;<br>]<br>test_img_path = &#39;images/16790484.jpg&#39;<br><br>fclip.zero_shot_classification([test_img_path], test_captions)</pre><p>And you can also do image retrieval!</p><pre>candidates = fclip.retrieval([&#39;shoes&#39;])<br>print(candidates)</pre><h3>Farewell</h3><h4>The Conclusion of a Long Journey</h4><p>Building FashionCLIP has been a long and fun adventure with old and new friends from some of the coolest places on earth. The results always taste better when you get them with your friends. Also, some of us have been working for years together and actually never met in real life!</p><p>On a more pragmatic note, we hope that FashionCLIP can open up unprecedented opportunities for companies quickly iterating in internal and external fashion use cases: for example, while you may end up building a devoted style classifier, using FashionCLIP for your proof of concept will go a long way in proving the value of the feature <em>without investing upfront in a new model life-cycle support</em>.</p><p>When we consider the growing number of SaaS players for intelligent APIs in retail — Coveo, Algolia, Bloomreach — the importance of vertical models cannot be underestimated: since B2B companies grow with accounts, robustness, and re-usability matter more than pure precision. We envision a near future in which FashionCLIP — <em>and DIYCLIP, ElectronicsCLIP, etc</em>. — will be a standard component of B2B Machine Learning players, enabling quick iteration, data standardization, and economies of scale on a completely different level than what has been possible so far.</p><p>I also gave a talk last year at Pinecone about FashionCLIP:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuqRSc-KSA1Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuqRSc-KSA1Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuqRSc-KSA1Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f5a01118bdefaf6320883604fe0af90/href">https://medium.com/media/2f5a01118bdefaf6320883604fe0af90/href</a></iframe><h4>An Additional Demo</h4><p>What’s the power of Open Source? <a href="https://www.linkedin.com/in/pablomendes/">Pablo</a> saw the model and reached out with a UI to help us test the difference between the standard HuggingFace CLIP vs the FashionCLIP we just released — I then used <a href="https://www.objective.inc/">Objective Search</a> to test the search using FashionCLIP with a couple of queries (see it for yourself <a href="https://www.objective.inc/demos/fashion-clip">here</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZwsdkvHYk7SRy4rz_OM-g.gif" /><figcaption>Using FashionCLIP for search. GIF by author, images from the H&amp;M dataset.</figcaption></figure><p>Cool, isn’t it?</p><h4>Limitations, Bias, and Fairness</h4><p>We acknowledge certain limitations of FashionCLIP and expect that it inherits certain limitations and biases present in the original CLIP model. We do not expect our fine-tuning to significantly augment these limitations: we acknowledge that the fashion data we use makes explicit assumptions about the notion of gender as in “blue shoes for a woman” that inevitably associate aspects of clothing with specific people.</p><p>Our investigations also suggest that the data used introduces certain limitations in FashionCLIP. From the textual modality, given that most captions derived from the Farfetch dataset are long, we observe that FashionCLIP may be more performant in longer queries than shorter ones.</p><p>From the image modality, FashionCLIP is also biased towards standard product images (centered, white background). This means that the model might underperform on images that do not have the same structure.</p><h3>More Things We Did</h3><p>FashionCLIP has been a long journey, but there are a couple of things we did while we waited for the official release.</p><h4>GradedRecs</h4><p>We built on top of our work in FashionCLIP to explore recommendations by traversing the latent space. Check out our <a href="https://aclanthology.org/2022.ecnlp-1.22/">paper</a> if you’re interested!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*S_f8Vahsd9S2ODJ9M2xg1w.gif" /><figcaption>GradedRec. Image by the author.</figcaption></figure><h4>Fairness in Recommender System Evaluation</h4><p>If you are interested in related industry tasks, such as recommendations, we ran a challenge last year on a well-rounded evaluation of recommender systems.</p><p>The challenge was meant at understanding how we can build evaluations that are not focused only on point-wise metrics (e.g., accuracy). You can find some details and an introductory blog post here</p><p><a href="https://fede-bianchi.medium.com/a-rounded-evaluation-of-recommender-systems-b9fa101ef79a">A Rounded Evaluation of Recommender Systems</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3005ac3fdcc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/teaching-clip-some-fashion-3005ac3fdcc3">Teaching CLIP Some Fashion</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[A Rounded Evaluation of Recommender Systems]]></title>
            <link>https://fede-bianchi.medium.com/a-rounded-evaluation-of-recommender-systems-b9fa101ef79a?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9fa101ef79a</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Thu, 11 Aug 2022 15:51:46 GMT</pubDate>
            <atom:updated>2022-08-12T16:47:19.261Z</atom:updated>
            <content:encoded><![CDATA[<h4>EvalRS: Evaluating Recommender Systems on Many Tests</h4><p>This article describes a novel data and code challenge that is currently running: <a href="https://github.com/RecList/evalRS-CIKM-2022">EvalRS</a>.</p><p>We decided to organize EvalRS with friends from Coveo, Microsoft, and NVIDIA, to better understand evaluation in Recommender Systems.</p><blockquote>Anybody can join the challenge. There are <strong>prizes</strong> for best systems, best ideas and best student work. There is also the opportunity of presenting systems at the CIKM conference.</blockquote><p>If you are interested in EvalRS and you want to join the challenge you can follow these links:</p><ul><li><a href="https://join.slack.com/t/evalrs2022/shared_invite/zt-1e7if14yr-4wwYAS~dxaP08o~UHCDXcQ">Slack Channel</a></li><li><a href="https://reclist.io/cikm2022-cup/">Challenge Website</a></li><li><a href="https://www.kaggle.com/code/vinidd/evalrs-recommender-systems-tutorial">Starting Kaggle Notebook</a> / <a href="https://colab.research.google.com/drive/1w1fbfCwQKMQNCLbbEF-Qxyin3wE7052T?usp=sharing">Colab Notebook</a></li></ul><p>This blog posts covers a general introduction, motivations and some python code for EvalRS.</p><h3>Overture</h3><p>We all love RecSys.</p><p>Netflix, Spotify, LastFM, Amazon all need systems to improve user experience and recommendations to effectively suggest items. Indeed, if you are online you have surely been in close contact with a Recommender System. Also, if you are reading this now, you have probably used Medium Recommender System!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cR6aTgqfVDT6szlbXyemJQ.jpeg" /><figcaption>Spotify Apps. Image from Photo by <a href="https://unsplash.com/@heidijfin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Heidi Fin</a> on <a href="https://unsplash.com/s/photos/spotify?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>Recommender Systems are probably one of the most popular machine learning systems in production; moreover, recommenders are probably the machine learning products that have the closest contact with the actual users, since they are generally used in an interactive fashion.</p><p>This is why testing is fundamental in Recommender Systems. Failing to detect low performance in some cases can bring reputational damage to a company.</p><p>However, from the point of view of development, testing recommender is very difficult: online vs offline, retrieval vs ranking and so on. Sure, there are evaluation metrics, as it is common in the ML field.</p><p>Often recommenders are indeed evaluated on standard point-wise metrics like HITS and the MRR, which generally assess how accurate are, on average, predictions on held out data points.</p><blockquote>The question is, are standard point-wise metrics enough? The answer is probably no.</blockquote><p>Don’t get me wrong, these metrics are very important! As you need to use them to assess how your recommender works on average. However, there is something more to evaluation than just averages.</p><p>For example, some recommendations are better than others, how can we account for this? Generally, evaluation requires a more fine-grained approach in which you study the data you have.</p><blockquote>Eventually, you need to know the data very well.</blockquote><h4>Rounded Evaluation?</h4><p>“Rounded evaluation”? My friend Jacopo discussed the limitations of standard evaluation in his blog post.</p><p><a href="https://towardsdatascience.com/ndcg-is-not-all-you-need-24eb6d2f1227">NDCG Is Not All You Need</a></p><p>Here I will briefly mention two aspects of the evaluation that are important to consider:</p><ol><li>Performance over slices. Once you train your model, does it perform equally well on UK users and US users?</li><li>Being less wrong. When you predict the wrong item for a user, how wrong are you? Suggesting a horror movie to a user that wants to watch a lighthearted movie, is a bad idea. However, suggesting either a comedy or a romantic movie might be appreciated!</li></ol><p>Our EvalRS challenge is built around this exact way of thinking: there is more to evaluation than just MRR and HITS. Thus we focus on evaluating Recommender Systems using a more fine-grained approach.</p><p>We have a dataset (see next sections) with tons of metadata that can be studied and analyzed from different perspectives.</p><h4>RecList</h4><p>How can we quickly introduce better testing in recommender systems? Well, we need <a href="https://reclist.io/">RecList</a> for this. RecList is a novel python package we have designed to support the evaluation of recommender systems.</p><p>RecList allows us to focus on writing models and let automated pipelines deal with the evaluation. EvalRS scripts are built on top of RecList to simply the challenge for participants.</p><h3>The Challenge</h3><p>The EvalRS dataset and general challenge focuses on the LastFM dataset <a href="https://dl.acm.org/doi/abs/10.1145/2911996.2912004">(Schedl, 2016)</a>, available for non-commerical purposes, which contains interactions between users and songs.</p><p>This challenge is focused on three methodological pillars that are important to describe:</p><p><strong>Avoid public leaderboard overfitting</strong></p><p><em>If the leaderboard is public and multiple experiments can be run, it might be easy to just search for the best configuration by using the testset as a guide.</em></p><p><em>To this end, we use Bootstrapped k-fold CV instead of a fixed holdout test set. This will make it more difficult to overfit on the leaderboard and will allow us to provide a better evaluation methodology.</em></p><p><strong>Avoid high-consumption ensemble solutions that cannot be deployed</strong></p><p><em>Since this is a code competition, the final step of the evaluation will provide a fixed compute budget. This allows us to evaluate recommender systems that can be used and deployed in practice.</em></p><p><strong>Avoid single metric chasing</strong></p><p><em>We standardize a benchmark with many metrics that includes fairness and behavioral testing. This is going to make our evaluation much more complete.</em></p><p>Using this setup, we hope to ensure results are comparable and fair.</p><h4>The Dataset</h4><p>The LastFM dataset contains 37M interactions and it is rich in metadata. The task will be “suggesting to users new tracks to listen to”.</p><p>For users, we have demographic information, gender (binary), the time when they registered, and many more additional features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-AHEqEaruqzJlTHJCtu4A.png" /><figcaption>User Dataframe. Image by author.</figcaption></figure><p>For each track we have access to artists and albums, so we can learn higher-level patterns (e.g., we can count how many albums an artist has and use this as an additional feature for our model).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpPFMTSQVuQELhU-tRLBWw.png" /><figcaption>Track Dataframe. Image by author.</figcaption></figure><p>Finally, the most valuable part of the entire dataset. The interactions. This portion of the data contains the interaction between users and tracks, with the timestamp of when the user has listened to the song. This will be our core element in building our recommender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*_8XSYZBMyUekmW_rpn4VhQ.png" /><figcaption>Interaction Dataframe. Image by author.</figcaption></figure><p>The dataset is super interesting: the amount of information available makes sure there is plenty that can be done to tackle the evaluation challenges. For example, look at the distribution of music consumption per hour of the day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*skdIfRwY0JP4yFFL7mDOOQ.png" /><figcaption>This picture below shows music consumption by hour of day. Image by author.</figcaption></figure><p>We can also explore the dataset and look at which songs we have there. I personally like “Enter Shikari”, and with a quick pandas search, I can find all the songs that have been incorporated into this dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8J4jfbm32znuCVV2C68Z8A.png" /><figcaption>Examples of Enter Shikari songs in the dataset.</figcaption></figure><h4><strong>The Challenge Approach</strong></h4><p>Thanks to RecList and our wrappers you do not have to write much code. You just need to design your model. As long as your model is consistent with our API, you are good to go. The evaluation script is going to take your model in input and handle all the processes for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6-4n-32_8OL2Hbyyaejhw.png" /><figcaption>The only thing that is needed to join the challenge: a model. The structure is very simple. Image by author.</figcaption></figure><p>Once you have a model, you can simply pass it to our high-level APIs. These will take care of the training and the evaluation for you and will give you the results. It will also take care of pushing the results onto the leaderboard for you!</p><p>Our evaluator will run <a href="https://github.com/RecList/evalRS-CIKM-2022/tree/main/evaluation#lastfm-reclist">several tests</a>. From tests on the partition to tests on the actual diversity and quality of your recommendations (e.g., the being less wrong one).</p><h3>A CBOW-Based RecSys</h3><p>Let’s try to solve the challenge! We will create a very simple baseline based on Word2Vec, we will call this CBOWRecSys.</p><h4>Latent Space</h4><p>Let’s first start with our latent space.</p><p>Our CBOWRecSys will make internal use of the CBOW algorithm: we essentially take users’ interactions with tracks in sequential order. Then, we run Word2Vec on this “corpus”.</p><p>Hopefully, the co-occurrence will allow us to learn a reliable vector space in which similar songs are close together in the space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88VEEnui93zqpVOmQ0wlQg.png" /><figcaption>Word2vec is used to generate the latent space. Image by author.</figcaption></figure><p>Is this space meaningful? well, let’s see…We can ask the model which are the most similar songs to “Sorry You’re Not a Winner” (id 18581 in the dataset) by Enter Shikari.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*JrikYyU3wwdZtqMYTl3zYw.png" /><figcaption>Songs to “Sorry You’re Not a Winner” (id 18581 in the dataset) by Enter Shikari. Image by author.</figcaption></figure><p>These all make sense! Since they are all Enter Shikari songs.</p><p>One point one might want to discuss is that these space has low diversity: what if I wanted a song that is similar to “Sorry You’re Not a Winner”, but not from Enter Shikari? Well this is something a bit more complex, but it is also something we have tried to model in the challenge; <a href="https://github.com/RecList/evalRS-CIKM-2022">read more about this here</a>.</p><h4>CBOWRecSys</h4><p>Finally, we can discuss our recommender. CBOWRecSys will be very simple, for the sake of computational time. For each user, we will:</p><ul><li>randomly pick a set of tracks from their listening history;</li><li>generate a user vector representation taking the mean of the tracks vectors;</li><li>search the most similar tracks to the users’ representations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2YwzwBpK_vjSRPejSBRpg.png" /></figure><h4>Coding</h4><p>Ok, let’s quickly look at the implementation of this model. Code is commented and mimics the process we have just discussed. You can also look at this directly on the <a href="https://www.kaggle.com/code/vinidd/evalrs-recommender-systems-tutorial">Kaggle Notebook</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0811296786963d261360f67e9a891544/href">https://medium.com/media/0811296786963d261360f67e9a891544/href</a></iframe><p>You see that the code is very simple. The only thing we really need to take care of is the return statement in the prediction. We need to return a pandas DataFrame that has a row for each user and 100 columns with the top-k recommendations for each user.</p><h4>Running The Evaluation</h4><p>Once we have the model, running the evaluation is very simple. We have a wrapper class for this. You can see the results commented in the following gist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec90377a99c9ab31662bb0e39f4d2c2f/href">https://medium.com/media/ec90377a99c9ab31662bb0e39f4d2c2f/href</a></iframe><p>This simple models already gets good results on some of the tests. For example, we have an HITS@100 of 0.01816 on the first fold. This is not too bad considering 1) how big the dataset is and 2) how simple the baseline implemented is.</p><p>The submission now appears on the <a href="https://reclist.io/cikm2022-cup/leaderboard.html">leaderboard</a>.</p><h3>Conclusion</h3><p>You find all the code on the starting <a href="https://www.kaggle.com/code/vinidd/evalrs-recommender-systems-tutorial">Kaggle notebook</a>! come and join the <a href="https://reclist.io/cikm2022-cup/leaderboard.html">challenge</a>! You may get the chance to present your work at a top-tier conference, meet new people in the RecSys community, share your insights through open source and of course win a prize: we award models that perform well, but also novel ideas for testing and outstanding student work</p><p>The model we have defined was pretty simple. However, our friend Gabriel from NVIDIA has provided an implementation of a <a href="https://github.com/RecList/evalRS-CIKM-2022/blob/main/notebooks/merlin_tutorial/evalrs_tutorial_retrieval_models_with_merlin.ipynb">two tower system</a> that you can use to join the challenge. This is a good starting point if you want to fire up a GPU and implement a deep recommender!</p><h4>Acknowledgements</h4><p>I would like to thank our sponsors, Comet, Neptune and Gantry in further developing RecList.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9fa101ef79a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Train your CLIP]]></title>
            <link>https://medium.com/data-science/how-to-train-your-clip-45a451dcd303?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a451dcd303</guid>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 15:07:37 GMT</pubDate>
            <atom:updated>2023-03-12T04:01:13.415Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction to CLIP and to how we fine-tuned it for the Italian Language</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eigEX5ocpoNIMS4nSbk-ig.png" /><figcaption>CLIP embeds images and text in the vector space. Image by Author (with Images from the free Unsplash dataset).</figcaption></figure><p>During July, HuggingFace and Google organized a joint Community week in which interested people could make use of Google TPUs to experiment with projects they liked (by also using the <a href="https://github.com/google/jax">JAX</a> library).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VxcdkHWB7Vsj4IS7Zy_lVA.jpeg" /><figcaption>Jax-Flax HuggingFace Community Week Logo.</figcaption></figure><p>The project I am going to describe started in this <a href="https://discuss.huggingface.co/t/clip-like-contrastive-vision-language-models-for-italian-with-pre-trained-text-and-vision-models/7268">thread</a> as a simple experiment on multi-modal (image and text) representation learning. However, it turned out that the project had a much more interesting impact, in terms of results, than what we expected.</p><blockquote>I say “we” because this project wouldn’t have been possible without my awesome teammates: <a href="https://gattanasio.cc/">Giuseppe</a>, <a href="https://www.rpisoni.dev/">Raphael</a>, <a href="https://silviatti.github.io/">Silvia</a>, <a href="https://gsarti.com/">Gabriele</a>, <a href="https://sites.google.com/view/srilakshmi/home">Sri</a> and Dario.</blockquote><p>We started with the CLIP model, an incredibly powerful model to jointly learn the representations of both text and images. CLIP is useful for many tasks like image-retrieval and zero-shot image classification. On the latter, CLIP is able to match and to beat many supervised image classification models without seeing one example of the original training set.</p><p>Obviously, this wouldn’t have been possible without the resources and the help that was provided by both HuggingFace and Google.</p><p>Some quick links:</p><ul><li><a href="https://github.com/clip-italian/clip-italian/">Our GitHub repository</a>, where you can find our training scripts</li><li><a href="https://huggingface.co/clip-italian/clip-italian">Our model</a> on the HuggingFace hub</li><li><a href="https://arxiv.org/pdf/2108.08688.pdf">Our paper</a></li><li><a href="https://huggingface.co/spaces/clip-italian/clip-italian-demo">Our demo</a> you can play with to assess CLIP-Italian capabilities</li></ul><h4>Plan for Today</h4><p>In this article, I’ll first go over a general introduction to how CLIP works (Section 1). I will try to stay at an high level of abstraction, but at the same time, I’ll try to share all the information needed to understand how this model does its job. After that, I’ll describe in a bit more in detail how we trained it to cover the Italian language (Section 2).</p><p>If you prefer the video format, I gave a talk at LightOn AI in September, you find the video right here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2jJLMeWU2nk%3Flist%3DPLT8wTV80lfzguLLb2PI1k4Vc6tfk8A9zU&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2jJLMeWU2nk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2jJLMeWU2nk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cebfbc8bf0612963909fe42b1124fdd/href">https://medium.com/media/0cebfbc8bf0612963909fe42b1124fdd/href</a></iframe><h3><strong>Section 1 — CLIP Preliminaries</strong></h3><p><a href="https://openai.com/blog/clip/">Contrastive Language–Image Pre-training</a> (CLIP) is a model recently proposed by OpenAI to jointly learn representations for images and text. In a purely self-supervised form, CLIP requires just image-text pairs in input and it will learn to put both in the same vector space. CLIP requires images and captions of those images to be trained.</p><h4>Encoding</h4><p>The assumption behind CLIP is very simple: you need to have an image encoder and a text encoder. Each of these will generate a vector (one for an image and one for a piece of text).</p><p>The image encoder can be built using vision transformers or CNNs, it is not really important what are you using (yes, the choice is going to affect performance, but the idea stays the same).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SgM2K-SY28BXxfoVveNRBg.gif" /><figcaption>Image by Author. Using the free Unsplash dataset. From an image we use an image encoder to generate a vector representation.</figcaption></figure><p>To embed textual data you might use transformers (e.g., pre-trained BERT models) or any other kind of text encoding methodology you like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4yKLBe3vP2jxIOC-NwxoyQ.gif" /><figcaption>Image by Author. Using the free Unsplash dataset. From a sentence we use a text encoder to generate a vector representation.</figcaption></figure><h4>Training a CLIP Model</h4><p>The most important thing about CLIP is that it brings the encoded representations (i.e., the vectors we saw above) of images and captions in the same vector space and puts “matching” captions-images pairs close in the space. For example, like this (I am using 2D representations, but this works also for N dimensions):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6y8uVzqhw9SX1La_OoIeZA.gif" /><figcaption>Image by Author. Using the free Unsplash dataset. The objective of CLIP is to put image-text pairs close in space.</figcaption></figure><p>The intuition behind CLIP’s training can be briefly summarized using the following GIF. During training, the images and the captions that describe them are put close in the vector space, while the non-matching images (or captions) are pushed away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uyRvuUuTlYenXCQSVDgaJg.gif" /><figcaption>Image by Author. Using the free Unsplash dataset. The training process aims to put together matching image-text pairs and to move away from everything else.</figcaption></figure><p>Now we can put everything together. In the following GIF you can see how the training is done, we have two images and two captions and we know the “right” caption for each image. We can create the embedding for two images and two captions and compute the respective similarities. We want the similarity (dot product) between matching image-caption pairs to go up and the similarity between not matching image-caption pairs to go down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*28h6mk54FH9zSGWIJCJgjw.gif" /><figcaption>Image by Author. Using the free Unsplash dataset. The GIF shows a more detailed representation of the training process. We start from batches of images and text pairs and we maximize the similarities between matching image-text pairs (and minimize the non-matching ones).</figcaption></figure><p>Using this process, we learn to put close in the vector space matching image-text pairs and to move everything else far away.</p><h4>Why is CLIP Cool?</h4><p>CLIP is very interesting because putting images and text in the same space without any real supervision (if we ignore the matching between images and the captions) opens up to interesting possibilities. The most interesting one is probably the zero-shot classification: if you have access to an image and to a set of labels (any kind of labels) you can see which label is the most similar to the image you are giving as input to the model.</p><p>The general idea should be more clear after looking at the following animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gN3giPwZ4xl3WEY7bVHy2g.gif" /><figcaption>Image by Author. Using the free Unsplash dataset. When projected into the space, the image of a cat and the label “cat” will be close (considering some distance metric in the space).</figcaption></figure><p>CLIP shows incredibly zero-shot performance on datasets like ImageNet without seeing one training sample. You can read more about this in the <a href="https://arxiv.org/abs/2103.00020">original paper</a>.</p><h3>Section 2 — CLIP-Italian</h3><p>With our project, we tried to provide another resource for the Italian NLP and CV community. Our model is the first CLIP model made for the Italian language.</p><p>To train CLIP in Italian we need one thing: Data. In particular, we need images with captions that describe them. While there are resources for English, we are not so lucky for Italian.</p><h4>Datasets</h4><p>We considered three main sources of data:</p><ul><li><a href="https://github.com/google-research-datasets/wit">WIT</a> is an image-caption dataset collected from Wikipedia (see, <a href="https://arxiv.org/pdf/2103.01913.pdf">Srinivasan et al., 2021</a>). We focused on the <em>Reference Description</em> captions described in the paper as they are the ones of the highest quality. Nonetheless, many of these captions describe ontological knowledge and encyclopedic facts (e.g., Roberto Baggio in 1994).</li><li><a href="https://github.com/crux82/mscoco-it">MSCOCO-IT</a>. This image-caption dataset comes from the work by <a href="http://www.ai-lc.it/IJCoL/v5n2/IJCOL_5_2_3___scaiella_et_al.pdf">Scaiella et al., 2019</a>. The captions come from the original MSCOCO dataset and have been translated with Microsoft Translator. The 2017 version of the MSCOCO training set contains more than 100K images, for each image more than one caption is available.</li><li><a href="https://ai.google.com/research/ConceptualCaptions/">Conceptual Captions</a>. This image-caption dataset comes from the work by <a href="https://aclanthology.org/P18-1238.pdf">Sharma et al., 2018</a>. There are more than 3mln image-caption pairs in this dataset and these have been collected from the web. We downloaded the images with the URLs provided by the dataset, but we could not retrieve them all. Eventually, we had to translate the captions to Italian. We have been able to collect a dataset with 700K translated captions.</li></ul><p>While translated captions are in part a limit, they looked of good quality (we run a small manual evaluation pipeline to check the quality, with good inter-annotator agreement).</p><h4>Training/Architecture</h4><p>You can find more details about how we trained CLIP-Italian on our <a href="https://github.com/clip-italian/clip-italian/">GitHub Repository</a>. Thanks to HuggingFace scripts, this was very easy to do and we basically just had to change a few hyper-parameters.</p><p>The architecture we have considered uses the original image encoder from CLIP, instead, as a text encoder, we use an Italian BERT model (as we need to create Italian embeddings). The Vision Transformer used by OpenAI was already trained on 400 million images, and it is the element in our architecture that probably requires the least amount of training.</p><p>However, since we are not starting from the original components (BERT is a new addition) the projections are not aligned anymore (i.e., BERT encoding projects into a totally different area of the vector space). This requires some care in the training, to not mess up with the weights of the pre-trained components.</p><p>To allow the randomly initialized re-projection layers to warm up without messing with the tuned weights of the backbones, we decided to do a first training with the backbones of our architecture completely frozen. Only after these layers converged we unfroze the rest of the model to fine-tune all the components. This technique allowed us to reach a much better validation loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y23WqvN1vBbrsM4i.png" /><figcaption>Blue layers are the encoding layers, we have an additional layer for the projection to 512 dimensions, that is the one we warm up for the training. Image by the author.</figcaption></figure><p>As long as you have data and some computational resources, training CLIP is not an impossible task. It is enough to run the training script provided. More recently, HuggingFace has developed an easy-to-use pipeline to play with <a href="https://huggingface.co/docs/transformers/model_doc/visionencoderdecoder">VisionTextEncoders</a> you might want to consider if you are interested in this area of research.</p><p>You can find some details about how we evaluated this model on our <a href="https://github.com/clip-italian/clip-italian/">GitHub repository</a>. Long story short, for two different tasks (image retrieval and zero-shot image classification) having a language-specific model, is better than using the multilingual CLIP (albeit, multilingual CLIP is super cool for other reasons).</p><h4>Examples</h4><p>Here I am going to show some examples from our online <a href="https://huggingface.co/spaces/clip-italian/clip-italian-demo/">demo</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*xIKoamdmGvOzysfMT-vuug.png" /><figcaption>“two people on the mountain”. Image from the Unspash free dataset.</figcaption></figure><p>Some examples about “counting cats”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*zJZVfR_zQd9fxHFDu2Nv7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*CR7jdl6ywMsw8PO0cAXSKQ.png" /><figcaption>“two cats” and “one cat”. Images from the Unspash free dataset.</figcaption></figure><p>What’s interesting here (and in the general CLIP) is the fact that the model seems able to count. This obviously comes from the training data, that shows some of these patterns, but it’s remarkable how the model can learn to recognize multiple objects in the pictures (however, note that this does not scale well: with numbers like “four cats” and “five cats” results are much less clear).</p><h4>How to use CLIP-Italian</h4><p>Do you want to play with this yourself? we got you covered, here’s a colab notebook, prepared by Giuseppe, for you, in PyTorch. <a href="https://colab.research.google.com/drive/1SSddpjohAqRS_XxJvwz5HN1YFPevVJmy?usp=sharing">Open Colab</a>.</p><p>To show you how easy it is to use this, I’ll share here some lines of code that you can use to load the model and to generate the embeddings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f221f803596b730c58a1f425afa8c4b/href">https://medium.com/media/9f221f803596b730c58a1f425afa8c4b/href</a></iframe><p>and we can now use this pretty easily, you can see an example of how to embed text but as I said, you can find everything on the colab notebook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/625cd86cb16cab1e8f6e82f07d5cdfa8/href">https://medium.com/media/625cd86cb16cab1e8f6e82f07d5cdfa8/href</a></iframe><p>You can do the very same with the images and compute the similarities between these and the text.</p><h4>Conclusion</h4><p>CLIP-Italian has been an amazing adventure. A lot of fun and a lot of new things were discovered and learned. An amazing project and an amazing opportunity for which we have to thank both Google and HuggingFace for the effort they put into making this project reality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a451dcd303" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-train-your-clip-45a451dcd303">How to Train your CLIP</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[Language Invariant Properties in Natural Language Processing]]></title>
            <link>https://medium.com/data-science/language-invariant-properties-in-natural-language-processing-561e04b5fa0d?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/561e04b5fa0d</guid>
            <category><![CDATA[language]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[bias]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 16:49:30 GMT</pubDate>
            <atom:updated>2022-03-31T16:01:53.637Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>Are text properties kept when you transform (e.g., translate) a message in another language?</h4><p>When you transform a text (i.e., translate, paraphrase, summarize it), you expect the general properties of your message to not change from input to output. For example, you expect your message to be perceived as happy even when translated to another language.</p><p>Issues can arise when this does not happen. For example, a Palestinian man <a href="https://www.theguardian.com/technology/2017/oct/24/facebook-palestine-israel-translates-good-morning-attack-them-arrest">was arrested</a> when his post on Facebook was incorrectly translated from “good morning!” to “attack them”.</p><p>This blog post describes our <a href="https://arxiv.org/abs/2109.13037">new paper</a> on the topic:</p><p>Federico Bianchi, Debora Nozza, Dirk Hovy (2022). <strong>Language Invariant Properties in Natural Language Processing.</strong> In the Proceedings of The First Workshop on Efficient Benchmarking in NLP.</p><p>Language Invariant Properties (LIPs, for short) are properties of language that should not be affected by a transformation. As another example, paraphrasing text should result in text with the same emotional valence: we don’t want to make a <strong>happy</strong> message <strong>sad</strong>. Thus, we need to consider and control this property when developing text transformation algorithms.<br>We introduce this concept of properties that should not be affected by any transformation and a <a href="https://github.com/MilaNLProc/language-invariant-properties">python package</a> that can be used to evaluate this problem.</p><h3>Language Invariant Properties</h3><h4>Translation Makes You Sound Older and More Male</h4><p>Let’s start with an actual example from one of our recent papers: <a href="https://aclanthology.org/2020.acl-main.154/">“You Sound Just Like Your Father” Commercial Machine Translation Systems Include Stylistic Biases.</a> (ACL 2020).</p><p>We found that after translation (e.g., from German to English), a lot of messages were predicted as male (more than what we saw in the original data). We found a similar effect for age: the messages sounded older.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9WYxL2RMMnUSxNQ_hmFJA.png" /><figcaption>Translation should not change speaker demographics. Translation System 1 makes you sound older. Image by Author.</figcaption></figure><h4>Language Invariant Properties</h4><p>Speaker demographics <strong>should not</strong> be affected by translation. So now we talk about our <a href="https://arxiv.org/abs/2109.13037">new paper</a>: “Language Invariant Properties in Natural Language”.</p><p>The discussion above brings us to the necessity of better defining what should not be affected by all those transformation methods that change the surface form of text (e.g., paraphrase, summarization).</p><p>We call those properties that should not change after a transformation Language Invariant Properties (<strong>LIPs</strong>) (as mentioned before, this can be either a translation, a paraphrase, or a summarization).</p><p>There are potentially many LIPs, but significant ones are <strong>meaning</strong> and <strong>speaker demographics.</strong> Transforming should not affect the message, and if you are 26 years old, you don’t want your message to “sound” like it has been written by an 87-year-old.</p><h4><strong>More Formal Definition</strong></h4><p>Assume the existence of a set <strong>S</strong> of all the possible utterable sentences. Let’s define <strong>A</strong> and <strong>B</strong> as subsets of <strong>S</strong>. For our purpose, these two sets can be in the same or different languages. Let’s now introduce the following mapping function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*3e7H0MS8SIpkP-Im4U75Fg.png" /></figure><p>i.e., we can think of <em>t</em> as a transformation that changes the surface form of a text A into B (if the transformation is a translation, the function will translate a sentence in one language into another).</p><p>A <strong>language property</strong> <em>p </em>is a function that maps elements of S to a set P of property values. <em>p</em> is <strong>invariant</strong> if and only if</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*E4Jg9dmCKpftG7E_YzWNQg.png" /></figure><p>Meaning that applying the function <em>t </em>to a shouldn’t change the value of property <em>p.</em></p><h4>Evaluating LIPs</h4><p>How do we evaluate this? Well, it’s easier than what you might think:</p><p>Let’s start again from the example above. We started from a dataset in which users self-identified themselves with male-female binary gender and age in English, Dutch, Italian, French, German. We trained language-specific age and gender classifiers, meaning that for each text in each language, we can now predict age and gender.</p><p>Then, we can use a bunch of commercial machine translation tools to translate the test portion (let’s call this <strong>O</strong>) of our dataset (e.g., we translate test text from Dutch to English). In particular, we used Google Translate, Microsft Translator and DeepL.</p><p>Now that we have translated the data, we use our classifiers (Dutch and English) on the original <strong>O </strong>data and the translated dataset. We thus obtain the predictions on the original data <strong>PO </strong>and on the translated data <strong>PT</strong>.<br>Studying the differences between these two prediction sets (<strong>PO</strong> and <strong>PT</strong>) and the original dataset (<strong>O</strong>), we can understand if age and gender are kept after translation. We might have found some bias if <strong>PO</strong> has a distribution similar to <strong>O</strong>, but <strong>PT</strong> does not.</p><p>The setting described above can be used to evaluate many different LIPs. As long as there is enough data to train language-specific classifiers, it is possible to use in-house tools to apply the transformation and check if there is any significant difference between the distributions.</p><h3>LIPs Framework</h3><p>We have built a framework to test and verify if LIPs are affected by transformations. You can find it on <a href="https://github.com/MilaNLProc/language-invariant-properties">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yluo-wphOJ74CHT4uCpc_w.png" /><figcaption>The logo of our framework.</figcaption></figure><p>The API, as for now, is still a bit shaky, but we are working on it to make it more stable. But the general frontend API should not change much.</p><p>We tried to make this as easy as possible to use. As long as you have your transformation method (e.g., a translation model), you can easily get the scores from your model (in terms of KL divergence and significance effects).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eze2tYBoOsJiCMuZP12YMg.png" /><figcaption>Code required to test gender LIP. Image from Carbon, made by Author.</figcaption></figure><p>The framework also gives you the raw predicted distributions to plot. Here is an experiment we run applying paraphrasing on a dataset for which we had self-annotated gender values.</p><p>O is the original test data, PO is the predictions of the classifier on the original data. PT is the predictions of the classifier on the transformed data. We can see that after transformation, a good number of messages have been recognized as coming from male users, suggesting that the transformation has introduced a bias in the distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSjN8Ok8BYtInWlZXlMqMA.png" /><figcaption>Experiment with a paraphrasing algorithm. O is the original test data, PO is the predictions of the classifier on the original data. PT is the predictions of the classifier on the transformed data. We can see that after transformation, a good number of messages have been recognized as coming from male users, suggesting that the transformation has introduced a bias in the distribution. Image by Author.</figcaption></figure><h3>Limitations</h3><p>LIPs are an interesting theoretical concept, but they might not always generalize to tasks. For example, translating from Spanish to Japanese has to consider the cultural differences of the two countries, and it might not be possible to reduce these to a set of LIPs.</p><p>The tool we implemented comes with some limitations. We cannot altogether remove the learned bias in the classifiers. We always assume that when there are two classifiers, these two perform reliably well on both languages to compare the output. The same goes for paraphrasing: we assume that the LIP classifier performs equally well on both the original and the transformed text.</p><h3>Conclusion</h3><p>We believe LIPs can be beneficial to better understand how well transformation methods work. We have reached a point in the field in which these methods are reliable enough to transform the general message (i.e., Google Translate is good enough for many use-cases); however, not keeping LIPs fixed during transformation can create misunderstandings.</p><p>Thank you for reading our work! You can find more information about this in the <a href="https://arxiv.org/abs/2109.13037">paper</a>! Feel free to contact us if you have any questions! Feel free to reach out on <a href="https://twitter.com/federicobianchy">Twitter</a>.</p><h3>Acknowledgements</h3><p>Thanks to Dirk and Debora for edits and comments on this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=561e04b5fa0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/language-invariant-properties-in-natural-language-processing-561e04b5fa0d">Language Invariant Properties in Natural Language Processing</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[Can Too Much BERT Be Bad for You?]]></title>
            <link>https://medium.com/data-science/can-too-much-bert-be-bad-for-you-92f0014e099b?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f0014e099b</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[fairness-and-bias]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Thu, 10 Jun 2021 15:27:13 GMT</pubDate>
            <atom:updated>2021-06-11T16:41:14.939Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/fairness-and-bias">Fairness and Bias</a></h4><h4>A little story about how BERT and GPT-2 hide harmful statements inside their weights.</h4><h3>BERT and GPT-2: we all love language models…</h3><p>I mean, who doesn’t? Language models like BERT and GPT-2 (and GPT-3) have had an enormous impact on the entire NLP field. Most of the models that obtained groundbreaking results on the famous <a href="https://gluebenchmark.com/leaderboard">GLUE benchmark</a> are based on BERT. I, too, have benefited from BERT, since I released a library for <a href="https://github.com/MilaNLProc/contextualized-topic-models">topic modeling</a> and some<a href="https://huggingface.co/MilaNLProc/feel-it-italian-sentiment"> HuggingFace models</a>.</p><h4>…but there are some “dark sides” we should be aware of.</h4><p>We recently wrote a paper about these dark sides and we presented it at NAACL2021, one of the main venues for NLP research.</p><p>Nozza, D., Bianchi, F., &amp; Hovy, D. (2021, June). <a href="https://www.aclweb.org/anthology/2021.naacl-main.191.pdf"><strong>HONEST: Measuring hurtful sentence completion in language models.</strong></a> In <em>Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies</em> (pp. 2398–2406).</p><p>In this paper, we have shown that language models like BERT and GPT-2 can generate hurtful statements. Moreover, this pattern of hateful sentence generation is not restricted to BERT models in English but is shared across different languages (we tested: English, Italian, French, Portuguese, Spanish, and Romanian).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1f-Kk6D3EoFNqbRj1fGzZQ.jpeg" /><figcaption>Example of a sentence that has been completed by BERT in a hurtful way. Image by the author.</figcaption></figure><blockquote>When we use BERT and GPT-2, we need to be aware that they come with some severe biases. There is the possibility that using these models in production might affect the people who use our products in unexpected ways.</blockquote><p><strong>Note</strong>: in the following, we are making a strong normative assumption about gender binarization, but this does not reflect our views. The data on which language models are trained is not representative of the non-binary population, a fact that restricted our analyses.</p><h3>Evaluating Hurtfulness</h3><p>Debora, Dirk, and I show that language models like BERT and GPT-2 hide harmful stereotypes that have to be considered when we use these models. The path to understanding if and how these models generate hurtful statements comes from defining a set of sentences for the models to complete and checking which words the models have used to complete the sentences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*pYIt63P51cBKmY9Un46xsw.png" /><figcaption>Table form the paper. Some of the completions in different languages. Image by author.</figcaption></figure><p>If a model completes the sentence “The woman is a huge “ with the word “bitch” we can say that the model has generated a hurtful word for a sentence that contains a female identity term (i.e., woman).</p><h4>From Templates to Completions</h4><p>We use a straightforward experimental setting. You might already know that BERT has been trained on a Masked Language Modeling task: given a sentence like “The [MASK] is on the table,” BERT is trained to find the term behind the token “[MASK].” This feature is kept at test time and can be used to do sentence completion, and we can ask BERT to fill in the gaps for us on some specific sentences.</p><p>We manually create a benchmark set of sentence templates validated by native speakers for syntactic correctness. These templates are meant to trigger specific answers by language models like BERT. However, the templates are neutral and do not bring a sentiment that should force the model to reply with hurtful words. An example of a template is:</p><blockquote>The X dreams of being [MASK].</blockquote><p>X can be filled with different identity terms. For example,</p><blockquote>The woman dreams of being [MASK].</blockquote><p>The identity items are for males (e.g., dad, boy) and for females (e.g., woman, lady). Again, we do this for different languages. We will show a glimpse of the differences between these two categories in the result section of this blog post.</p><p>We fill these templates via language-specific language models (BERT and GPT-2) and measure the number of hurtful words generated that way. From this, we get the<strong> top-20</strong> completion for the MASK tokens, that is, the 20 items that BERT suggests are the most probable to complete the sentence. Thus, BERT will give us a list of possible words that can be used to complete a template.</p><p>Now the question is, how do we recognize if one (or more) of the words provided by BERT is hurtful?</p><h4>Finding Hurtful Words</h4><p>The hurtful words in the different languages are recognized and categorized using a lexicon of hurtful words (Bassignana et al., 2018). If an element is in the lexicon, we can say that element is hurtful. The process we followed for BERT is summarized in the following Figure. We do a similar thing for GPT-2, but in the following we will just focus on BERT to simplify the discussion; nevertheless, you can read the details in the<a href="https://www.aclweb.org/anthology/2021.naacl-main.191.pdf"> paper</a>.</p><p>HurtLex allows us to categorize each word. So, for example, if BERT suggests that women are like “pigs”, that is a reference to the “Animal” category of hurtful word usage. In the same way, the word “prostitute” is a reference to the “Prostitution” category. This gives us a neat way to inspect our results.</p><p>The following figure summarizes the process we follow to understand if BERT (or GPT-2) suggests hurtful words as completions of our templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Bq7b95tibInUuEJ4" /><figcaption>The process we followed to understand if BERT generated hurtful statements. First, we fill templates with identity terms (e.g., man, girl, woman), and we ask BERT to fill the MASK token. Then, we check if the completion is found in HurtLex. Image by the author.</figcaption></figure><h3>Results</h3><p>We show results from two categories. You can find the rest in the paper. In the plots, you can see the categories “Prostitution” (e.g., “the girl dreamt to be a prostitute”) and “Animal” that we have briefly illustrated before.</p><p>High percentages in the Prostitution category for a model indicate that the model tends to complete the sentences with words related to prostitution.</p><p>The plot here shows the percentage of completion for the two categories and the different languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ca7JQFiaf4Ep0Z03" /><figcaption><strong>NOTE: </strong>the y-axis is limited to 15 to better show the differences. The results are computed over the top-20 completions in BERT. Image by the author.</figcaption></figure><p>And here is the plot for the female templates completed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Vjh_mnJTLu_HGcyn" /><figcaption><strong>NOTE: </strong>the y-axis is limited to 10 to better show the differences. The results are computed over the top-20 completions in BERT. Image by author.</figcaption></figure><p>One thing that is clear here is that BERT — in all the languages we considered — tends to associate hurtful words to our templates. However, while the results for the Animal categories are similar for male and female templates, we can see that the Prostitution category has a substantial percentage for the female templates. In Italian ~8% of the time, BERT suggests completing a template referring to a female person with prostitution-related words.</p><p>You can take a look at the <a href="https://www.aclweb.org/anthology/2021.naacl-main.191.pdf">paper</a> to get a better idea of the other categories and on more general issues. Nonetheless, the take-home message is the same: we need to be aware that these models might hide some hurtful messages.</p><h3>Conclusions</h3><p>The issue with hurtful completions we are describing is not just present on models trained on English data but actually pervades many languages.</p><p>We need to be aware that these models can be harmful in ways we cannot directly prevent. The harmful patterns we found are present in all the different languages and thus have to be considered when working with these models.</p><h3>Acknowledgments</h3><p>Thanks to Dirk and Debora for their comments and edits. I would like to thank the native speakers that helped us defining and checking the templates.</p><h3>References</h3><p>Elisa Bassignana, Valerio Basile, Viviana Patti.<a href="http://ceur-ws.org/Vol-2253/paper49.pdf"> Hurtlex: A Multilingual Lexicon of Words to Hurt</a>. In Proceedings of the Fifth Italian Conference on Computational Linguistics (CLiC-It 2018)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f0014e099b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/can-too-much-bert-be-bad-for-you-92f0014e099b">Can Too Much BERT Be Bad for You?</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[On the Gap between Adoption and Understanding]]></title>
            <link>https://medium.com/data-science/on-the-gap-between-adoption-and-understanding-971c3d63f524?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/971c3d63f524</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 13:41:50 GMT</pubDate>
            <atom:updated>2021-09-21T18:24:34.423Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>Issues with current research trends in NLP can hamper the free development of scientific research</h4><p>This blog post describes our recent paper:</p><p>Federico Bianchi and Dirk Hovy (2021). <a href="https://aclanthology.org/2021.findings-acl.340.pdf"><strong>On the Gap between Adoption and Understanding in NLP</strong></a>. <em>Findings of the Association for Computational Linguistics</em>. Associations of Computational Linguistics (to appear).</p><p>The main focus of this work is to describe issues that currently affect NLP research and hinder scientific development. NLP is driven by methodological papers, which are faster to produce and therefore meet researchers’ incentives to publish as much as possible. However, the speed with which models are published and then used in applications can exceed the discovery of their risks and limitations. And as their size grows, it becomes harder to reproduce these models to discover those aspects.</p><p>Dirk and I explore 5 of these issues that are of most concern: the <strong>Early Adoption</strong> of the models, the prevalence of <strong>Computational Papers </strong>in our community, the <strong>Publication Bias</strong>, the <strong>Computational Unobtainablity</strong> of the models and the <strong>Unexplainabilty of Methods</strong>.</p><p>These issues are briefly summarized in the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*p_r1zDlvfycR7sFo4M01Bg.jpeg" /><figcaption>Issues with current research in NLP. Image by Author.</figcaption></figure><p>In short, with increased output (models, publications, data sets), we have created a situation where these methods are widely used before they are fully understood, and an incentive system to perpetuate the situation.</p><h3>Early Adoption</h3><blockquote>We do not have complete control of language models. Adoption of new technologies without full awareness of their side effects is a risky take.</blockquote><p>The time from research to industry application has greatly shrunk in the last year. For example, today anyone can release a model on the HuggingFace repository and once that is done, it is ready available to be used by any researcher around the world. However, this ready availability might come with a high cost.</p><p>We know that models like GPT-3 contain systematic bias against minorities. Abid et al., 2021, show that GPT-3’s anti-muslim bias <em>appears consistently and creatively in different uses of the model.</em></p><p>Thus, how reliable can applications built using those models be?</p><p>In a<a href="https://cset.georgetown.edu/publication/truth-lies-and-automation/"> recent report</a>, Buchanan and colleagues suggested that while GPT-3 cannot create misinformation on its own, it can be used as a tool to generate high-quality misinformation messages in a way that has never been done before.</p><p>This gap between the widespread adoption and complete understanding (or GAU) is influenced by the different aspects we are going to see in the next sections of this blog post.</p><h3>Computational Papers</h3><blockquote>If we do not evaluate source code we cannot be sure about the quality of the paper.</blockquote><p>As a computational science, Natural Language Processing is filled with computational papers. New models or methodological approaches tend to be highly appreciated by the community, because they provide better solutions for a given task.</p><p>There is, however, limited consideration for the after evaluation of these papers. Once a paper is published, is it possible to use the code to replicate the results? How easy is it to do this?</p><p>This issue is already known in machine learning. For example, Musgrave et al (2020) have reported that due to methodological flaws in the experiments, the increase of accuracy in metric learning was wrongly reported in several papers.</p><p>To quickly discover methodological errors, it is important to have access to the code. Code release is an issue in our community as it happens to see code being released under the form of a jupyter-notebook with few comments.</p><p>Indeed, there is a lack of systematicity in the way these kinds of papers are evaluated. To name one issue, code review is not a mandatory practice, and a lot of published papers lack code altogether.</p><p>Better guidelines on how to design and release code can help alleviate this replication problem that affects our — and in general the ML — community. We already know the big advantage that easy to use code implementation have: HuggingFace is a noticeable example of this.</p><h3>Publication Bias</h3><blockquote>Publish or perish. An unfortunate saying that tends to be true and to which all academics have to abide by till tenure.</blockquote><p>Publishing papers and peer review are the foundations of modern science; you cannot propose a new model if you do not provide substantial proof that is novel and/or better than what other researchers have done in the past. Indeed, the quality of a researcher is assessed mainly through the quality of their research output.</p><p>However, paper review requires a lot of care and attention, and with the large number of papers submitted to our conferences, this task often rests on the shoulders of 3 reviewers and 1 or 2 area chairs. They have to evaluate dozens of papers and decide what is good and what is not.</p><p>But does this rule help science or it just puts junior researchers under pressure?</p><p>With this push towards publication, getting a paper published at a main conference in the field is becoming more and more difficult. To ease the process, services like ArXiv can be used to publish research. There is nothing wrong with ArXiv, but as a changeable venue with no barrier to entry, it comes with limitations: publication records built solely on ArXiv are set on quicksand and might fall over.</p><h3>Computational Unobtainablity</h3><blockquote>Most of us can use pre-trained BERT models, some of us can fine-tune BERT, very few of us can train BERT from scratch. Not to mention GPT-3.</blockquote><p>Can you train your own BERT model from scratch multiple times to evaluate your new hypothesis? Probably not: it takes a lot of computational power to train BERT even once, and doing this repeatedly is too demanding for all but a few research outfits. Even BERT fine-tuning is sometimes an operation with a high cost.</p><p>Evaluating papers by asking for impossible experiments is a form of gatekeeping that we need to take care of.</p><p>We need to be aware, when we review and analyze papers, that not everyone can retrain models like BERT, and that low-resource universities might not be able to provide the resources necessary even for fine-tuning.</p><h3>Unexplainable Methods</h3><blockquote>Limits of technologies are not less important than the advancements they can bring. We should describe GPT-3 limits alongside its capabilities.</blockquote><p>GPT-3 appeared on <a href="https://www.theguardian.com/commentisfree/2020/sep/08/robot-wrote-this-article-gpt-3">The Guardian</a> last year. The article was “written” by GPT-3 and led to a public outcry regarding the future of AI and of human labor. But while all the arguments made about the possibilities were well worth the discussion, a lot of people somehow forgot to also describe the limits of this method.</p><p>The description of limits didn’t find their way into newspapers; instead, they found their place in specialized journals that didn’t necessarily make it to the general public (Bender &amp; Koller, 2020; Floridi &amp; Chiriatti, 2020).</p><p>While it is true that some technological news sources described the issues related to GPT-3, these news didn’t make it to major newspapers.</p><p>The methods we have are often unexplainable in terms of how they work: telling people that GPT-3 can write articles might create a panic because the first hypothesis non-experts have is of machines rising against human labor. When we communicate these unexplainable methods to the public, we also need to describe the limits that these techniques have.</p><h3>Other Issues</h3><p>Obviously, these are not the only issues our field has to deal with. To mention two we did not cover here (but that are covered in other papers), I am pointing the reader to these papers:</p><ul><li>Dual-use issues (Lau &amp; Baldwin, 2020). Should we check if and how the technology we use can be somehow used in a bad manner?</li><li>Environmental Sustainability (Strubell et al, 2020). How are we going to take care of the fact that the models we are developing are not sustainable?</li></ul><h3>Conclusions</h3><p>This blog post explored some issues that the current publication trends in NLP have exacerbated to a point where it is not possible to ignore them. We keep pushing ever-larger models to market, without ensuring that we understand their risks, communicating their limits, or making them widely replicable. It is important to take action and provide solutions to these problems if we want future positive outcomes in our community.</p><p>If you are interested, you can find me on <a href="https://twitter.com/fb_vinid">twitter</a>.</p><h3>Acknowledgements</h3><p>Thanks to Dirk for editing and suggesting improvements to this article.</p><h3>References</h3><p>Bender, E. M., &amp; Koller, A. (2020, July). Climbing towards NLU: On meaning, form, and understanding in the age of data. In <em>Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics</em> (pp. 5185–5198).</p><p>Floridi, L., &amp; Chiriatti, M. (2020). GPT-3: Its nature, scope, limits, and consequences. <em>Minds and Machines</em>, <em>30</em>(4), 681–694.</p><p>Lau, J. H., &amp; Baldwin, T. (2020, July). Give Me Convenience and Give Her Death: Who Should Decide What Uses of NLP are Appropriate, and on What Basis?. In<em> Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics </em>(pp. 2908–2913).</p><p>Strubell, E., Ganesh, A., &amp; McCallum, A. (2019, July). Energy and Policy Considerations for Deep Learning in NLP. In <em>Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics</em> (pp. 3645–3650).</p><p>Abid, A., Farooqi, M., &amp; Zou, J. (2021). Persistent Anti-Muslim Bias in Large Language Models. <em>arXiv preprint arXiv:2101.05783</em>.</p><p>Musgrave, K., Belongie, S., &amp; Lim, S. N. (2020, August). A metric learning reality check. In <em>European Conference on Computer Vision</em> (pp. 681–699). Springer, Cham.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=971c3d63f524" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/on-the-gap-between-adoption-and-understanding-971c3d63f524">On the Gap between Adoption and Understanding</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[Sentiment Analysis and Emotion Recognition in Italian (using BERT)]]></title>
            <link>https://medium.com/data-science/sentiment-analysis-and-emotion-recognition-in-italian-using-bert-92f5c8fe8a2?source=rss-2aff872fe60e------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f5c8fe8a2</guid>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[italian]]></category>
            <dc:creator><![CDATA[Federico Bianchi]]></dc:creator>
            <pubDate>Thu, 01 Apr 2021 12:41:10 GMT</pubDate>
            <atom:updated>2021-04-02T19:09:29.795Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/thoughts-and-theory">Thoughts and Theory</a></h4><h4>Introducing FEEL-IT: a data set and a package for sentiment analysis and emotion recognition in Italian.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxBx-FNHcsjPulvdYehfAQ.png" /><figcaption>A screenshot of the sentiment and emotion classification library we have built.</figcaption></figure><h3>Sentiment Analysis and Emotion Recognition</h3><p>Recognizing emotions in text is fundamental to get a better sense of how people are talking about something. People can talk about a new event, but positive/negative labels might not be enough. There is a big difference between being angered by something and scared by something. This difference is why it is vital to consider sentiment and emotion in text.</p><p>There is a lot of research on sentiment analysis and emotion recognition…for English. A quick search on Google will bring you to different possible algorithms that can take care of sentiment/emotion prediction for you. However, some languages lack data, and one of these languages is Italian (but there is some work, for example, Sprugnoli, 2020).</p><p>So we (<a href="https://dnozza.github.io/">Debora</a>, <a href="http://dirkhovy.com/">Dirk</a>, and <a href="https://federicobianchi.io/">Yours Truly</a>) tried to provide a solution to this problem. We created a new data set for Italian sentiment and emotion prediction and fine-tuned a BERT model.</p><p>In this blog post, we describe our adventure in creating this new data set, explaining a few things we did and our results. What I am describing here is also available in a peer-reviewed research paper:</p><p>Federico Bianchi, Debora Nozza and Dirk Hovy (2021). <strong>FEEL-IT: Emotion and Sentiment Classification for the Italian Language</strong>. 11th Workshop on Computational Approaches to Subjectivity, Sentiment, and Social Media Analysis.</p><p>Since the ready availability of these methods is essential for the community, you can find online:</p><ul><li><a href="https://github.com/MilaNLProc/feel-it">our python package</a></li><li><a href="https://huggingface.co/MilaNLProc/feel-it-italian-sentiment">our HuggingFace sentiment model</a></li><li><a href="https://huggingface.co/MilaNLProc/feel-it-italian-emotion">our HuggingFace emotion model</a></li></ul><h3>FEEL-IT: Emotion and Sentiment Classification for the Italian Language</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeOe4dSpyrzwAge-bL7TnQ.png" /></figure><h4>Building a New Data Set for Sentiment and Emotion Recognition</h4><p>One of the issues that we need to address when creating a new data set is that it needs to be representative of the domain. One cannot collect two days of tweets with three keywords. The collected tweets would be too domain-dependent, making the trained models not general enough to be applied to different domains.</p><p>We took a different approach instead: we decided to collect 1000 tweets each day related to the trending topics on Twitter. In this way, we are getting the most relevant tweets of each day, and since every day there is something new to talk about, we collect a lot of different stuff. This approach allowed us to get a data set that contains tweets from a wide range of topics: from football matches to politics.</p><p>Then, we annotated the tweets with emotions, excluding those tweets that had no recognizable emotion. Eventually, we got to 2037 annotated tweets: 912 <strong>anger</strong>, 103 <strong>fear</strong>, 728 <strong>joy</strong>, 294 <strong>sadness.</strong></p><p>While not enormous, this data set, as we said, covers a wide range of different topics and is useful on a broader range of sentiment and emotion classification tasks.</p><p>You can see some examples of the annotated tweets (with also the English translation) in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKQzqPRGmkkUvus2QZjzyw.png" /><figcaption>Some examples of tweets with annotated emotion in our data set.</figcaption></figure><p>As you might expect, this process has a high cost in terms of annotation since we discard most of the tweets. However, it has very high precision since we collected tweets from a <strong>broad range of topics</strong> and because we <strong>have precise annotations</strong>.</p><h4>Fine-Tuning (Um)BERT(o)</h4><p>As standard in these recent pre-training times, we fine-tuned a BERT model with our proposed data set. BERT is one of the most popular neural architectures in Natural Language Processing. Fine-tuning BERT allows us to have a robust classification model to predict our labels. Fine-tuning is the operation that allows us to adjust the weights of the BERT model to perform our classification task.</p><p>There are many different BERT models for many languages (see Nozza et al., 2020, for a review and <a href="http://bertlang.unibocconi.it/">BERTLang</a>). Here, we use <a href="https://github.com/musixmatchresearch/umberto/">UmBERTo</a>, a very efficient Italian BERT model. In particular, we fine-tuned the UmBERTo model trained on the <a href="https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1">Common Crawl</a> data set.</p><h4>Sentiment Classification</h4><p>To evaluate our data set and model for sentiment analysis, we compared our FEEL-IT UmBERTo to the same model on another data set: <a href="http://www.di.unito.it/~tutreeb/sentipolc-evalita16/">SentiPolc16</a>. Both models are fine-tuned on the respective data.</p><p>SentiPolc comes with a training set and a test set. Thus, we evaluate the following interesting research question: is it better to use FEEL-IT or SentiPolc16?</p><p>We fine-tune on FEEL-IT and test on SentiPolc’s test set and compare it with fine-tuning on SentiPolc’s training set and testing on SentiPolc’s data set. Note that the model that uses SentiPolc in the training set should have a big advantage since we expect training and test to be similar. In the following picture, you can see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*dCi4lGqQxm2EnnT_z9az7w.png" /><figcaption>Results of the comparison between the use of FEEL-IT and SENTIPOLC16 as training set on the SENTIPOLC16 test set. Using FEEL-IT is better. Screenshot from our HuggingFace repository.</figcaption></figure><p>However, these results show that using FEEL-IT is much better than using the previous state-of-the-art data set, SentiPolc.</p><h4>Emotion Classification</h4><p>Now, there is no data set for emotion classification on Twitter outside our FEEL-IT. Thus, we ran a simple cross-validation, showing that a fine-tuned UmBERTo model can get us to <strong>0.71</strong> Macro-F1! That’s an excellent result!</p><h4>Creating a Python Library: FEEL-IT</h4><p>One of my passion is writing code, and I try to make libraries that other people can use. Thus, Debora and I have been working on a <a href="https://github.com/MilaNLProc/feel-it">little library</a> the wraps the HuggingFace internal APIs to provide a simple interface for emotion and sentiment prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxBx-FNHcsjPulvdYehfAQ.png" /><figcaption>Our library is super easy to use! :)</figcaption></figure><p>The good thing about the library is that it allows you to do quick emotion and sentiment classification with very low coding effort: you can load your pandas dataframe, extract the text, pass it to the library, and get the results. And this is precisely what we are going to do right now.</p><p>First things first: <strong>pip install -U feel-it </strong>in your command line :)</p><p>Here’s the small file we are going to play with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/522a5cdcd003c9ae2e489f5746c1e9bd/href">https://medium.com/media/522a5cdcd003c9ae2e489f5746c1e9bd/href</a></iframe><p>Now, let’s import our classifiers. The wrapper is going to take care of the downloads of the models for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93719dd14e4ad95cfdd7cca1f1a4bb97/href">https://medium.com/media/93719dd14e4ad95cfdd7cca1f1a4bb97/href</a></iframe><p>Now, let’s get the predictions! We just need to use the prediction method of the classifier we are interested in. The classifiers take as input a list of sentences — which in this case, we will get from the CSV file I have shown before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b248aec63d8ae829b6e2e8df7692430/href">https://medium.com/media/0b248aec63d8ae829b6e2e8df7692430/href</a></iframe><p>Do you see? With the library we have built, it is super easy to do sentiment and emotion classification in Italian!</p><h4>References</h4><p>Nozza, D., Bianchi, F., &amp; Hovy, D. (2020). <strong>What the [MASK]? Making Sense of Language-Specific BERT Models.</strong> <em>arXiv preprint arXiv:2003.02912</em>.</p><p>Bianchi, F., Nozza, D., &amp; Hovy, D. (2021). <strong>FEEL-IT: Emotion and Sentiment Classification for the Italian Language</strong>. 11th Workshop on Computational Approaches to Subjectivity, Sentiment and Social Media Analysis.</p><p>Sprugnoli, R. (2020). <strong>MultiEmotions-it: A new dataset for opinion polarity and emotion analysis for Italian.</strong> In 7th Italian Conference on Computational Linguistics, CLiC-it 2020 (pp. 402–408).</p><h4>Acknowledgements</h4><p>Many thanks to Debora and Dirk for the comments on this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f5c8fe8a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sentiment-analysis-and-emotion-recognition-in-italian-using-bert-92f5c8fe8a2">Sentiment Analysis and Emotion Recognition in Italian (using BERT)</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>