<?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 Gaby A on Medium]]></title>
        <description><![CDATA[Stories by Gaby A on Medium]]></description>
        <link>https://medium.com/@gabya06?source=rss-15998130867b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b0oWWoe1Der9g5CSJmviQQ@2x.jpeg</url>
            <title>Stories by Gaby A on Medium</title>
            <link>https://medium.com/@gabya06?source=rss-15998130867b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:00:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabya06/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 Step-by-Step Deployment Guide: Streamlit, Docker and Google Cloud]]></title>
            <link>https://medium.com/@gabya06/a-step-by-step-deployment-guide-streamlit-docker-and-google-cloud-fc4e62c92e3e?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4e62c92e3e</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Wed, 28 May 2025 16:01:06 GMT</pubDate>
            <atom:updated>2025-05-28T16:01:06.054Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@gabya06/paws-pixels-and-prompts-building-a-genai-pipeline-for-cat-breed-discovery-443ebe99b91b">previous post</a>, I shared how I built a GenAI application using CLIP embeddings and RAG to classify cat breeds using image and text inputs. Building the app was only half the journey —<strong><em>sharing</em></strong> it with fellow cat lovers meant turning a local prototype into something anyone could access. At first, I figured I <em>could</em> just show people my localhostURL… But I quickly realized that if I wanted real feedback, I needed to <strong><em>deploy </em></strong>it.</p><p>That’s where <strong>Docker </strong>and <strong>Google Cloud Run</strong> came in.</p><p>This post documents my <strong><em>deployment</em></strong> journey, including some of the roadblocks I faced, what I learned and how I overcame them. If this is your first time deploying your ML application to the cloud, keep on reading! You’ll find practical solutions to common challenges here.</p><p><strong>What We’ll Cover:</strong></p><ul><li>🐳 <strong>Dockerfile, Image and Container</strong>: Core Docker Concepts</li><li>🧱 <strong>Building and Testing Docker Images</strong></li><li>🚀 <strong>Deploying to Google Cloud Run</strong></li><li>🛠 <strong>Lessons Learned</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZXTLvpkJ4wmUoSEe" /></figure><h3>Required Installations</h3><p>To containerize and deploy your app, you will need a couple of tools set up locally:</p><p><a href="https://docs.docker.com/desktop/setup/install/mac-install/"><strong>Docker</strong></a></p><p>I used Docker Desktop for Mac with Apple Silicon (M2).</p><p>To confirm Docker is installed, run the follow in terminal:</p><pre># Verify installation<br>docker --version</pre><p><a href="https://cloud.google.com/sdk/docs/install"><strong>Google Cloud CLI</strong></a><strong> (gcloud)</strong></p><p>After downloading from Google Cloud Platform, install it with:</p><pre># Run the installer<br>./google-cloud-sdk/install.sh<br><br># Initialize your configuration<br>gcloud init</pre><h3>🗂 Project Structure and Organization</h3><p>A clean project structure makes containerization a lot easier and more straightforward. Here is how I organized my app:</p><pre>cat_breeds/<br>└── src/<br>    ├── app/                  ← Streamlit UI + logic helpers<br>    ├── cat_breeds/           ← Core prediction logic, embeddings, RAG logic<br>    └── db/                   ← ChromaDB files<br>    └── data/                 ← Cat breed data csv file<br>├── app.py                    ← Streamlit entry point<br>└── pyproject.toml            ← Project dependencies<br>└── DockerFile           ← Container configuration<br>└── .dockerignore        ← Files to exclude from container</pre><h3>🐳 Core Docker Concepts: Dockerfile, Image, and Container</h3><p>Before I could deploy my cat breed GenAI app, I needed to understand three <em>key Docker concepts</em> that confused me when I was getting started: the <strong>Dockerfile</strong>, the <strong>Docker Image</strong>, and the <strong>Docker Container</strong>.</p><h4>📄 Dockerfile — The App Blueprint</h4><p>A <strong>Dockerfile</strong> is a plain text file that describes how to build your app’s environment from scratch. It defines everything your app needs to run.<br>It is <strong><em>step-by-step instructions</em></strong> to:</p><ul><li>Install system libraries and Python dependencies</li><li>Copy your code, data, and app files</li><li>Set the working directory</li><li>Tell Docker how to run the app</li></ul><p>You don’t “run” a Dockerfile directly — you use it to build a Docker <strong>image</strong>.</p><p>For my project cat-breeds-app, the Dockerfile included everything from installing torch, copying Chroma embeddings, to launching Streamlit on the correct port.</p><h4>📦 Docker Image — A Packaged Snapshot of the App</h4><p>A <strong>Docker image</strong> is a packaged, <em>read-only </em>snapshot of your app and its environment — <strong><em>created from the Dockerfile</em></strong>.</p><p>For cat-breeds-app, my image included:</p><ul><li>All dependencies like Streamlit, Transformers, CLIP, ChromaDB, etc</li><li>My app logic — including app.py, embeddings and prediction code</li><li>The working directory and runtime instructions</li></ul><p>You build the Docker image with:</p><pre>docker build -t cat-breeds-app .</pre><h4>🚀 Docker Container — A Running Instance of the App</h4><p>A <strong>Docker container</strong> is your <em>app in action</em>: it is <em>running</em> in a clean, isolated environment with everything it needs. ▶️ Imagine a “play” button on your Docker image.</p><p><strong>Docker Containers</strong>:</p><ul><li>Are isolated environments — they don’t affect your local system</li><li>Can be stopped, started, deleted, or rebuilt at any time</li><li>Run the exact same way every time, regardless of when you deploy them</li></ul><p>To launch a Docker container:</p><pre>docker run -p 8501:8501 cat-breeds-app</pre><h4>🔁 Typical Docker Workflow:</h4><pre># Build the image (after creating DockerFile)<br>docker build -t cat-breeds-app .<br><br># Run the app in a container<br>docker run -p 8501:8501 cat-breeds-app</pre><h4><strong>Key Notes:</strong></h4><ul><li><strong>Images are <em>immutable</em></strong> — once built, they don’t change. If you modify code or data, you will need to <strong><em>rebuild</em></strong> the image.</li><li><strong>Containers are <em>ephemeral</em></strong> — they spin up, run, and can be destroyed or rebuilt.</li><li>Docker makes it <strong><em>repeatable</em></strong> — it’s great to have repeatable results, that don’t just “work on my machine”!</li></ul><h4>📄 My Dockerfile</h4><p>Here’s the exact Dockerfile I used — feel free to copy and update it for your own project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e9d8d165d1d6898d8cc0471865ebc4b/href">https://medium.com/media/3e9d8d165d1d6898d8cc0471865ebc4b/href</a></iframe><h4>Key Notes:</h4><ul><li><strong>Dependencies</strong>: pip install -e . installs my package in <a href="https://pip.pypa.io/en/stable/cli/pip_install/"><em>editable</em></a> mode inside the container. My dependencies live in pyproject.toml, which lets me manage them cleanly using <a href="https://peps.python.org/pep-0621/">PEP 621</a>.</li><li><strong>Order matters:</strong> Put stable steps like base images and pip installs at the top to leverage caching.</li><li><strong>Use </strong>.dockerignore: This excludes unnecessary files like data/, __pycache__, .venv/.</li></ul><h3>🛠 Build the Docker Image</h3><p>To build your image using the linux/amd64 architecture that is required by Google Cloud Run:</p><pre>docker buildx build --platform linux/amd64 \<br>-t gcr.io/cat-breeds-app/cat_breeds . --load</pre><p>🔍 <strong>Flag breakdown:</strong></p><ul><li>buildx build: Uses <strong>Buildx</strong>, a Docker plugin that supports building images for <strong>multiple platforms</strong> (e.g., ARM64, AMD64)</li><li>--platform linux/amd64: Ensures compatibility with Cloud Run (especially on M1/M2 Macs)</li><li>-t gcr.io/...: Tags the image with for GCR path</li><li>.: Builds from the <strong>current directory</strong> — this must contain your Dockerfile</li><li>load: <strong>Loads the image into your local Docker engine</strong>, so you can run it and test it</li></ul><h3>Test the Image Locally</h3><p>Run it <em>interactively</em> to test the image and make sure it works as expected:</p><pre>docker run -it -p 8501:8501 \<br>--platform linux/amd64 \<br>-e GEMINI_API_KEY=your_api_key \<br>gcr.io/cat-breeds-app/cat_breeds /bin/bash</pre><p>🔍 <strong>Flag breakdown:</strong></p><ul><li>--it: Opens an <strong>Interactive terminal </strong>(you can run commands inside)</li><li>-p 8501:8501: <strong>Maps</strong> Port 8501 so you can open the app in your browser</li><li>--platform linux/amd64: Match your <strong>build architecture</strong></li><li>/bin/bash: Launches the container in <strong>shell mode</strong> so you can run commands manually</li></ul><p>Inside the container:</p><pre>streamlit run app.py --server.port=8501 --server.address=0.0.0.0</pre><p>❇️ If you see a link with 0.0.0.0:8501, that means it’s ready and exposed externally. You’re good to go!</p><p><strong>Note</strong>: If you leave off --server.address=0.0.0.0, the app will bind only to localhost and it won’t be reachable from your browser.</p><h3>☁️ Deploying to Google Cloud Run</h3><ol><li><strong>Create your project and enable API’s</strong></li></ol><pre>gcloud projects create cat-breeds-app<br><br># Set project<br>gcloud config set project cat-breeds-app<br><br># Enable Cloud Run, Artifact Registry, etc.<br>gcloud services enable run.googleapis.com artifactregistry.googleapis.com<br></pre><p><strong>2. Authenticate and Configure Docker</strong></p><pre>gcloud auth login<br>gcloud auth configure-docker</pre><p><strong>3. Tag your image for Google Container Registry (GCR):</strong></p><pre>docker tag cat-breeds-app gcr.io/cat-breeds-app/cat_breeds</pre><p><strong>Note</strong>: I had originally built my image with the local name cat-breeds-app, so I needed to tag it with the proper GCR path before pushing. Google Cloud requires images to be tagged using the registry path gcr.io/... in order to deploy it to Cloud Run.</p><p>If you already built your image with the correct GCR tag (e.g: gcr.io/cat-breeds-app/cat_breeds), you can skip this step.</p><p><strong>4. Push Image to Google Container Registry:</strong></p><p>Once you’re happy with the local result and want to deploy the app:</p><pre>docker push gcr.io/cat-breeds-app/cat_breeds</pre><p><strong>5. Deploy the app to Cloud Run:</strong></p><pre>gcloud run deploy cat-breeds-app \<br>  --image gcr.io/cat-breeds-app/cat_breeds \<br>  --platform managed \<br>  --region us-east1 \<br>  --allow-unauthenticated \<br>  --memory 4Gi</pre><p>🔍 <strong>Flag breakdown:</strong></p><ul><li>--platform managed: Use the fully managed version of Cloud Run</li><li>--region us-east1: This should match your GCP project region (close to your users)</li><li>--allow-unauthenticated: Makes the app public — great for demos and sharing! As a note, in a work setting this would <em>obviously change</em>.</li><li>--memory 4Gi: More memory = less crashing when loading models</li></ul><p>Once your app is deployed, a <strong>service URL</strong> is created which you can share publicly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*7m54c0WTmy_iIoqiuNFvhQ.png" /></figure><h3>Google Cloud Environment Variables and Oath</h3><p><strong>Set up Oath Client ID</strong></p><ul><li>In GCP Console: Go to <strong>APIs &amp; Services &gt; Credentials</strong></li><li>Choose <strong>OAuth client ID</strong>, set type to <strong>Web App</strong>.</li><li>Add any necessary redirect URIs or leave blank if unused.</li></ul><p><strong>Environment Variables</strong></p><p>In Cloud Run’s deploy panel, use the <strong>Variables &amp; Secrets </strong>tab to configure any required variables like API keys.</p><h3>🧠 Lessons Learned</h3><p><em>What fun would deploying your first app be without errors?</em></p><p>In this section, I would like to share some of the errors I came across during my deployment journey:</p><h4>❌ ERR_CONNECTION_REFUSED</h4><p>Usually happens if:</p><ul><li>Port 8501 might <em>already be in use</em>. In your terminal, to check and kill it: lsof -i:8501</li><li>Maybe you forgot --server.address=0.0.0.0. Make sure you add it!</li><li>Forgot to map ports? Use — p 8501:8501</li></ul><h4>❌ exec format error</h4><p>This usually means you built your image using Apple’s arm64 (Apple Silicon) but deployed to a platform expecting amd64 (like Google Cloud Run).</p><p>Always build using: --platform linux/amd64</p><h4>❌ Streamlit not loading in Cloud Run</h4><p>Streamlit runs on PORT=8501 and Cloud Run expects containers to listen on PORT=8080. To fix this and support both, use this in your Dockerfile:</p><pre>CMD streamlit run app.py --server.port=${PORT:-8501} --server.address=0.0.0.0</pre><p>This defaults to 8501 if PORT isn’t defined.</p><h3>🧱 Dealing with Large Docker Images</h3><p>At one point my image was close to <strong>10GB</strong> 😱 — that’s huge!! It totally confused me…</p><h3>‼️ What happened?</h3><p>My app seemed to be running — I saw the container spin up, no errors, the logs looked fine…But when I opened the app in the browser: <strong>nothing happened!</strong> There was just a blank page.</p><p>I <em>eventually</em> realized the container didn’t have enough memory to load everything, after having wasted quite a bit of time… The image size was way too large.</p><h4>🤯 What was the Problem?</h4><ul><li>I hadn’t added a proper .dockerignore file</li><li>I was copying <strong>everything</strong> into the container with COPY . /app — including: data, .venv/ and.ipynb_checkpoints</li><li>pip install torch was installing <strong>GPU support and CUDA binaries</strong> by default, even though I only needed CPU.</li></ul><h4>🧽 How I fixed it:</h4><ul><li>I created a clean .dockerignore file:</li></ul><pre>.venv<br>__pycache__<br>.DS_Store<br>.git<br>.ipynb_checkpoints<br>data/</pre><ul><li>I explicitly installed the CPU-only version of torch:</li></ul><pre>  pip install torch==2.6.0+cpu \<br>  --extra-index-url https://download.pytorch.org/whl/cpu</pre><ul><li>I moved large runtime files like Chroma DB and mounted them during local dev using:</li></ul><pre>-v $(pwd)/db:/app/db</pre><h4>🤔 So… how big <em>should</em> your image be?</h4><p>There’s no hard rule, but for a Python Streamlit app:</p><ul><li><strong>&lt;1GB</strong> is great</li><li><strong>1–2GB</strong> is common with large models or dependencies</li><li><strong>&gt;3GB</strong> is probably too much and could be cut down</li></ul><h4>💡 Bonus tips</h4><pre># To check image size:<br>docker image ls<br><br># To clean up unused images and containers:<br>docker system prune --all</pre><h3>Debugging Cloud Run</h3><p><strong><em>Check logs:</em></strong></p><pre>gcloud run services logs read cat-breeds-app --region=us-east1</pre><p><strong><em>Common causes of blank screens:</em></strong></p><ul><li>Not setting the <strong>right port</strong></li><li>Image missing app.py</li><li>Streamlit errors silently failing</li></ul><h3>Final Thoughts</h3><p>At first containerizing my GenAI app felt like a daunting task, but it really wasn’t that difficult! And, it felt really rewarding to be able to share my app with colleagues and friends! I learned how to:</p><ul><li>Build reproducible environments</li><li>Debug tricky architecture issues on M2</li><li>Push a full-stack app to production</li><li>Keep my Docker images lean and clean</li></ul><h3>🐱 Want to try it?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6K0F1feNYhWmDbUY2FEXgA.gif" /></figure><h4>🐾 Check out the live <a href="https://cat-breeds-app-624036724229.us-east1.run.app/">Cat Breeds App</a></h4><h4>💻 See the code on <a href="https://github.com/Gabya06/cat_breeds/tree/main">GitHub</a></h4><h4>🐾 <strong>Questions?</strong></h4><p>Drop a comment below or reach out if you’re interested in collaborating or learning more about my project. Feel free to connect with me on <a href="https://linkedin.com/in/gabrielleagrocostea">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4e62c92e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paws, Pixels, and Prompts: Building a GenAI Pipeline for Cat Breed Discovery ]]></title>
            <link>https://medium.com/@gabya06/paws-pixels-and-prompts-building-a-genai-pipeline-for-cat-breed-discovery-443ebe99b91b?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/443ebe99b91b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 13:02:31 GMT</pubDate>
            <atom:updated>2025-04-17T13:02:31.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Paws, Pixels, and Prompts: A GenAI Pipeline for Cat Breed Search with CLIP, RAG and ChromaDB <strong>😸</strong></h3><p>Welcome to my journey of using GenAI, CLIP, and ChromaDB to classify cat breeds in a unique multimodal pipeline! From scraping breed data to building embeddings and enabling image-based queries, I’ll walk through how I built a full-stack GenAI project — powered by Retrieval-Augmented Generation (RAG) — all inspired by my love of cats. 🐾</p><p>As a lifelong cat lover, I thought why not combine my passion for cats with cutting-edge AI? My goal was to build a system that can understand cat breeds visually and retrieve facts about them when asked. Sure, I could just ask ChatGPT… but then I wouldn’t get <em>hands-on experience with full-stack GenAI</em> concepts.</p><p>In this project, I will discuss the following:</p><ul><li>Combining structured API data and images</li><li>Generating image and text embeddings using CLIP</li><li>Storing and querying information using ChromaDB</li><li>Using Gemini to answer questions in natural language</li></ul><h3>🤔 But What is RAG?</h3><p>Let’s start by explaining what RAG is and why it is so powerful!</p><p><strong>Retrieval-Augmented Generation (RAG)</strong> is a technique where relevant documents are retrieved first and then passed into a large language model to generate better, more grounded responses. In this project, I built a mini RAG system that can answer questions about cat breeds — using both images and text!</p><h3><strong>🐱 </strong>Data Ingestion — CatAPI</h3><p>I started by scraping Wikipedia for breed data, but realized it required a lot of data cleaning. Instead, I found the <a href="https://thecatapi.com/">CatAPI</a> which provided clean, structured data and free access to images.</p><p>The free tier allowed me to collect information on about 65 cat breeds, including images, temperament, origin, shedding level and more. (There’s a DogAPI too, but we’re sticking with cats here!)</p><p>Here is how I pulled breed data:</p><pre>import os<br>import requests<br>from dotenv import load_dotenv<br>import pandas as pd<br><br># Load CATAPI key<br>load_dotenv()<br>CAT_API_KEY = os.getenv(&quot;CAT_API_KEY&quot;)<br><br># Base URL for CatAPI<br>BASE_URL = &quot;https://api.thecatapi.com/v1/&quot;<br>headers = {&quot;x-api-key&quot;: CAT_API_KEY}<br>response = requests.get(BASE_URL + &quot;breeds&quot;, headers=headers)<br><br># Create dataframe<br>df = pd.DataFrame(response.json())</pre><h3><strong>🐾 </strong>Data Preprocessing for RAG</h3><p>While there were many fields to chose from, I selected the ones I found most interesting and relevant:</p><pre>[&#39;name&#39;, &#39;origin&#39;, &#39;temperament&#39;, &#39;description&#39;, &#39;affection_level&#39;, <br>&#39;shedding_level&#39;, &#39;health_issues&#39;, &#39;life_span_avg&#39;, &#39;image_url&#39;]</pre><p>The data returned from the API was quite clean, but there were numerical fields like affection_level rated 1–5 which I translated into more human readable descriptions (e.g: 5-&gt;very affectionate).</p><p>I mapped shedding_level and health_issues in the same way, and created life_span_avg by parsing and taking the average of life_span_min and life_span_max columns.</p><p>I concatenated the new text columns along with description and temperament to create cat_description, which was used as text inputs to the RAG pipeline.</p><p><strong>A Sample Cat Description for the Abyssinian:</strong></p><blockquote><em>The Abyssinian is easy to care for, and a joy to have in your home. They’re affectionate cats and love both people and other animals. Their temperament is described as Active, Energetic, Independent, Intelligent, Gentle. They are known to be very affectionate, tend to shed and have few health issues. They typically live around 14.5 years.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*Hcxmv0NOA1B0iVd-Uv4bMQ.png" /><figcaption>An Abyssinian Cat</figcaption></figure><h3>Downloading 🐱 Images</h3><p>To enable image-based queries, I downloaded images for each breed and stored each in its own separate folder.</p><p>I downloaded images using the CatAPI’s images/search endpoint:</p><pre>url = &quot;https://api.thecatapi.com/v1/images/search&quot;<br>params = {&quot;breed_id&quot;: breed_id, &quot;limit&quot;: 1}<br><br># One example<br>breed_name = &#39;Abyssinian&#39;<br>breed_folder = f&quot;images/{breed_name}&quot;<br>os.makedirs(breed_folder, exist_ok=True)<br><br># Get image URLs from Cat API<br>response = requests.get(url, headers=headers, params=params)<br>images = response.json()<br><br>for idx, img in enumerate(images):<br>    try:<br>        img_url = img[&quot;url&quot;]<br>        img_ext = img_url.split(&quot;.&quot;)[-1].split(&quot;?&quot;)[0]  # get file extension<br>        out_path = os.path.join(breed_folder, f&quot;{breed_name}.{img_ext}&quot;)<br>        img_response = requests.get(img_url)<br>        if img_response.status_code == 200:<br>            image = Image.open(BytesIO(img_response.content))<br>            image.save(out_path)<br>            print(f&quot;Saved: {out_path}&quot;)<br> <br>    except Exception as e:<br>        print(f&quot;Error saving image for {breed_name}: {e}&quot;)</pre><h3>🧠 Embeddings Generation using CLIP</h3><p>To generate embeddings, I opted to use <a href="https://huggingface.co/docs/transformers/model_doc/clip">CLIP</a> because it is great for multimodal work. For a bit of additional context, CLIP — Contrastive Language-Image Pretraining — is a multimodal model developed by OpenAI in 2021. It was trained on 400M image-text pairs and performs well on tasks like zero-shot classification and semantic similarity.</p><p>CLIP <em>maps both images and text into the same embedding space. </em>This makes it ideal for cross-modal retrieval — so one can query an image to retrieve relevant text, or query a text description to find matching images.</p><p>In my cat project, this capability was exactly what I was looking for: I wanted to <em>align cat images with their textual descriptions</em> to enable flexible semantic search across <em>both</em> modalities. Using text-only embeddings wouldn’t have made this possible.</p><p><strong>Example:</strong></p><p>Using CLIP allowed me to do the following:</p><ul><li>query(&quot;white haired cat&quot;) -&gt; returns an image of a white Persian cat</li><li>query(image_of_my_cat.png) -&gt; returns text like “This looks like a Siamese cat with short hair”</li></ul><h4>📚 <strong>CLIP Text Embeddings</strong></h4><pre>import torch<br>from transformers import CLIPModel, CLIPProcessor<br><br>model_name = &quot;openai/clip-vit-base-patch32&quot;<br>DEVICE = &quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br><br># Load CLIP and its processor<br>clip_model = CLIPModel.from_pretrained(model_name)<br>processor = CLIPProcessor.from_pretrained(model_name)<br><br># Example for one cat description<br>text = data.cat_description.iloc[0]<br><br># Generate textual embeddings<br>with torch.no_grad():<br>    inputs = processor(<br>        text=[text], return_tensors=&quot;pt&quot;, padding=True, truncation=True<br>    ).to(DEVICE)<br>    text_embeddings = clip_model.get_text_features(**inputs)<br>    text_embeddings = text_embeddings / text_embeddings.norm(dim=-1, keepdim=True)</pre><h4>📸 <strong>CLIP Image Embeddings</strong></h4><pre>from PIL import Image<br>from io import BytesIO<br><br># Generate image embeddings for one image:<br>image_path = data.image_path.iloc[0]<br><br>try:<br>    image = Image.open(image_path).convert(&quot;RGB&quot;)<br>    with torch.no_grad():<br>        inputs = processor(images=image, return_tensors=&quot;pt&quot;).to(DEVICE)<br>        image_embeddings = clip_model.get_image_features(**inputs)<br>        image_embeddings = image_embeddings / image_embeddings.norm(dim=-1, keepdim=True)<br>except Exception as e:<br>    print(f&quot;Error processing image {image_path}: {e}&quot;)</pre><h3><strong>📍 Input Formatting Tips for CLIP</strong></h3><p>CLIP expects <strong>specific input formats</strong> when processing data:</p><ul><li>Text inputs must be passed as a list (even if it is just one string). For example: [&quot;This is a Siamese cat&quot;].</li><li>Image should be PIL images. The image needs to be opened using Image.open(image_path).convert(&quot;RGB&quot;) before passing it to the processor.</li></ul><h4><strong>What Do CLIP Embeddings Look Like?</strong></h4><p>CLIP embeddings are just numeric representations of input text or images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*6m4giEdsPTOtTusD75kLSg.png" /></figure><h3>🔍 Query Retrieval using ChromaDB</h3><p><a href="https://docs.trychroma.com/docs/overview/introduction">ChromaDB</a> is a lightweight, developer friendly vector database that stores documents in collections. It has optional metadata that can be used for filtering.</p><p>Each document has:</p><ul><li>A document (string)</li><li>An embedding (vector)</li><li>A unique id</li><li>Optional metadata (breed name, origin …)</li></ul><p>When you run a query, <em>ChromaDB does the following:</em></p><ul><li>Generates an <strong>embedding for the query</strong> (using the specified embedding function)</li><li>Finds the <strong>most similar vectors</strong></li><li><strong>Returns top-N documents</strong> with the optional metadata filtering</li></ul><h3>🔧 System Overview</h3><p>The below diagram shows the overall architecture — how user queries (text or image) are processed:</p><ul><li><strong>Query Encoder (CLIP)</strong> — Converts the inputs (text or image) into an embedding vector.</li><li><strong>ChromaDB Vector Store</strong> — Searches for the most similar entries in the collection (text or image collection), filtered by metadata.</li><li><strong>Retriever</strong> — Finds top N matching documents.</li><li><strong>LLM (Gemini)</strong> — Generates the final answer using the retrieved context.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9laHC4lZFCcVvsdRyUj-g.png" /></figure><h3>🐱 My Cat RAG System</h3><p>In my project, I created two separate collections in ChromaDB:</p><ol><li>A <em>text collection</em> with CLIP generated <em>text embeddings</em> of breed descriptions (cat_description).</li><li>An <em>image collection</em> with CLIP <em>image embeddings</em>.</li></ol><p>This enabled me to support both text-to-image and image-to-text retrieval.</p><h4>️️️‼️ <strong>Lessons Learned While Creating Collections</strong></h4><p>When initializing a ChromaDB collection, you need to pass in an embedding function that <em>exactly</em> matches the one you used to generate your stored embeddings.</p><p>At first, I ran into InvalidDimensionException errors because ChromaDB’s default embedding function outputs 768-dimensional vectors, while CLIP’s embeddings are 512-dimensional. Fixing this mismatch by passing a custom CLIP embedding function resolved the issue.</p><h4><strong>‼️ Key Considerations When Adding Documents</strong></h4><p>When adding documents to a ChromaDB, a few things are important to keep in mind:</p><ul><li>The inputs — documents , embeddings , ids , metadatas must all be the <em>same length</em></li><li>ids must be <em>unique</em> to each collection</li><li>Embeddings must be in the format: List[List[float]] shaped [n_samples][embedding_dim]</li><li>Mismatches of any of the above will result in errors or entries being dropped silently.</li></ul><h4><strong>Why I used Phrases Like </strong><strong>Image: Abyssinian in the Image collection instead of the cat description:</strong></h4><p>For the image collection, I used a simple description like:</p><p>[f&quot;Image: {breed}&quot;] -&gt; [&#39;Image: Abyssinian&#39;]</p><p>This format made the collection semantically searchable with natural language due to the way CLIP was trained. CLIP was trained to associate simple phrases (“a Siamese cat”) with image features — and not long paragraph style descriptions. So using cat_description wouldn’t have worked well and could have reduced the model’s ability to match accurately.</p><h4><strong>🐍 Code Snippets</strong></h4><pre>import chromadb<br>from chromadb.config import Settings<br><br># Create db<br>settings = Settings(persist_directory=&quot;db/&quot;) # This saves the DB between runs<br>chroma_client = chromadb.Client(settings=settings)<br><br># Create collection<br>db = chroma_client.get_or_create_collection(name=db_name, <br>embedding_function=embedding_function) # use CLIP embedding function instead</pre><h4><strong>📃 Adding Documents to Collections</strong></h4><pre># Text collection: store descriptions and embeddings<br>text_collection.add(<br>    documents=[row[&#39;cat_description&#39;] for _, row in data.iterrows()],<br>    ids=[str(idx) for idx in range(len(data))],<br>    embeddings=text_embeddings,<br>    metadatas=metadatas<br>)<br><br># Image collection: store simple descriptions and embeddings<br>image_collection.add(<br>    documents=[f&quot;Image: {row[&#39;breed&#39;]}&quot; for _, row in data.iterrows()],<br>    ids=[str(idx) for idx in range(len(data))],<br>    embeddings=image_embeddings,<br>    metadatas=metadatas<br>)</pre><p>Let’s look at an example — how ChromaDB stores image embeddings for a Ragdoll:</p><pre># Filter for Ragdolls<br>ragdoll = image_collection.get(<br>    where={&quot;breed&quot;: &quot;Ragdoll&quot;},<br>    include=[&quot;embeddings&quot;, &quot;metadatas&quot;, &quot;documents&quot;]<br>)<br><br># Access the first embedding vector<br>ragdoll_embedding = ragdoll[&quot;embeddings&quot;][0]<br><br>print(&quot;Embedding vector length:&quot;, len(ragdoll_embedding)) # should be 512<br>print(&quot;First 10 values:&quot;, ragdoll_embedding[:10])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*elxd2mAIrmKLLPGqCpWKJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*t9QIhhq9I0S58E9DSzObiQ.png" /></figure><h3>✔️ Final Step: LLM + Answer Generation</h3><p>Once the top documents are retrieved from ChromaDB (either using a text or image query), I pass them into a Gemini Pro model for final summarization and response generation.</p><p>This creates a full Retrieval-Augmented Generation (RAG) loop:</p><ol><li><strong>User submits a query</strong> (breed name or an image)</li><li><strong>Relevant documents</strong> are retrieved using CLIP embeddings and ChromaDB</li><li>The top results are <strong>inserted into the prompt</strong> for Gemini</li><li>Gemini generates a <strong>natural language answer</strong> using the grounded context</li></ol><h3>🏹 Putting It ALL Together</h3><p>Here is a simplified code snippet for the final pipeline:</p><pre># Get user query (text or image)<br>query = &quot;fluffy white haired cat&quot;  # or an image path<br><br># Generate query embedding<br>query_embedding = get_clip_embedding(query, mode=&quot;text&quot;)  # or mode=&quot;image&quot;<br><br># Query ChromaDB<br>results = collection.query(<br>    query_embeddings=[query_embedding],<br>    n_results=3,<br>)<br><br># Step 4: Build context string from top documents<br>context = &quot;\n\n&quot;.join(results[&quot;documents&quot;])<br><br># Build Prompt for Gemini and ask a question using the context<br>prompt = f&quot;&quot;&quot;You&#39;re a helpful cat breed assistant. <br>            Use the following info to answer:<br>{context}<br><br>Q: What cat breed matches this description?&quot;&quot;&quot;<br><br>answer = gemini.generate_content(prompt)</pre><h4>Prompt Example with Retrieved Context</h4><p>One of my first queries was “Which cat is the most affectionate?”</p><p>The following prompt was inserted into Gemini — I used gemini-2.0-flash but you could use another model:</p><blockquote>You are a helpful and informative expert bot on cat breeds that answers questions using text from the reference passages included below. Be sure to respond in a complete sentence, being comprehensive, including all relevant background information that you have been given …</blockquote><blockquote>Reference passage:</blockquote><blockquote>The Cymric is a placid, sweet cat. They do not get too upset about anything that happens in their world. They are loving companions and adore people…The Munchkin is an outgoing cat who enjoys being handled. She has lots of energy and is faster and more agile than she looks…</blockquote><blockquote>Question: Which cat is the most affectionate?</blockquote><h4>Sample results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*nOckewSq-_5wZx6hkKzMNA.png" /></figure><figure><img alt="Of the breeds listed, the Ragamuffin or Persian might be a good fit for you, as they are both long haired cats. However, of the two, only the Ragamuffin has no specific health issues mentioned." src="https://cdn-images-1.medium.com/max/508/1*NcxJ7QdwbSu3-KKFtinANA.png" /></figure><h3><strong>LLM Final Results</strong></h3><h4><strong>Most Affectionate Cat</strong></h4><blockquote>Both the Cymric and Munchkin cat breeds are known to be very affectionate, so it’s difficult to say which one is the most affectionate! The Cymric is a placid, sweet cat that is a loving companion and adores people. The Munchkin is an outgoing cat who enjoys being handled.</blockquote><h4><strong>Long-haired White Cat</strong></h4><blockquote>Of the breeds listed, the Ragamuffin or Persian might be a good fit for you, as they are both long haired cats. However, of the two, only the Ragamuffin has no specific health issues mentioned.</blockquote><h3>😻 What I Learned (Besides 100 Cat Breeds)</h3><p>Building this project has taught me a lot more than feline fun facts! I had many gotcha moments, and here are some of the interesting lessons I learned along the way:</p><ul><li><strong>Modularity <em>really </em>helps </strong>— Separating out the RAG flow, CLIP logic, and image handling made the whole system easier to debug, improve, and scale. For example, I had an easier time debugging embeddings not being added to ChromaDB.</li><li><strong>LLMs + structured data is <em>so much</em> better</strong> — Gemini + ChromaDB gave me grounded, non-hallucinated answers that felt surprisingly more human. Tweaking the prompt matters too, but the context passed to the LLM makes a huge difference!</li><li><strong>Multimodal workflows are the future</strong> — Combining visual and textual understanding unlocks a whole new level of interaction.</li></ul><p>And by the way, I did accidentally embed my own cats’ images about 50 times while testing. Leo and Bellini are both very flattered.</p><h3>✅ Final Thoughts</h3><p>This project was not only a fun blend of cats and code, but also a great hands-on exercise in GenAI engineering — from data ingestion and multimodal embeddings to semantic search and natural language responses.</p><p>What’s next? Maybe I’ll try this with dog breeds… or build an app where users can upload their pet’s photo to get a breed match and facts, RAG-style. Stay tuned! 🐶😸</p><p>📚 <a href="https://github.com/Gabya06/cat_breeds/tree/main"><strong>GitHub Repo</strong></a>: Check out the code and get your own cat breed classification system started today!</p><p>📑 Full <a href="https://github.com/Gabya06/cat_breeds/blob/main/notebooks/cat_breeds_capstone_final.ipynb">Jupyter Notebook</a>: Check out the full Jupyter Notebook.</p><p>🐱 <strong>Questions?</strong> Drop a comment below or reach out if you’re interested in collaborating or learning more about my project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=443ebe99b91b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[T5-Base, T5-Large, and BART — The Battle of the Summarization Models]]></title>
            <link>https://medium.com/@gabya06/t5-vs-bart-the-battle-of-the-summarization-models-c1e6d37e56ca?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e6d37e56ca</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[intro]]></category>
            <category><![CDATA[transformer-model]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 17:00:08 GMT</pubDate>
            <atom:updated>2025-03-04T17:00:08.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>T5-Base, T5-Large, and BART — The Battle of the Summarization Models</h3><p>In my last <a href="https://medium.com/@gabya06/hugging-face-roberta-model-for-sentiment-analysis-4f52e9ccb490">post</a>, I explored using Hugging Face’s RoBERTa model for sentiment analysis on Reddit posts and comments that I pulled via the Reddit API (PRAW).</p><p>As a next step in this series of posts, I’ll walk through <strong>how to summarize </strong>those posts using two different transformer models: <strong>T5</strong> and <strong>BART</strong>. My goal was to experiment with how different model sizes and architectures impact summarization. I wanted to compare efficiency, fluency, and overall quality across models.</p><p>I started with <a href="https://huggingface.co/google-t5/t5-base">T5-base</a> for a lightweight baseline, then scaled up to <a href="https://huggingface.co/google-t5/t5-large">T5-large</a> to see if a bigger model really means better results. Once I had a winner, I put it head-to-head with <a href="https://huggingface.co/facebook/bart-large-cnn">BART</a>, which is known for its strong summarization ability.</p><p>This post will cover:</p><ul><li>How to use <em>Hugging Face’s pipeline for summarization</em></li><li>A step-by-step breakdown of <em>text summarization</em></li><li>A comparison of <a href="https://huggingface.co/google-t5/t5-base">T5-base</a>, <a href="https://huggingface.co/google-t5/t5-large">T5-large</a>, and <a href="https://huggingface.co/facebook/bart-large-cnn">BART-large-CNN</a><strong> </strong>outputs</li><li>More <em>parameter control</em> — Loading transformer models manually</li><li>Exploring num_beams parameter</li><li>How to leverage <strong>Google Colab</strong> for efficient model execution</li></ul><p>By the end, you will have a clear understanding of how to implement text summarization using Hugging Face’s pipelines, and see how it can be used to extract key insights from large volumes of Reddit discussions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*1GVBQRCABXvu3-I9.png" /></figure><h3><strong>📊 Data Overview — Brief Refresher</strong></h3><p>We previously extracted comments from the <strong>NYCApartment</strong> subreddit and performed sentiment analysis using RoBERTa. In case you missed my post on how to scrape Reddit data, you can find it <a href="https://medium.com/@gabya06/automating-reddit-summaries-pulling-data-with-python-91afeb6acdb3">here</a>.</p><p>Here is a quick recap of what our Reddit post data looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tErw1pqIxZMPt8Vt7vKwBA.png" /></figure><p>To help analyze and understand how sentiment plays a role in engagement levels, we will add upvotes and comments and use it as a proxy measure for engagement. We could get fancier and weigh these, but for the purposes of this post adding them will do.</p><pre><br># Assign engagement score: score + num_comments<br>data = data.assign(engagement=data.score + data.num_comments)<br><br># Define color palette for sentiment<br>palette = sns.color_palette([&quot;green&quot;, &quot;red&quot;, &quot;grey&quot;])<br><br># Plot histogram of engagement by sentiment<br>fig, ax = plt.subplots(figsize=(8, 6))<br>sns.histplot(data=data, x=&#39;engagement&#39;, hue=&#39;sentiment&#39;, palette=palette, <br>            ax=ax)<br>ax.set_title(&#39;Engagement by Sentiment&#39;, fontsize=16, fontweight=&#39;bold&#39;)<br>ax.set_xlabel(&#39;Engagement&#39;)<br>ax.set_ylabel(&#39;Count&#39;)<br><br># Format x-axis tick labels with commas<br>ax.xaxis.set_major_formatter(<br>          ticker.FuncFormatter(lambda x, pos: &#39;{:,.0f}&#39;.format(x)))<br>plt.show()</pre><p>From the plot, we observe significant overlap in <strong>low-engagement</strong> comments, while <strong>higher engagement</strong> comments tend to have a more <strong>negative sentiment</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lBYAMQk0tPoLc6OnMfPwA.png" /></figure><p>Let’s analyze the <strong>sentiments of the most engaging posts</strong> by focusing on the <strong>top 25%</strong> based on engagement scores. This will help us determine whether <strong>highly engaging posts</strong> tend to be more <strong>positive, negative, or neutral</strong>.</p><pre># Define the engagement threshold (75th percentile)<br>top_25_threshold = data.engagement.quantile(0.75)<br><br># Filter for top 25% most engaging posts<br>top_engagement_posts = data[data.engagement &gt;= top_25_threshold]<br><br># Plot sentiment distribution for high-engagement posts<br>fig, ax = plt.subplots(figsize=(8, 6))<br>sns.histplot(top_engagement_posts, x=&#39;sentiment&#39;, color=&#39;blue&#39;, ax=ax)<br><br># Format plot<br>ax.set_title(&#39;Sentiment Distribution for Top 25% Most Engaging Posts&#39;, <br>              fontsize=12, fontweight=&#39;bold&#39;)<br>ax.set_xlabel(&#39;Sentiment&#39;)<br>ax.set_ylabel(&#39;Count&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgW4dGS0CNDEDlQifAOOxw.png" /></figure><p>This visualization helps us determine that <strong>highly engaging posts</strong> are more <strong>polarizing</strong> (leaning strongly positive or negative) or if <strong>neutral sentiment</strong> dominates. In this case, highly engaging posts are clearly more negative.</p><h3>Using the Hugging Face Pipeline for Summarization</h3><p>Hugging Face’s pipeline simplifies working with pre-trained models for various NLP tasks, including <strong>summarization</strong>. It abstracts the complexities of tokenization and model inference, making it easy to implement.</p><h3>📒 Summarization with T5-Base</h3><p>First, let’s use the <strong>T5-Base model</strong>, a general-purpose text-to-text transformer:</p><p>Let’s use the pipeline function:</p><pre>from transformers import pipeline<br><br># Load summarization pipeline with T5-base<br>summarizer = pipeline(&quot;summarization&quot;, model=&quot;t5-base&quot;, tokenizer=&quot;t5-base&quot;)</pre><p>We can now apply it to a sample Reddit comment:</p><pre>sample_comment = &quot;&quot;&quot;is the building or most of the units in the building rent stabilized? <br>i knew someone that lived in that building 10 years ago. <br>it was a dump with questionable management (although i don&#39;t know if it was the same ownership and management) <br>then and it hasn&#39;t gotten better with age. guessing they&#39;re still coasting on the reputation of the beat generation. <br>i fell in love with someone on that roof pretty common wiring set up in most buildings. and is that flood water outside the building anyways? <br>i’m confused here. the address rules..! … kind of like bragging rights…! those are cable company wires and moldings. <br>they have to fix it not the management. bidding yourself into a $6k “deathtrap” then begging the city the come help is a perfect <br>definition of “play stupid games win stupid prizes” and we all know if they actually fix it up obviously someone with a little more standards <br>is going to pay $8k for it [deleted]&quot;&quot;&quot;<br><br># Generate summary<br>summary = summarizer(sample_comment, min_length=5, max_length=200, <br>                  do_sample=False)<br>print(summary[0][&#39;summary_text&#39;])</pre><h4>T5-BASE Summary Output:</h4><pre>&quot;the address rules are kind of like bragging rights...! those are cable <br>company wires and moldings. they have to fix it not the management . <br>bidding yourself into a $6k &#39;deathtrap&#39; then begging the city <br>to come help is a perfect definition of &#39;play stupid games win stupid prizes&#39;&quot;</pre><p>This summary preserves key elements but trims <em>unnecessary details</em>.</p><p>Notice, we set do_sample=False which makes the summarization <em>deterministic. </em>This means it will always return the <em>same summary</em> for the same input<em>. </em>If we set this to True then the model will return <em>different summaries</em> each time<em>.</em></p><p>Since we are comparing different model outputs, using do_sample=False ensures that the same input always produces the same output. This eliminates randomness, making it easier to evaluate differences between models.</p><h3>🥊 Comparing T5-Base vs. T5-Large</h3><p>We can now compare the results with <strong>T5-Large</strong>, a more powerful variant of <strong>T5-Base</strong>.</p><pre># Load T5-Large model<br>summarizer = pipeline(&quot;summarization&quot;, model=&quot;t5-large&quot;, tokenizer=&quot;t5-large&quot;)<br><br># Generate summary<br>summary = summarizer(text, min_length=5, max_length=200, do_sample=False)<br>print(summary[0][&#39;summary_text&#39;])</pre><h4>T5-LARGE Summary Output:</h4><pre>&quot;is the building or most of the units in the building rent stabilized? <br>i knew someone that lived in that building 10 years ago. <br>it was a dump with questionable management . i fell in love with <br>someone on that roof pretty common wiring set up in most buildings.&quot;</pre><p>Compared to T5-Base, T5-Large retains more details and appears less negative in tone<em>. </em>The output from T5-Large is also <em>more coherent</em> and natural.</p><h3>💻 Summarizing with BART-Large-CNN</h3><p>Finally, we run summarization using <a href="https://huggingface.co/docs/transformers/model_doc/bart"><strong>BART-Large-CNN</strong></a>, a model designed specialized for general text summarization.</p><p>As its name suggests:</p><blockquote>BART model pre-trained on English language, and fine-tuned on <a href="https://huggingface.co/datasets/cnn_dailymail">CNN Daily Mail</a></blockquote><p>Unlike T5, which requires prefixing tasks like &quot;summarize:&quot;, BART is pre-trained and fine-tuned for summarization, making it a great choice for extracting concise summaries directly.</p><pre>from transformers import BartTokenizer<br><br># Load summarization pipeline<br>summarizer = pipeline(&quot;summarization&quot;, model=&quot;facebook/bart-large-cnn&quot;)<br><br># Load the tokenizer separately to enable manual truncation<br>tokenizer = BartTokenizer.from_pretrained(&quot;facebook/bart-large-cnn&quot;)<br>summary = summarizer(sample_comment, min_length=30, max_length=100, do_sample=False)<br>print(summary[0][&#39;summary_text&#39;])</pre><h4>BART Summary Output:</h4><pre>&quot;Is the building or most of the units in the building rent stabilized? <br>i knew someone that lived in that building 10 years ago. it was a dump <br>with questionable management (although i don&#39;t know if it was the same <br>ownership and management) then and it hasn&#39;t gotten better with age. <br>guessing they&#39;re still coasting on the reputation of the beat generation. <br>i fell in love with someone on that roof pretty common wiring set up in most <br>buildings.&quot;</pre><p>The summary feels more readable, human-like and less choppy than the T5 summaries. It also has the same tone as the original text.</p><h3>🥊 Initial Thoughts: Summarization Comparison</h3><p>After running multiple posts and comments through T5-BASE, T5-LARGE, and BART-LARGE-CNN the differences crystal clear and there is a clear winner:</p><ul><li><strong>T5-BASE</strong>: Reading these summaries felt like I was listening to someone who keeps jumping between half-finished thoughts — disjointed, off-topic, and missing the point entirely… <em>Sorry T5-BASE, nothing personal.</em></li><li><strong>T5-LARGE:</strong> Scaling up to T5-LARGE helped with fluency, but it still dropped what I considered to be key details.</li><li><strong>BART:</strong> Actually got it! It understood the core discussion, kept things concise, and didn’t lose clarity. This is the clear winner!</li></ul><p>This makes sense — T5 is trained for text-to-text tasks, but BART’s denoising pre-training gives it a stronger grasp of context and coherence. Turns out, scaling T5 helps, but <em>pre-training strategy matters even more</em>.</p><h3>✍🏻 Manually Loading Summarization Models</h3><p>Instead of using the pipeline, we can manually load the T5 model and tokenizer to have <em>more control over the summarization process.</em></p><pre>from transformers import T5Tokenizer, T5ForConditionalGeneration<br><br># Load model and tokenizer (T5-base example)<br>model_name = &quot;t5-base&quot;<br>tokenizer = T5Tokenizer.from_pretrained(model_name)<br>model = T5ForConditionalGeneration.from_pretrained(model_name)</pre><p>Before summarization, we prepend the text with &quot;summarize: &quot;, as required by T5 models:</p><pre># Add &quot;summarize:&quot; prefix for T5 models<br>input_text = &quot;summarize: &quot; + text<br><br># Tokenize the input text<br>input_ids = tokenizer.encode(input_text, return_tensors=&quot;pt&quot;, <br>            max_length=512, truncation=True)</pre><p>We can inspect the tokenized text input_ids:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOINAAAd9cXKw83NOBusFA.png" /></figure><p>And, we can decode input_ids back to the original text:</p><pre># Decode tokenized text<br>tokenizer.decode(input_ids[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDTehRhFc_ohnIQ16oSyZw.png" /></figure><p>Now, let’s generate a summary:</p><pre># Generate summary<br>summary_ids = model.generate(input_ids, max_length=100, min_length=30, <br>            length_penalty=2.0, num_beams=4)<br><br># Decode the output<br>summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)<br><br>print(summary)</pre><p><strong>Parameters in</strong> .generate():</p><ul><li>max_length=100: Limits the summary length.</li><li>min_length=30: The minimum summary size.</li><li>length_penalty=2.0: Penalizes longer outputs (higher values encourage brevity).</li><li>num_beams=4: Uses beam search to improve quality (explained in next section).</li><li>skip_special_tokens=True: This cleans up generated text, removing unnecessary tokens for human-readable output.</li></ul><h3>💬 The Impact of the num_beams Parameter on <strong>Text Generation</strong></h3><p>When experimenting with different parameters, I wanted to better understand how num_beams influences the <em>quality</em> of generated text. This parameter is used in <em>beam search decoding</em>, a method that improves text generation in transformer models.</p><p>How num_beams Works:</p><ul><li>Setting num_beams=1 is equivalent to <strong>greedy search</strong>, meaning the model selects the most probable word at each step. While this is <strong>faster</strong>, it may lead to <strong>suboptimal results</strong> since it doesn’t explore alternative sequences and can miss sequences.</li><li>Setting num_beams &gt; 1 enables <strong>beam search</strong>, where multiple possible sequences are considered before selecting the best one. This approach is <strong>slower</strong> and more computationally expensive, but it generally yields <strong>more coherent and meaningful</strong> results.</li></ul><p>Below, I compare the effect of different num_beams values using T5-Base:</p><pre><br># Load model and tokenizer (T5-base example)<br>model_name = &quot;t5-base&quot;<br>tokenizer = T5Tokenizer.from_pretrained(model_name)<br>model = T5ForConditionalGeneration.from_pretrained(model_name)<br><br># Add &quot;summarize:&quot; prefix for T5 models<br>input_text = &quot;summarize: &quot; + sample_comment<br># Tokenize the input text<br>input_ids = tokenizer.encode(input_text, return_tensors=&quot;pt&quot;, max_length=512, <br>                             truncation=True)<br><br>summary_ids = model.generate(input_ids, max_length=100, min_length=30,<br>            length_penalty=2.0, num_beams=4)<br><br># Generate summaries with different beam sizes<br><br># Greedy search<br>output_1 = model.generate(input_ids, num_beams=1, <br>                          max_length=100, min_length=30)  <br># Beam search with 4 beams<br>output_4 = model.generate(input_ids, num_beams=4, <br>                          max_length=100, min_length=30)  <br># Beam search with 8 beams<br>output_8 = model.generate(input_ids, num_beams=8, max_length=50)  <br><br># Decode and print outputs<br>print(&quot;Greedy Search:&quot;, tokenizer.decode(output_1[0], <br>                                         skip_special_tokens=True))<br>print(&quot;Beam Search (4 beams):&quot;, tokenizer.decode(output_4[0], <br>                                                 skip_special_tokens=True))<br>print(&quot;Beam Search (8 beams):&quot;, tokenizer.decode(output_8[0], <br>                                                 skip_special_tokens=True))</pre><h4>Beam Search Output:</h4><pre># Output_1 - Greedy Search:<br>&quot;john sutter: i&#39;m confused here. the address rules..! <br>those are cable company wires and moldings. they have to fix it <br>not the management . sutter: i&#39;m sure if the city fixes it up someone <br>with a little more standards is going to pay $8k for it .&quot;<br><br># Output_4 - Beam Search (4 beams):<br>&quot;the address rules are kind of like bragging rights...! those are cable <br>company wires and moldings. they have to fix it not the management . <br>bidding yourself into a $6k &#39;deathtrap&#39; then begging the city to come help <br>is a perfect definition of &#39;play stupid games win stupid prizes&#39;&quot;<br><br># Output_8 - Beam Search (8 beams):<br>&quot;the address rules are kind of like bragging rights...! those are cable <br>company wires and moldings. they have to fix it not the management . <br>bidding yourself into a $6k &#39;deathtrap&#39; then begging&quot;</pre><ul><li><strong>Greedy Search </strong>(num_beams=1): The output is <em>concise but not well structured</em>. It picks the most probable next word at each step but lacks coherence.</li><li><strong>Beam Search</strong> (num_beams=4): The summary is <em>more structured and coherent.</em> The model considers multiple possibilities which leads to a more natural and <em>contextually relevant</em> output.</li><li><strong>Beam Search </strong>(num_beams=8): The output is <em>more refined</em> than 4 beams, but it sometimes over-trims details. While it improves coherence, it can become too restrictive depending on the maximum length setting. In practical applications, num_beams=4 is often a balanced choice between quality and efficiency.</li></ul><p>Increasing num_beams generally improves output quality by considering more possible sequences, but higher values require <em>more computation</em>. A balance between <em>speed and quality</em> is key, and num_beams=4 often provides a good tradeoff.</p><h3>🥊 Final Comparison: T5, Beam Search and BART</h3><p>Compared to the T5 model with beam search, BART’s summary is more natural and conversational. At first glance, we notice that it is a lot more human-like and does not look like structured extraction. Here are some of my observations:</p><ul><li><strong>Readability:</strong> The summary feels more fluid as it maintains the original style, whereas T5 sometimes produces more a structured summary that doesn’t seem as human-like or natural.</li><li><strong>Less rigid:</strong> BART doesn’t necessarily pick the most important or factual sentences but it maintains the tone and key themes.</li><li><strong>Shorter but more impactful:</strong> Compared to beam search (num_beams=4 or num_beams=8), BART’s output is less repetitive, delivering a concise yet<strong> </strong>rich summary.</li></ul><h3>⏳Running LLMs Efficiently: Why Use Google Colab?</h3><p>As the final part of this post, I would like to briefly discuss why using <a href="https://colab.research.google.com/">Google Colab </a>facilitates this task.</p><p>Large Language Models (LLMs) like <strong>T5</strong> and <strong>BART</strong> require significant computational power, especially for tasks like summarization and fine-tuning. Running these models locally on a MacBook (like my small personal computer) can be very computationally expensive and slow due to the lack of a powerful GPU. It can feel like an eternity to finish running a summarization task on a larger dataset… This is where Google Colab comes in!</p><p>Google Colab provides free access to GPUs and TPUs, making it a great alternative for running deep learning models efficiently.</p><p>For large-scale summarization tasks, Colab Pro offers access to more powerful GPUs, reducing execution time significantly compared to a CPU-only setup. Not only is this faster, but you also don’t need to use up your computer’s resources!</p><p>To run this code in <strong>Google Colab</strong>, upload your dataset and select:</p><p><strong>Runtime→ Change runtime type → GPU</strong> before executing the cells.</p><h3>Final Thoughts</h3><p>This post demonstrated <em>how to summarize Reddit comments using Hugging Face’s pipeline</em> and how to manually load models for finer control. We explored <strong>T5-base, T5-large, and BART-large-CNN</strong>, comparing their output quality.</p><p>While we focused on a sample comment for demonstration purposes, you can find the full code to apply these models to the entire dataset in my <a href="https://github.com/Gabya06/RentWatchAI/blob/main/post_summarization.ipynb">Github</a> Repo.</p><p>For future work, we can:</p><ul><li>Scale summarization to larger datasets to identify trends across thousands of Reddit comments.</li><li>Fine-tune T5 or BART on domain-specific text (e.g., real estate discussions) to improve summary relevance.</li></ul><p>Try it out and let me know if you have any questions!</p><h3>Useful Resources</h3><p><a href="https://towardsdatascience.com/foundations-of-nlp-explained-visually-beam-search-how-it-works-1586b9849a24/">https://towardsdatascience.com/foundations-of-nlp-explained-visually-beam-search-how-it-works-1586b9849a24/</a></p><p><a href="https://huggingface.co/models?pipeline_tag=summarization&amp;p=1&amp;sort=trending&amp;search=t5">https://huggingface.co/models?pipeline_tag=summarization&amp;p=1&amp;sort=trending&amp;search=t5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e6d37e56ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LLMs to Understand Reddit Sentiment with Hugging Face’s RoBERTa]]></title>
            <link>https://medium.com/@gabya06/hugging-face-roberta-model-for-sentiment-analysis-4f52e9ccb490?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f52e9ccb490</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 16:16:06 GMT</pubDate>
            <atom:updated>2025-02-07T16:16:06.030Z</atom:updated>
            <content:encoded><![CDATA[<h2>Hugging Face’s RoBERTa Model for Reddit Posts Sentiment Analysis</h2><p>In my <a href="https://medium.com/@gabya06/automating-reddit-summaries-pulling-data-with-python-91afeb6acdb3">previous</a> post, I explored how to use PRAW to pull Reddit posts and comments. Now, let’s take it a step further by performing sentiment analysis with RoBERTa! Yes, you heard it right — her name is RoBERTa. Developed by the Meta AI Research team, RoBERTa is a model trained on about 124 million tweets from January 2018 to December 2021, specializing in natural language processing.</p><p>You can find <a href="https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment-latest">RoBERTa</a> on Hugging Face, a fantastic platform that hosts models for various NLP tasks, from sentiment analysis to text summarization and question answering.</p><blockquote>The Hugging Face Hub is a platform with over 900k models, 200k datasets, and 300k demo apps (Spaces), all open source and publicly available, in an online platform where people can easily collaborate and build ML together. The Hub works as a central place where anyone can explore, experiment, collaborate, and build technology with Machine Learning.</blockquote><p>In this post, we’ll use RoBERTa for sentiment analysis on Reddit comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jev8r3DWG5Sakb6G.png" /></figure><h3>Step 1: Install the Required Libraries</h3><p>First, let’s install the transformers library to access RoBERTa:</p><pre>pip install transformers</pre><p>With that installed, we’re ready to load the model and its tokenizer:</p><pre>from transformers import pipeline<br>from transformers import AutoTokenizer, AutoConfig<br><br># Load model and tokenizer<br>model = AutoModelForSequenceClassification.from_pretrained(&quot;cardiffnlp/twitter-roberta-base-sentiment&quot;)  <br>tokenizer = AutoTokenizer.from_pretrained(&quot;cardiffnlp/twitter-roberta-base-sentiment&quot;)</pre><p>Note that all transformer models need a tokenizer to prepare the inputs for the model.</p><h3>Step 2: Prepare Sample Comments</h3><p>Let’s try out the model with a few sample comments. The dataset consists of 200 sample rows with over 8,000 comments, so we have plenty to chose from.</p><p>Below is a small sample from one of our posts:</p><pre>sample_comment = &quot;&quot;&quot;<br>I didn&#39;t live in one but I worked at an office in Hudson Yards on the 72nd floor and the view never got old.<br>I got used to it. I never got tired of it.<br>I got used to mine, but continued to vicariously live through other people when they saw it the first time.<br>Impressed my girlfriend at the time enough to become my wife so all in all worth it.<br>But after 6.5 years of a 6-floor walk-up, I&#39;m happy to be a ground-floor dweller now.<br>It never gets old for me. Besides the view, I&#39;ve noticed my apartment is very quiet.<br>There are no bugs or rodents that make it up this high, either. Totally worth it for me.<br>&quot;&quot;&quot;</pre><p>If I had to guess, I’d classify this comment as positive — I see ‘positive’, ‘never gets old’, ‘no bugs’, ‘worth it’. But let’s see if the model agrees as we use machine learning to classify it as positive, negative, or neutral.</p><h3>Step 3: Tokenize the Text</h3><p>To prepare the comment for RoBERTa, we need to convert it into a format the model understands. This means using the tokenizer to transform the text into <em>numerical representations</em>:</p><pre># Tokenize the sample_comment, ensuring truncation <br>encoded_comment = tokenizer(<br>    sample_comment,<br>    return_tensors=&#39;pt&#39;,<br>    truncation=True,<br>    max_length=512<br>)</pre><p>Here, I set max_length to 512 because this model can process up to 512 tokens at a time. This limit ensures that our input fits within the model&#39;s capabilities. If we exceed this length, the tokenizer truncates the text, which means some information could be lost. By carefully managing the length, we can maintain the integrity of the most important content in our comments while ensuring that our input is compatible with RoBERTa.</p><p>What does this encoded_comment consist of? We notice keys input_ids and attention_mask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtYIX-89zSSF0hDO_6hlvw.png" /></figure><p>The input_ids represent the numerical values of the words in the text, and these are stored as a <em>tensor</em>. Because we can not utilize RoBERTa with words, we must first encode our words. The attention_mask is a tensor with 1&#39;s or 0&#39;s indicating which tokens should be attended to during processing. Usually, we pad sequences so that they have the same length by setting padding=True; and in the attention_mask we can see the position of the padded indices. 1 indicates that a value should be attended, while 0 indicates a padded value.</p><h3>Step 4: Decode Sample Output</h3><p>You can decode part of the input_ids back to text to verify it, which is useful for understanding how the tokenizer breaks down our input.</p><p>Let’s see an example:</p><pre># Get the original text back from IDs<br>tokenizer.decode(encoded_comment[&#39;input_ids&#39;][0][0:30])</pre><p>From the output we can see that we are able to retrieve the first 30 characters from the encoded numerical values:</p><pre>I didn’t live in one but I worked at an office in Hudson Yards on the 72nd floor and the view never got old.</pre><h3>Step 5: Make Predictions</h3><p>Next, on to the fun part! Let’s make some predictions! We pass the encoded input to the model to predict the sentiment:</p><pre># Sentiment analysis - is this positive, negative or neutral?<br>output = model(**encoded_input)<br>print(output)<br><br># Output<br>SequenceClassifierOutput(loss=None, logits=tensor([[-1.9768,  0.1379,  2.0923]], grad_fn=&lt;AddmmBackward0&gt;), hidden_states=None, attentions=None)</pre><h3>Step 6: Interpret the Logits</h3><p>Let’s break down the model output into three parts: model output, logits, and interpretation.</p><ul><li><strong>Model output</strong>: The model generates a SequenceClassifierOutput object, which includes the logits. Logits are raw scores representing each sentiment class before applying an activation function like softmax.</li><li><strong>Logits</strong>: Higher logit values indicate a stronger association with a particular sentiment class. In our example, the logits look like [-1.9768, 0.1379, 2.0923], suggesting that the model is most inclined toward the third class (positive), but these scores haven’t yet been converted into probabilities.</li><li><strong>Interpretation</strong>: To turn the logits into understandable probabilities, we apply the softmax function, which helps us see the likelihood of each sentiment class.</li></ul><p>Here is how we convert logits to probabilities with the softmax function:</p><pre>import torch.nn.functional as F<br><br># Get probabilities using softmax<br>probs = F.softmax(output.logits, dim=1)</pre><p>These probabilities show us the likelihood of the text being negative, neutral, or positive. In our case, let’s say the output is something like:</p><pre><br># output<br>tensor([[0.0148, 0.1222, 0.8630]])</pre><p>There’s a 1.48% probability the text sentiment is negative, a 12.2% probability it’s neutral, and 86.3% probability the sentiment is positive.</p><h3>Step 7: Map Predicted Label</h3><p>Finally, we need to map the highest probability to the corresponding sentiment label. To confirm which label index corresponds to which sentiment, we can check the model’s configuration:</p><pre># Get model configuration for label mapping<br>config = AutoConfig.from_pretrained(&quot;cardiffnlp/twitter-roberta-base-sentiment&quot;)<br>print(config.id2label)<br><br><br># output<br>{0: &#39;negative&#39;, 1: &#39;neutral&#39;, 2: &#39;positive&#39;}</pre><p>With this mapping, we know that index 2 corresponds to a positive sentiment. Let’s print our final prediction:</p><pre># Print the final sentiment prediction<br>predicted_label_index = torch.argmax(probs).item()<br>print(f&quot;Predicted sentiment is: {config.id2label[predicted_label_index]}&quot;)<br><br># Predicted sentiment is: positive</pre><p>For our sample, the prediction is <em>positive</em>! The model agrees with our initial classification. Although we’ve only classified one comment here, it’s always a good practice to verify model predictions against initial observations to see if they align with our intuition. While it’s not feasible to do this for all data, spot-checking a few predictions helps ensure the model’s results make sense.</p><p>This approach provides a powerful way to quickly gauge sentiment across numerous Reddit comments, opening up new ways for analyzing discussions on your favorite subreddits.</p><h3>Visualizing Sentiment Distribution</h3><p>To get a clearer view of our sentiment analysis results, let’s plot a chart showing the distribution of positive, neutral, and negative comments. This will help us quickly understand which sentiment is most prevalent in our data.</p><pre># Sentiment counts<br>sentiment_df = data.sentiment.value_counts().reset_index()<br><br># Plotting the bar chart<br>plt.figure(figsize=(8, 6))<br>plt.bar(sentiment_df[&#39;sentiment&#39;], sentiment_df[&#39;count&#39;], color=[&#39;#66BB6A&#39;, &#39;#FFCA28&#39;, &#39;#EF5350&#39;])<br>plt.xlabel(&#39;Sentiment&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Sentiment Distribution of Reddit Comments&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwN_I5_zBPrep8XvDwnrvQ.png" /></figure><h3>Discussion</h3><p>In this sample of Reddit comments about NYC apartments, the model detected a higher proportion of <strong>negative sentiments</strong> compared to positive or neutral sentiments. This trend is understandable given that apartment hunting in New York City often evokes frustration — from the high prices to quality concerns and the competitive nature of the rental market.</p><p>This insight could significantly impact real estate strategies, highlighting common frustrations such as high rents or quality concerns. Real estate professionals might use this data to refine their marketing approaches, focusing on the aspects that renters value most, such as safety, amenities, and overall living experience. Moreover, landlords could address prevalent complaints by improving property features or enhancing communication with tenants, ultimately leading to better tenant satisfaction and retention. Understanding the sentiment landscape not only provides a snapshot of user experience but can also guide decision-making for both buyers and sellers in a competitive market.</p><p>Adding this kind of analysis can offer valuable insights to anyone involved in NYC real estate — whether they’re looking to identify common complaints or discover what makes certain apartments stand out.</p><h3><strong>Wrapping It Up</strong></h3><p>With RoBERTa, we’ve turned Reddit comments into valuable sentiment insights, bringing a new level of understanding to online conversations. By following these steps, you’ve unlocked the ability to understand community sentiment — whether it’s excitement, frustration, or something in between! Ready to level up? Try running this model across different posts, experimenting with other sentiment models on Hugging Face, or adding metrics like engagement to see how sentiment evolves over time. The possibilities for diving deeper into the online pulse are endless — so keep exploring and uncover what insights await!</p><h3>Useful Resources:</h3><ul><li><a href="https://huggingface.co/docs/hub/index">Hugging Face Hub documentation · Hugging Face</a></li><li><a href="https://medium.com/@hunter-j-phillips/a-simple-introduction-to-softmax-287712d69bac">A Simple Introduction to Softmax</a></li><li><a href="https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment-latest">cardiffnlp/twitter-roberta-base-sentiment-latest · Hugging Face</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f52e9ccb490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reddit API: Analyzing NYC Apartment Engagement with Python]]></title>
            <link>https://medium.com/@gabya06/automating-reddit-summaries-pulling-data-with-python-91afeb6acdb3?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/91afeb6acdb3</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[reddit]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 13:52:26 GMT</pubDate>
            <atom:updated>2024-10-29T13:52:26.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*dsF8lHUH9YSrA3I2.png" /></figure><p><strong>Tired of scrolling through endless apartment listings on Reddit?</strong> What if you could instantly pull the most engaging conversations with just a few lines of code? Recently, I found myself browsing through Reddit’s New York City Apartments subreddit, eager to catch up on the latest discussions but too overwhelmed by the sheer number of posts and comments.</p><p><em>This sparked an idea: </em><strong><em>why not pull and analyze the data myself?</em></strong></p><p>In this post, we will do just that! I’ll walk you through how to use Python and PRAW to scrape Reddit’s API, filter top posts, and uncover trends in NYC’s housing community — all while avoiding the clutter of manual browsing.</p><h3>But …. What is an API?</h3><p>An API, or Application Programming Interface, is a server that you can use to retrieve and send data to using code. APIs provide essential tools in the world of artificial intelligence (AI) and data science, enabling access to vast amounts of data and powerful computing capabilities. For us, this is simply a way to pull data from Reddit!</p><h3>Setting up Reddit API Access</h3><p>Getting access to Reddit’s API is simpler than you might think. Here’s how to create your own Reddit app to get started:</p><ul><li>Go to the <a href="https://www.reddit.com/prefs/apps">Reddit Apps</a></li><li>Select <strong>script</strong> as the type of app.</li><li>Name your app (I used “Gaby’s app” for this blog post, but feel free to use something relevant to your project).</li><li>Set the redirect URI to be http://localhost:8000</li><li>Save your client_id and client_secret in a credentials file — this is important for the next step.</li></ul><p>After completing this, you’re ready to connect to Reddit’s API using Python and PRAW!</p><p>Here is an example of what creating a Reddit App looks like, along with the client_id and client_secret that are created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmKfcluIWRAhHu6lC8TPiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*PDbHZs5r0JiFyLZORGqbYg.png" /></figure><h3>Connecting to Reddit with PRAW</h3><p><a href="https://praw.readthedocs.io/en/stable/index.html">PRAW</a> is a Python Reddit API Wrapper which makes interacting with the Reddit API quite simple.</p><p>First, let’s install it:</p><pre>pip install praw</pre><p>To establish a connection, use the credentials from your Reddit app:</p><pre># Connect to Reddit API using PRAW<br>reddit = praw.Reddit(<br>    client_id=client_id,<br>    client_secret=client_secret,<br>    password=client_password,<br>    user_agent=user_agent,<br>    username=user_name,<br>)</pre><p>This code authenticates your Reddit account using your client_id, client_secret, and other credentials. Once connected, you can start pulling data from subreddits.</p><p>Next, we’ll create an <a href="https://praw.readthedocs.io/en/stable/code_overview/reddit_instance.html">instance</a> for the NYC Apartments subreddit:</p><pre># Create an instance of NYCapartments subreddit<br>sub_reddit = reddit.subreddit(&quot;NYCapartments&quot;)</pre><p>This tells PRAW to focus on the NYC Apartments subreddit, where all our data will come from.</p><h3>Filtering Top Posts from Last Week</h3><p>Now that we’re connected, let’s fetch the top 5 posts from the past week using the time_filter parameter. You can customize the time range with options like &#39;day&#39;, &#39;week&#39;, &#39;month&#39;, or &#39;year&#39; (with ‘all’ as the default).</p><pre># Get the top 5 posts from the past week<br>weekly_posts = sub_reddit.top(time_filter=&#39;week&#39;, limit=5)<br><br># Print post titles, scores and comments<br>for post in weekly_posts:<br>    print(f&#39;Post title: {post.title}&#39;)<br>    print(f&#39;Post upvotes: {post.score}&#39;)<br>    print(f&#39;Post comments: {post.comments}&#39;)<br>    print()</pre><p>This code grabs the top 5 posts, displaying the title, upvote count, and number of comments for each. You’ll notice the comments are returned as a comment_forest object, which requires further processing to extract individual comments.</p><p>Here is an example of the output:</p><pre>Post title: Looking for roommates to fill $1667 rooms in Park Slope<br>Post upvotes: 279<br>Post comments: &lt;praw.models.comment_forest.CommentForest object at 0x28d081790&gt;<br><br>Post title: Age discrimination in NYC rentals?<br>Post upvotes: 113<br>Post comments: &lt;praw.models.comment_forest.CommentForest object at 0x28d1f4d90&gt;<br><br>Post title: Lease takeover through March 2025 | Williamsburg | 2BD 2BA | $6,600/month<br>Post upvotes: 101<br>Post comments: &lt;praw.models.comment_forest.CommentForest object at 0x28d2170d0&gt;<br><br>Post title: LES Lease Takeover 1br/1ba<br>Post upvotes: 83<br>Post comments: &lt;praw.models.comment_forest.CommentForest object at 0x28d1fcc90&gt;</pre><p>From this output we can see that we’ve captured a snapshot of the top posts, including the number of upvotes and comments. From here, we can move on to extracting and analyzing the individual comments to gain deeper insights into the discussions taking place!</p><h3>🗒Extracting and Analyzing Post Data</h3><p>To work with this data in a more structured way, I wrote a function that scrapes post details (title, upvotes, comments, etc.) and returns it all in a neat DataFrame:</p><pre>import pandas as pd<br><br>def pull_post_data(subrreddit:str)-&gt;pd.DataFrame:<br>    &#39;&#39;&#39;<br>    Scrapes posts and their comments from a given subreddit<br><br>    Parameters<br>    ----------<br>    subrreddit: str<br>        The name of the subreddit to scrape<br>    <br>    Returns<br>    -------<br>    result_df: pd.DataFrame<br>        DataFrame with the folllowing columns: <br>        [&#39;subreddit&#39;, &#39;title&#39;, &#39;score&#39;, &#39;num_comments&#39;, &#39;url&#39;, &#39;comments&#39;]<br>    &#39;&#39;&#39;<br><br>    # Pull posts from last year NYCapartments subreddit<br>    post_list = []<br><br>    for post in subrreddit:<br>        post_dict = {}<br>        post_comments = []<br><br>        post_dict[&#39;subreddit&#39;] = post.subreddit_name_prefixed<br>        post_dict[&#39;title&#39;] = post.title<br>        post_dict[&#39;score&#39;] = post.score<br>        post_dict[&#39;num_comments&#39;] = post.num_comments<br>        post_dict[&#39;url&#39;] = post.shortlink<br>  <br>        # Retrieve full comments, including nested ones<br>        post.comments.replace_more(limit=None)<br>        for top_level_comment in post.comments:<br>            post_comments.append(top_level_comment.body)<br><br>        post_dict[&#39;comments&#39;] = post_comments<br>        post_list.append(post_dict)<br><br><br>    result_df = pd.DataFrame(post_list)<br>    return result_df</pre><p>This function loops through the posts and comments, compiles everything into a dictionary, and returns a DataFrame. Note the use of replace_more to retrieve all comments, including nested ones. This ensures you don’t miss out on any key discussion points. You can find the documentation <a href="https://praw.readthedocs.io/en/stable/tutorials/comments.html">here</a>.</p><p>Here’s a quick peak at the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmc-0kzQvipJLMKK05PXMA.png" /></figure><h3>📊Data Insights: What Can We Learn from Reddit Discussions?</h3><p>Once we’ve collected the data, several important questions arise about post engagement on the NYC Apartments subreddit.</p><h4><strong>How much engagement do posts typically receive?</strong></h4><p>By examining the distribution of comments, we see that the majority of posts get fewer than 100 comments. This suggests that while many posts are created, only a fraction spark in-depth discussions.</p><h4>Are there outliers in engagement?</h4><p>Yes! There’s a long tail of posts with over 300 comments. These rare, high-engagement posts likely revolve around topics that resonate deeply with the community, such as pressing rental issues or unique apartment listings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*MhaBrBd6gri4TcqQvwNiXQ.png" /></figure><h4>How do post upvotes and comments correlate?</h4><p>While most posts have moderate engagement, a few posts drive the majority of interaction with much higher upvotes and comments. There is a general trend where posts with more upvotes tend to receive more comments, but the correlation isn’t perfect, especially for outliers that might generate more discussion without corresponding upvotes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*gPlIez3ZgkE2Yb3e2TgQqw.png" /></figure><h4>What’s the typical upvote range for posts?</h4><p>Most posts fall within the range of 150 to 300 upvotes, showing moderate interest from the subreddit. However, there are occasional outliers with over 600 upvotes, indicating viral content that grabs more widespread attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*gio15CbLzeQkNxPmo7d3wg.png" /></figure><h4>Which posts have the highest engagement?</h4><p>To answer this, we can create a simple engagement metric that combines upvotes and comments:</p><pre># Create a new column to combine score and number of comments<br>data[&#39;engagement&#39;] = data[&#39;score&#39;] + data[&#39;num_comments&#39;]<br><br># Top 5 posts based on this new engagement metric<br>top_engaged_posts = data.nlargest(5, &#39;engagement&#39;)<br><br># Display the top engaged posts<br>print(top_engaged_posts[[&#39;title&#39;, &#39;score&#39;, &#39;num_comments&#39;, &#39;engagement&#39;]])</pre><p>This code gives us the top posts in terms of overall engagement, highlighting what the community is most interested in. Unsurprisingly, posts featuring skyline views, rental price discussions, or “too good to be true” apartment listings dominate the top spots.</p><p>At the top of the chart, a Midtown Manhattan studio with stunning views garnered nearly 2,000 interactions, underscoring New Yorkers’ love for breathtaking vistas despite the city’s well-known housing challenges. In the end, the pursuit of the ideal NYC apartment remains a blend of real estate savvy and hopeful optimism… after all, one can dream!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_dIOFXiskDcZDdgkevlRg.png" /></figure><h3>What’s Next?</h3><p>In my upcoming post, I will explore sentiment analysis using Hugging Face’s Twitter-RoBERTa-base model for Sentiment Analysis. This model, trained on a vast amount of social media data, is particularly suited for understanding the tone and sentiment of discussions within platforms like Reddit.</p><p>By applying it to the NYC Apartments subreddit, we’ll assess how users feel about certain topics — whether they’re expressing frustration, optimism, or indifference. This analysis will provide a deeper layer of insight, complementing the engagement data, and helping us understand not only how much users are interacting but also the emotional context behind their conversations.</p><p>Stay tuned for actionable sentiment insights and trends!</p><h3>Useful Resources:</h3><p><a href="https://praw.readthedocs.io/en/stable/getting_started/quick_start.html">https://praw.readthedocs.io/en/stable/getting_started/quick_start.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91afeb6acdb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Interactive Data Visualizations: A Beginner’s Guide to Streamlit]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@gabya06/creating-your-first-streamlit-app-with-matplotlib-seaborn-7e888e8a7470?source=rss-15998130867b------2"><img src="https://cdn-images-1.medium.com/max/1000/0*5gKVOiLJN-kKgJcx.png" width="1000"></a></p><p class="medium-feed-snippet">Explore this beginner-friendly guide to creating interactive data visualizations with Streamlit. Analyze and present product defect trends!</p><p class="medium-feed-link"><a href="https://medium.com/@gabya06/creating-your-first-streamlit-app-with-matplotlib-seaborn-7e888e8a7470?source=rss-15998130867b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@gabya06/creating-your-first-streamlit-app-with-matplotlib-seaborn-7e888e8a7470?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e888e8a7470</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 14:53:08 GMT</pubDate>
            <atom:updated>2024-08-13T17:48:05.434Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Intro to Natural Language Processing]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@gabya06/intro-to-natural-language-processing-tutorial-6aa1a99a5e97?source=rss-15998130867b------2"><img src="https://cdn-images-1.medium.com/max/600/1*3CqE5kSukO102gIsvowQcA.png" width="600"></a></p><p class="medium-feed-snippet">Unraveling Consumer Complaints: Essential Building Blocks in Text Processing for Data Scientists</p><p class="medium-feed-link"><a href="https://medium.com/@gabya06/intro-to-natural-language-processing-tutorial-6aa1a99a5e97?source=rss-15998130867b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@gabya06/intro-to-natural-language-processing-tutorial-6aa1a99a5e97?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aa1a99a5e97</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[text]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 13:35:51 GMT</pubDate>
            <atom:updated>2024-07-23T14:20:36.209Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Ensemble models for price forecasting: Gradient Boosting Regression]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@gabya06/ensemble-models-for-price-forecasting-2977c51adb69?source=rss-15998130867b------2"><img src="https://cdn-images-1.medium.com/max/1400/0*itXo8WQrJKanITvM.png" width="1400"></a></p><p class="medium-feed-snippet">Combining models using ensembles for price forecasting via scikit-learn</p><p class="medium-feed-link"><a href="https://medium.com/@gabya06/ensemble-models-for-price-forecasting-2977c51adb69?source=rss-15998130867b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@gabya06/ensemble-models-for-price-forecasting-2977c51adb69?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2977c51adb69</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 19:40:28 GMT</pubDate>
            <atom:updated>2024-10-29T13:50:42.898Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Getting Started with Web Scraping Amazon Reviews with BeautifulSoup]]></title>
            <link>https://medium.com/@gabya06/getting-started-with-web-scrapping-amazon-reviews-with-beautifulsoup-55671a97b85b?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/55671a97b85b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[amazon-reviews]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 14:24:09 GMT</pubDate>
            <atom:updated>2025-12-19T13:02:52.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with Web Scraping: Amazon Reviews with BeautifulSoup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g16W-oBedL2PsNE4c1xyHQ.png" /></figure><h3>What is Web Scraping?</h3><p>Simply put, web scraping refers to extracting data from websites automatically; and there are different ways of doing this: one could use an <a href="https://www.dataquest.io/blog/python-api-tutorial/">API</a> (if it is available) or scrape data using Python libraries such as <a href="https://pypi.org/project/beautifulsoup4/">BeautifulSoup</a>. There are other libraries such as <a href="https://docs.scrapy.org/en/latest/intro/tutorial.html">Scrapy</a> and <a href="https://selenium-python.readthedocs.io/getting-started.html#simple-usage">Selenium</a>. Scrapy is quite robust and can be used for larger scraping projects and Selenium is a web testing tool that automates web browsers which can also be used to extract data.</p><p>BeautifulSoup is a Python library for pulling data out of HTML and XML files. It can be installed using <em>pip install bs4. </em>I like using BeautifulSoup because it is pretty straight forward and easy to use. I thought it would be interesting to scrape Amazon reviews, and since I was searching for a new cat tree for my cat Bellini — I thought what better introduction to web scraping?</p><p>Here is a quick look at the cat tree on <a href="https://www.amazon.com/Modern-Natural-Branch-Scratching-Lifestyle/dp/B07X1T4G5T/ref=cm_cr_arp_d_product_top?ie=UTF8">Amazon</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YbTFMZ1hZES3o-OiXN_fQ.png" /></figure><p>In this post, I will discuss how to scrape a few Amazon reviews using Python. But, one review at a time to get us started…</p><h3>Pulling Data Using BeautifulSoup</h3><p>To understand BeautifulSoup and HTML tags, it is helpful to first inspect the Amazon page that we want to scrape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-LGORe-V0VKq52pR67Gog.png" /></figure><p>When you right click in the review a small menu will pop up where you can access the page source code by clicking on <em>Inspect</em>. You can also access the HTML text by going to the View -&gt; Developer -&gt; Developer Tools menu. Once you click on <em>Inspect</em> you will see the HTML structure which can be thought of as a breakdown of the webpage on the right side. The more you inspect and get to know the webpage, the easier scraping it will be!</p><p>One feature I like is that if you hover over the HTML text on the right side, you can see the corresponding elements highlighted on the left side (webpage).</p><p>Here is an example where we see the product title MAU Modern Cat Tree Tower, Natural Branch Cat Condo with the <em>h1</em> tag. It becomes higlighlighted as I hover on the <em>h1</em> class on the right side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*100XfDnh1SjMOnx1_pjKRg.png" /></figure><h3>The Fun Part — Python and BeautifulSoup</h3><p>To get started using Python, I need to my import statements and headers that I will pass in when reading the webpage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*sPWk35qKwD0udd0IGnoxzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*lAaONMZCWyrIzU6NB8s3Gg.png" /></figure><p>Using <em>urllib</em> and <em>urlopen</em> will help us easily open the url that we want. I created a helper function to pull web data and convert into HTML code using <em>bs4</em>. This specifies that we want to use the HTML parser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMCe4eVBwNEO7pU2d0uwjg.png" /></figure><p>Using my helper function, I can access the page content as HTML code and store it as <em>soup</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*wlT9wptsPAarsxySJ3qPdw.png" /></figure><h3>Product Title Using Headers</h3><p>Once I have the website content in HTML code, I want to start by simply extracting the product title.</p><p>Since this has been tagged as an <em>h1 </em>header, we find the first <em>h1</em> tag by doing the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SOR3KcSQ9AZEeSV7UBkXw.png" /></figure><p>Note that this returns one BeautifulSoup element which has <em>id</em> and <em>class</em> attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*iS8HwoCRwi51vFRtjoL9VA.png" /></figure><p>We can extract the actual header text by using the <em>.get_text()</em> function — and doing a little data cleaning while we’re at it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZHsBHjSs6OUv1b7_r9T_A.png" /></figure><p>BeautifulSoup also provides us with the ability to retrieve all elements with <em>h1</em> tags by using the <em>.find_all()</em> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kV-WKseYMIe3fsLEWQKdSg.png" /></figure><p>If we check the type of <em>all_headers</em>, we see that it is a <em>ResultSet</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02NBBSb5Iff94I59s6sgdQ.png" /></figure><p>In order to extract text from each of the items in the ResultSet, we have to iterate over each one. Here is an example of how to loop through each item and print its corresponding text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7z0pPOkDPlFVFghzafftzA.png" /></figure><p>And Voilà! Now we have our product title! Next, we will scrape product reviews for MAU Modern Cat Tree Tower.</p><h3>Product Reviews</h3><p>In order to extract product reviews, I have to go back to webpage and inspect the HTML text to see how it has been set up and find the corresponding tags and attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6EJBJwaZvgYJ0xTzpuVhA.png" /></figure><p>As I hover on the HTML text I see &lt;div&gt; with <em>id</em> attribute ‘cm_cr-review-list’ and <em>class</em> ‘a-section a-spacing-none review-views celwidget’ which gives me the hint that my review list is here. On the left side we see it highlighted as it is the corresponding element on the webpage.</p><p>Scrolling down a bit further, we see that each review has a unique <em>id</em> and <em>data-hook </em>attribute named ‘review’. There is additional information, but for now this is all we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NX5UJPHAIXPQpizHPFQ2Gw.png" /></figure><p>Using the <em>div</em> tag and <em>data-hook </em>attribute I am able to extract review information. Once again, I can use the <em>.find_all()</em> function which will return an iterable containing all the HTML for every review wrapped in a &lt;div &gt; element with the <em>data-hook </em>attribute ‘review’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLHptCoejsKQhn5yMZ0guQ.png" /></figure><p>Looking at our first review, we can recognize some of the same tags and attributes we saw on the webpage. I highlighted the <em>id</em> that we saw in the webpage. This is the raw HTML code so it does look a little messy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CS9WAOiT8su5DfBviMkp0w.png" /></figure><p>But, if we look at the <em>span</em> tags for the first review, it looks a little better and more organized.</p><p>We see the profile name Flower Momma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LT1uLOC7MhazRx4SZhiOwQ.png" /></figure><p>which matches what we see on Amazon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCqIJbK7nlbcE02TuNUVxw.png" /></figure><p>Using <em>.get_text()</em> we can retrieve the text in our first review for all elements with &lt;span<em>&gt;</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TS_eFI_REkZ2twpwQI9kBQ.png" /></figure><p>If we wanted to retrieve other information from the review, we would look for the appropriate tag. For example, to get the profile name we use &lt;span&gt; and search for elements with <em>class </em>attribute<em> </em>named “a-profile-name”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCya_HAnroMAHYV4zO7RnQ.png" /></figure><p>If we wanted to get the number of stars from the review we would use the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58IoqvI26pG285e-9si4WQ.png" /></figure><p>And, to extract the review content from this first review, we still use &lt;span&gt; with <em>class</em> “review-text” and <em>.get_text()</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDM0tdjrD-Kj884rLvAA1Q.png" /></figure><p>To do this for all reviews, I looped through the list of reviews and used the “review-text<em>”</em> <em>class </em>attribute once again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zkK-PHlboDUW_29VD0nTGw.png" /></figure><p>And finally, after a little data cleaning, we have the following list of Amazon reviews!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjeWNC8vJenI7INxKsaCkQ.png" /></figure><p>As you can see, once you understand the structure of the HTML text in a webpage by inspecting the page, then finding and extracting different information based on tags and attributes is quite easy using BeautifulSoup.</p><p>However, please note that each website is built differently and as a result the way this website uses tags will be different from another website. In case you are scraping another website — it is most likely not going to have the exact same HTML elements, tags and attributes as this example. So, it is important to match the attributes with the information you are trying to pull.</p><h3>Final Thoughts</h3><p>In this brief post, I discussed how to scrape Amazon customer reviews using BeautifulSoup in Python. If you are just getting started with web scraping, I hope this was helpful!</p><h4>Resources and Examples:</h4><p><a href="https://pypi.org/project/beautifulsoup4/">https://pypi.org/project/beautifulsoup4/</a></p><p><a href="https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/">https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/</a></p><p><a href="https://www.blazemeter.com/blog/scrapy-vs-selenium#:~:text=Selenium%20is%20an%20excellent%20automation,requests%2C%20Selenium%20can%20work%20better">https://www.blazemeter.com/blog/scrapy-vs-selenium#:~:text=Selenium%20is%20an%20excellent%20automation,requests%2C%20Selenium%20can%20work%20better</a></p><p><a href="https://www.techrepublic.com/article/reference-useful-html-tags-and-their-attributes/">https://www.techrepublic.com/article/reference-useful-html-tags-and-their-attributes/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55671a97b85b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Sentiment Analysis using TextBlob and VADER for Glassdoor Reviews]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@gabya06/python-sentiment-analysis-using-textblob-and-vader-for-glassdoor-reviews-cc9632babb73?source=rss-15998130867b------2"><img src="https://cdn-images-1.medium.com/max/600/1*YkbyX1T1ViBQHQZZAiumJQ.png" width="600"></a></p><p class="medium-feed-snippet">What do people really think about the companies they work for? Can we count on company ratings Glassdoor.com?</p><p class="medium-feed-link"><a href="https://medium.com/@gabya06/python-sentiment-analysis-using-textblob-and-vader-for-glassdoor-reviews-cc9632babb73?source=rss-15998130867b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@gabya06/python-sentiment-analysis-using-textblob-and-vader-for-glassdoor-reviews-cc9632babb73?source=rss-15998130867b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc9632babb73</guid>
            <category><![CDATA[vader]]></category>
            <category><![CDATA[text]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gaby A]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 14:56:04 GMT</pubDate>
            <atom:updated>2023-09-26T17:48:57.078Z</atom:updated>
        </item>
    </channel>
</rss>