<?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 Carlo Borella on Medium]]></title>
        <description><![CDATA[Stories by Carlo Borella on Medium]]></description>
        <link>https://medium.com/@carbor100?source=rss-e38485ee556b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*knKlzPMLEsgNPHJyyWi43A.jpeg</url>
            <title>Stories by Carlo Borella on Medium</title>
            <link>https://medium.com/@carbor100?source=rss-e38485ee556b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:38:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carbor100/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[Automating Zero-Shot Classification Generating Model Labels with GPT-3]]></title>
            <link>https://pub.towardsai.net/automating-zero-shot-classification-generating-model-labels-with-gpt-3-2c688a917a97?source=rss-e38485ee556b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c688a917a97</guid>
            <category><![CDATA[labels]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[zero-shot-learning]]></category>
            <dc:creator><![CDATA[Carlo Borella]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 14:01:53 GMT</pubDate>
            <atom:updated>2023-04-03T14:01:53.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*_y8QxzncGFWd_Nkzumke6g.png" /><figcaption>Source: Image generated by the author using MidJourney</figcaption></figure><p>Zero-shot learning is a machine learning method that allows using a pre-trained model to classify data according to a set of classes or labels that have not been used to train the model. Zero-shot can be useful for various applications including:</p><ol><li>labeling data without spending time training or fine-tuning a model</li><li>labeling data because we don’t have a training set to train or fine-tune a model</li></ol><p>Traditionally, creating labels for a Zero-shot Classification task involves manually defining a set of potential classes or labels that the model can use to make predictions on the unseen data. This process can be time-consuming and error-prone, particularly for large datasets or complex domains.</p><p>By using OpenAI’s GPT-3 to generate labels for Zero-shot Classification models, we can significantly reduce the time and effort required to create this set of labels!</p><p>In this article, I will show how to build a zero-shot text classification model, integrating OpenAI’s GPT-3 for label creation (i.e., coming up with a set of labels relevant to the data we want to categorize) and HuggingFace zero-shot models for the actual text classification (i.e., classifying the data according to this set of labels).</p><p>To get started, we will need to install transformers and openai and import all the necessary modules:</p><pre>!pip install transformers<br>!pip install openai<br><br>from transformers import pipeline<br>import torch<br>from tqdm import tqdm<br>import pandas as pd<br>import openai<br>import requests</pre><p>We will also need to initialize the OpenAI API client with our API key:</p><pre>openai.api_key = (&quot;your key&quot;) #replace with your key</pre><p>Now that we have the necessary packages and API key, let’s define (1) a function to generate labels relevant to the corpus of texts we want to classify and (2) a function to classify the corpus based on the set of labels previously defined.</p><p>(1) First, define a function to generate the labels we will feed to our zero-shot classification model:</p><pre>def get_zero_shot_labels(domain, n_labels = None):<br>    if n_labels is None:<br>        prompt = &#39;You are picking the labels for a zero shot classification model, Generate a list of themes for the domain: {}&#39;.format(domain)<br>    else:<br>        prompt = &#39;You are picking the labels for a zero shot classification model, Generate a list with a minimum of {} themes for the domain: {}&#39;.format(n_labels, domain)<br>    response = openai.Completion.create(<br>        engine=&quot;text-davinci-002&quot;,<br>        prompt=prompt,<br>        max_tokens=40,<br>        n=1,<br>        stop=None,<br>        temperature=0.5,<br>    )<br>    text = response[&quot;choices&quot;][0][&quot;text&quot;]<br>    labels = [label.strip(&#39;-&#39;) for label in text.split(&#39;\n&#39;)]<br>    return(labels)</pre><p>This function uses GPT-3 (alternatively, you can use GPT-4) to generate a set of labels relevant to the specified domain we are interested in.</p><p>get_zero_shot_labels has two inputs:</p><ul><li>domain is a string containing the description of the relevant domain for the data we will feed to the zero-shot classification model (e.g., restaurant reviews, football news, etc.)</li><li>n_labels is the minimum number of labels that we want to generate. If n_labels is not specified, the function will generate an unspecified number of labels for the specified domain.</li></ul><p>(2) Next, we will define a function to classify our input data based on the list of possible labels we previously created with get_zero_shot_labels:</p><pre>def zero_shot_classification(text_lst, labels ,model, multi_label = False):<br><br>    device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>    classifier_pipeline = pipeline(&quot;zero-shot-classification&quot;, model = model, multi_label = multi_label, device=device)<br>    preds = []<br>#loop for each text in text_list<br>    for input_sequence in tqdm(text_lst, total=len(text_lst)):<br>        pred = classifier_pipeline(input_sequence, labels)<br>        label_scores = dict(zip(pred[&#39;labels&#39;], pred[&#39;scores&#39;]))<br>        preds.append(label_scores)<br>#store the labels probabilities in a df<br>    preds_df = pd.DataFrame(preds)<br><br>    return(preds_df)</pre><p>The function has 4 inputs:</p><ul><li>text_lst: A list of strings representing the data to be classified.</li><li>labels: the set of labels to classify the data accordingly.</li><li>model: A string that represents the zero-shot classification model to use.</li><li>multi_label: A boolean flag indicating whether the model should output multiple labels per input sequence.</li></ul><p>Once we have our label generator function and the function to classify texts, we can combine the two into an end-to-end zero-shot classifier with little human input.</p><p>So now it is time to put them together: end_to_end_zero_shot combines the label generation code with the text classifier to provide an end-to-end solution for Zero-shot text classification:</p><pre>def end_to_end_zero_shot(domain, text_lst , n_labels =None , model = &quot;valhalla/distilbart-mnli-12-3&quot;, multi_label = False):<br><br>  labels = get_zero_shot_labels(domain, n_labels = n_labels)<br>  print(labels)<br>  user_input = input(&quot;proceed with these labels (yes/no)&quot;).lower()<br>  if user_input == &quot;yes&quot;:<br>    preds_df = zero_shot_classification(text_lst, labels ,model, multi_label = multi_label)<br>    return(preds_df)<br>  else:<br>    print(&#39;modify your prompt and/or retry.&#39;)<br>    return(labels)</pre><p>I am using “valhalla/distilbart-mnli-12–3”, which is a distilled version of bart-large-mnli (it runs faster), as my default model, but you can try it with others.</p><p>In the function, I also included user_input prompting the user to examine the labels proposed by GPT before proceeding with labeling the corpus.</p><p>Finally, here is an example:</p><pre>domain = &#39;restaurants reviews&#39;<br>text_lst = [ &quot;The food was amazing!&quot;,<br>    &quot;The service was slow and the staff was unfriendly.&quot;,<br>    &quot;The ambiance was perfect for a romantic dinner.&quot;,<br>    &quot;The prices were too high for the quality of the food.&quot;,<br>    &quot;I highly recommend this restaurant!&quot;]<br><br>results = end_to_end_zero_shot(domain, text_lst , n_labels =None , model = &quot;valhalla/distilbart-mnli-12-3&quot;, multi_label = False)</pre><pre>[&#39;Food quality&#39;, &#39;Service quality&#39;, &#39;Price&#39;, &#39;Atmosphere&#39;, &#39;Location&#39;, &#39;Menu&#39;, &#39;Dietary restrictions&#39;]<br>proceed with these labels (yes/no)yes<br>100%|██████████| 5/5 [00:09&lt;00:00,  1.85s/it]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd1NcUZNcT_g4GIF9U_lMg.png" /><figcaption>The predictions for each of the 5 examples we are classifying, with the probability distribution for each label. you can use the probabilities to assign a label to your text examples.</figcaption></figure><h3>End Note</h3><p>In this article, we discussed how to implement a Zero-shot text classification algorithm automating the label generation process using GPT-3 (or GPT4, even better!). For this implementation, I am assuming that the corpus we are labeling belongs to a given domain (therefore, the labels produced by GPT-3 will be relevant)</p><p>I appreciate any feedback and constructive criticism! My email is carbor100@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c688a917a97" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/automating-zero-shot-classification-generating-model-labels-with-gpt-3-2c688a917a97">Automating Zero-Shot Classification Generating Model Labels with GPT-3</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove Text from Images using CV2 and Keras-OCR]]></title>
            <link>https://medium.com/data-science/remove-text-from-images-using-cv2-and-keras-ocr-24e7612ae4f4?source=rss-e38485ee556b------2</link>
            <guid isPermaLink="false">https://medium.com/p/24e7612ae4f4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Carlo Borella]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 12:28:15 GMT</pubDate>
            <atom:updated>2022-05-03T13:48:04.597Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to automatically modify images to make them text-free using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3L4ThlC_2sKnhMY4fsieXw.png" /><figcaption>An example of before and after removing text using Cv2 and Keras. Source: image by the author processing an image by <a href="https://pixabay.com/users/morningbirdphoto-129488/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1605416">morningbirdphoto</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1605416">Pixabay</a>.</figcaption></figure><h3><strong>Introduction</strong></h3><p>In this article I will discuss how to quickly remove text from images as a pre-processing step for an image classifier or a multi-modal text and image classifier involving images with text such as memes (for instance the <a href="https://ai.facebook.com/blog/hateful-memes-challenge-and-data-set/">Hateful Memes Challenge</a> by Facebook).</p><p>Removing text can be useful for a variety or reasons, for example we can use the text-free images for data augmentation as we can now pair the text-free image with a new text.</p><p>For this tutorial we will use OCR (Optical Character Recognition) to detect text inside images, and inpainting - the process where missing parts of a photo are filled in to produce a complete image - to remove the text we detected.</p><h3>The Process</h3><p>In order to erase text from images we will go through three steps:</p><ol><li>Identify text in the image and obtain the bounding box coordinates of each text, using Keras-ocr.</li><li>For each bounding box, apply a mask to tell the algorithm which part of the image we should inpaint.</li><li>Finally, apply an inpainting algorithm to inpaint the masked areas of the image, resulting in a text-free image, using cv2.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuIbDBC-qKw0r-SgoRisiA.png" /><figcaption>A representation of the process from an image with text to a text-free image. Source: Image by Author.</figcaption></figure><h3>The Implementation</h3><h4><strong>Brief overview of Keras-ocr</strong></h4><p>Keras-ocr provides out-of-the-box OCR models and an end-to-end training pipeline to build new OCR models (see: <a href="https://keras-ocr.readthedocs.io/en/latest/">https://keras-ocr.readthedocs.io/en/latest/</a>).</p><p>In this case we will use the pre-trained model, which works fairly well for our task.</p><p>Keras-ocr would automatically download the pre-trained weights for the detector and recognizer.</p><p>When passing an image through Keras-orc it will return a (word, box) tuple, where the box contains the coordinates (x, y) of the four box corners of the word.</p><p>Here is a quick example:</p><pre>import matplotlib.pyplot as plt<br>import keras_ocr</pre><pre>pipeline = keras_ocr.pipeline.Pipeline()</pre><pre>#read image from the an image path (a jpg/png file or an image url)<br>img = keras_ocr.tools.read(image_path)</pre><pre># Prediction_groups is a list of (word, box) tuples<br>prediction_groups = pipeline.recognize([img])</pre><pre>#print image with annotation and boxes<br>keras_ocr.tools.drawAnnotations(image=img, predictions=prediction_groups[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xsh7LPrYTY2_0_I52rXOhw.png" /><figcaption>Source: Image by <a href="https://pixabay.com/users/paulsteuber-2493539/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3794348">Paul Steuber</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3794348">Pixabay</a>.</figcaption></figure><p>If we take a look at prediction_groups we will see that each element corresponds to a pair of word-box coordinates.</p><p>For example, prediction_groups[0][10] would look like:</p><pre>(&#39;tuesday&#39;,<br> array([[ 986.2778 ,  625.07764],<br>        [1192.3856 ,  622.7086 ],<br>        [1192.8888 ,  666.4836 ],<br>        [ 986.78094,  668.8526 ]], dtype=float32))</pre><p>The first element of the array corresponds to the coordinates of the top-left corner, the second element corresponds to the bottom-right corner, the third elements is the top-right corner, while the fourth element is the bottom-left corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZPImi8VDdhPbTJMDSljrw.png" /><figcaption>A representation of a text bounding box, and its coordinates. Source: Image by Author.</figcaption></figure><h4><strong>Brief overview of cv2 inpaint functions</strong></h4><p>When applying an inpainting algorithm using OpenCV we need to provide two images:</p><ol><li><strong>The input image with the text we want to remove.</strong></li><li><strong>The mask image, which shows where in the image the text that we want to remove is. </strong>This second image should have the same dimensions as the input. The mask will display non-zero pixels corresponding to those areas of the input image that contain text and would be inpainted, while the areas where we have zero pixels won’t be modified.</li></ol><p>Cv2 features two possible inpainting algorithms and allows to apply rectangular, circular or line masks (see: <a href="https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_photo/py_inpainting/py_inpainting.html">https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_photo/py_inpainting/py_inpainting.html</a>)</p><p>In this case I decided to use line masks, as they are more flexible to cover text with different orientations (rectangular masks would only work well for words parallel or perpendicular to the x-axis and circular masks would cover an area larger than necessary).</p><p>In order to apply the mask we need to provide the coordinates of the starting and the ending points of the line, and the thickness of the line:</p><p>The start point will be the mid-point between the top-left corner and the bottom-left corner of the box while the end point will be the mid-point between the top-right corner and the bottom-right corner.</p><p>For the thickness we will calculate the length of the line between the top-left corner and the bottom-left corner.</p><pre>import math<br>import numpy as np</pre><pre>def midpoint(x1, y1, x2, y2):<br>    x_mid = int((x1 + x2)/2)<br>    y_mid = int((y1 + y2)/2)<br>    return (x_mid, y_mid)</pre><pre>#example of a line mask for the word &quot;Tuesday&quot;</pre><pre>box = prediction_groups[0][10]</pre><pre>x0, y0 = box[1][0]<br>x1, y1 = box[1][1] <br>x2, y2 = box[1][2]<br>x3, y3 = box[1][3] <br>        <br>x_mid0, y_mid0 = midpoint(x1, y1, x2, y2)<br>x_mid1, y_mi1 = midpoint(x0, y0, x3, y3)<br>thickness = int(math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 ))</pre><p>Now we can create our mask:</p><pre>mask = np.zeros(img.shape[:2], dtype=&quot;uint8&quot;)<br>cv2.line(mask, (x_mid0, y_mid0), (x_mid1, y_mi1), 255, thickness)<br></pre><p>We can also check the masked area to make sure it is working properly.</p><pre>masked = cv2.bitwise_and(img, img, mask=mask)<br>plt.imshow(masked)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*qtSPYlg9TeTst2_usvdHEA.png" /><figcaption>The masked area corresponding to the word “Tuesday”.</figcaption></figure><p>Finally, we can inpaint the image. In this case we will be using cv2.INPAINT_NS which refers to the inpainting algorithm described in the paper <strong>“Navier-Stokes, Fluid Dynamics, and Image and Video Inpainting”.</strong></p><pre>img_inpainted = cv2.inpaint(img, mask, 7, cv2.INPAINT_NS)<br>plt.imshow(img_inpainted)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBC2lrSJWyR3kf75EuT13w.png" /></figure><p>As you can see the work “Tuesday” was removed from the image.</p><h3>The Implementation</h3><p>Now let’s wrap it up altogether and create a function to inpaint text from any image.</p><p>We will just need to generate the list of boxes and iterate masking and inpainting each text box.</p><pre>import matplotlib.pyplot as plt<br>import keras_ocr<br>import cv2<br>import math<br>import numpy as np</pre><pre>def midpoint(x1, y1, x2, y2):<br>    x_mid = int((x1 + x2)/2)<br>    y_mid = int((y1 + y2)/2)<br>    return (x_mid, y_mid)</pre><pre>pipeline = keras_ocr.pipeline.Pipeline()</pre><pre>def inpaint_text(img_path, pipeline):<br>    # read image<br>    img = keras_ocr.tools.read(img_path)<br>    # generate (word, box) tuples <br>    prediction_groups = pipeline.recognize([img])<br>    mask = np.zeros(img.shape[:2], dtype=&quot;uint8&quot;)<br>    for box in prediction_groups[0]:<br>        x0, y0 = box[1][0]<br>        x1, y1 = box[1][1] <br>        x2, y2 = box[1][2]<br>        x3, y3 = box[1][3] <br>        <br>        x_mid0, y_mid0 = midpoint(x1, y1, x2, y2)<br>        x_mid1, y_mi1 = midpoint(x0, y0, x3, y3)<br>        <br>        thickness = int(math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 ))<br>        <br>        cv2.line(mask, (x_mid0, y_mid0), (x_mid1, y_mi1), 255,    <br>        thickness)<br>        img = cv2.inpaint(img, mask, 7, cv2.INPAINT_NS)<br>                 <br>    return(img)</pre><p>and here is the final result (before vs after):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jefi9rQ9PtiXoVXltMK5Bw.png" /></figure><p>I also included another couple of examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ka6w4u3fEKELSM28ScAsLg.png" /><figcaption>Source: image by the author generated by processing a meme from <a href="https://www.facebook.com/hackernoon/?__tn__=-UC*F">HackerNoon</a>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEe7Cm6gN0h_ob4gGZfq0w.png" /><figcaption>Source: image by the author generated by processing an image by <a href="https://pixabay.com/users/derks24-5892478/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5026397">Alfred Derks</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=5026397">Pixabay</a>.</figcaption></figure><p>Note that if you want to save the image you will need to convert it to the RGB format, otherwise the colours will be inverted!</p><pre>img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)</pre><pre>cv2.imwrite(‘text_free_image.jpg’,img_rgb)</pre><p>In case you were interested in removing certain words only, an if-condition can be included as follows:</p><p>Given a list of words to remove</p><pre>remove_list = [‘tuesday’, ‘monday’]</pre><p>We can include the if condition in the for-loop</p><pre>def inpaint_text(img_path, remove_list, pipeline):<br>    # read image<br>    img = keras_ocr.tools.read(img_path)<br>    # generate (word, box) tuples <br>    prediction_groups = pipeline.recognize([img])<br>    mask = np.zeros(img.shape[:2], dtype=&quot;uint8&quot;)<br>    for box in prediction_groups[0]:<br>        if box[0] in remove_list:</pre><pre>           x0, y0 = box[1][0]<br>           x1, y1 = box[1][1] <br>           x2, y2 = box[1][2]<br>           x3, y3 = box[1][3] <br>        <br>           x_mid0, y_mid0 = midpoint(x1, y1, x2, y2)<br>           x_mid1, y_mi1 = midpoint(x0, y0, x3, y3)<br>        <br>           thickness = int(math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 ))<br>        <br>           cv2.line(mask, (x_mid0, y_mid0), (x_mid1, y_mi1), 255,    <br>           thickness)<br>           img = cv2.inpaint(img, mask, 7, cv2.INPAINT_NS)<br>                 <br>    return(img)</pre><p>This of course is just a quick case-sensitive example on how to apply the inpainting to just a certain list of words.</p><h3>End Notes</h3><p>In this article, we discussed how to implement an algorithm to automatically remove text from images with a pre-trained OCR model using Keras and an inpainting algorithm using cv2. The algorithm seems to work fairly well to quickly remove text from images without the need to train a model for this specific task. It generally performs not as well when a text box is close to other objects as it may distort the surroundings.</p><p>Edit: the implementation was executed using Python 3.7, I received a few feedbacks of problems encountered using OpenCv which happen when using other versions such as Python 3.9. I would suggest to try with 3.7 instead to fix the issue.</p><p>I appreciate any feedback and constructive criticism! My email is carbor100@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e7612ae4f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/remove-text-from-images-using-cv2-and-keras-ocr-24e7612ae4f4">Remove Text from Images using CV2 and Keras-OCR</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>