<?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 Daniel Afrimi on Medium]]></title>
        <description><![CDATA[Stories by Daniel Afrimi on Medium]]></description>
        <link>https://medium.com/@danielafrimi?source=rss-339695f755ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hI7TQHmYRnyqsM3T.</url>
            <title>Stories by Daniel Afrimi on Medium</title>
            <link>https://medium.com/@danielafrimi?source=rss-339695f755ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:50:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielafrimi/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[Text Clustering using NLP techniques]]></title>
            <link>https://medium.com/@danielafrimi/text-clustering-using-nlp-techniques-c2e6b08b6e95?source=rss-339695f755ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e6b08b6e95</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Daniel Afrimi]]></dc:creator>
            <pubDate>Mon, 01 May 2023 10:40:05 GMT</pubDate>
            <atom:updated>2023-05-01T10:40:05.106Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, Natural Language Processing (NLP) has become increasingly popular as a tool for analyzing large volumes of text data.</p><p>However, with so much information available, it can be difficult to make sense of it all. This is where text clustering comes in.</p><p>Text clustering is the process of grouping similar documents together based on their content. By clustering text, we can identify patterns and trends that would otherwise be difficult to discern.</p><p>This technique has many applications, from market research to customer segmentation to sentiment analysis. In this blog post, we will explore how text clustering can be used to analyze text data and uncover insights that can be used to make better business decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*bFhIFYQQoawsF9ZCATl2Cw.png" /></figure><p>The notebook focused on text clustering using various embedding techniques. The dataset we are using is the 20newsgroups dataset with 3 categories. The goal is to compare several embedding approaches such as sentence transformers, GloVe, TF-IDF, and BERT-CLS, and cluster the resulting embeddings. This comparison can help to determine which approach provides the best clustering performance for the given dataset.</p><p>To achieve this, we have taken several steps. First, we have preprocessed the text data and converted it into numerical representations using the different embedding approaches. Next, we have applied clustering algorithms to the resulting embeddings to group the documents into clusters. Finally, you have compared the performance of the different embedding approaches by evaluating the quality of the resulting clusters using relevant metrics such as silhouette score or purity.</p><p>By comparing the different embedding approaches, we can gain insights into which technique is most effective for clustering text data in general, and for the 20newsgroups dataset in particular. This information can be valuable for future projects involving text clustering, as it can inform the selection of the most appropriate embedding approach for a given dataset and task.</p><pre>categories = [<br> &#39;comp.os.ms-windows.misc&#39;,<br> &#39;rec.sport.hockey&#39;,<br> &#39;soc.religion.christian&#39;,<br>]<br><br>dataset = fetch_20newsgroups(subset=&#39;train&#39;, categories=categories, shuffle=True, remove=(&#39;headers&#39;, &#39;footers&#39;, &#39;quotes&#39;))<br>data = {&#39;text&#39;: dataset.data, &#39;target&#39;: dataset.target}<br>df = pd.DataFrame(data)</pre><p>To begin, we preprocess the data by eliminating links, special characters, stripping whitespace, and removing stopwords.</p><pre>def preprocess_text(text: str) -&gt; str:<br>    # remove links<br>    text = re.sub(r&quot;http\S+&quot;, &quot;&quot;, text)<br>    # remove special chars and numbers<br>    text = re.sub(&quot;[^A-Za-z]+&quot;, &quot; &quot;, text)<br>    <br>    # remove stopwords<br>    tokens = nltk.word_tokenize(text)<br>    tokens = [w for w in tokens if not w.lower() in stopwords.words(&quot;english&quot;)]<br>    text = &quot; &quot;.join(tokens)<br>    text = text.lower().strip()<br>    <br>    return text<br><br>df[&#39;text_cleaned&#39;] = df[&#39;text&#39;].apply(lambda text: preprocess_text(text))<br>df = df[df[&#39;text_cleaned&#39;] != &#39;&#39;]</pre><p>After preprocessing the data, the next step is typically to embed the text into a numerical vector space representation. There are several embedding techniques available, each with its own strengths and weaknesses.</p><h3><strong>TF-IDF Vectorization</strong></h3><p>This is a simple but effective method for generating vector representations of sentences. It stands for “term frequency-inverse document frequency” and it calculates the importance of words in a sentence by taking into account how often they appear in the sentence and how rare they are in the entire corpus of sentences.</p><pre>vectorizer = TfidfVectorizer(sublinear_tf=True, min_df=5, max_df=0.95)<br>X = vectorizer.fit_transform(df[&#39;text_cleaned&#39;]).toarray()</pre><h3><strong>Sentence Transformer</strong></h3><p>Sentence Transformers are deep learning models that can encode natural language sentences into high-dimensional vector representations. They are trained using a pre-training and fine-tuning approach and have achieved state-of-the-art performance on several natural language processing tasks. These models are widely used for various applications such as chatbots, search engines, and recommendation systems.</p><pre>st = time.time()<br><br>model = SentenceTransformer(&#39;paraphrase-MiniLM-L6-v2&#39;)<br>df[&#39;encode_transforemers&#39;] = df[&#39;text_cleaned&#39;].apply(lambda text: model.encode(text, convert_to_numpy=True).flatten())<br><br>et = time.time()<br><br>print(&quot;Elapsed time: {:.2f} seconds&quot;.format(et - st))<br><br>X_transformers = np.vstack(df[&#39;encode_transforemers&#39;])</pre><h3><strong>Glove</strong></h3><p>GloVe is a word embedding technique that represents words as dense vectors in a high-dimensional space. It captures both local and global context, making it useful for various tasks. To cluster sentences using GloVe, one approach is to concatenate the word vectors in a sentence, form a matrix, and then apply a clustering algorithm such as k-means. The resulting clusters can reveal common themes or patterns in the data.</p><pre>embeddings = GloVe(name=&#39;6B&#39;, dim=100)<br><br># Set the maximum sentence length and embedding dimension<br>max_length = 100 <br>embedding_dim = 100<br><br># define a function to convert a sentence to a fixed-size vector using GloVe embeddings<br>def sentence_embedding(sentence):<br>    words = sentence.split()<br>    num_words = min(len(words), max_length)<br>    embedding_sentence = np.zeros((max_length, embedding_dim))<br>    <br>    for i in range(num_words):<br>        word = words[i]<br>        if word in embeddings.stoi:<br>            embedding_sentence[i] = embeddings.vectors[embeddings.stoi[word]]<br>            <br>    return embedding_sentence.flatten()<br><br>df[&#39;encode_glove&#39;] = df[&#39;text_cleaned&#39;].apply(lambda sentence: sentence_embedding(sentence))<br>X_glove = np.vstack(df[&#39;encode_glove&#39;])</pre><h3>BERT — [CLS] token for sentence context</h3><p>BERT, is a pre-trained deep learning model that can be fine-tuned for various natural language processing tasks. One of the main innovations of BERT is its ability to represent both the left and right context of a word, allowing it to better capture the meaning of a sentence.</p><p>In BERT, the [CLS] token, which stands for “classification”, is a special token that is inserted at the beginning of every input sequence. During pre-training, BERT is trained to predict the correct class label for the entire sequence based on the [CLS] token representation, which is meant to capture the overall meaning of the sequence.</p><pre># Load pre-trained BERT model and tokenizer<br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;)<br>model = BertModel.from_pretrained(&#39;bert-base-uncased&#39;)<br><br>def get_cls_sentence(sentence):<br>    # Tokenize input sentence and convert to tensor<br>    input_ids = torch.tensor([tokenizer.encode(sentence, add_special_tokens=True, max_length=512)])<br><br>    # Pass input through BERT model and extract embeddings for [CLS] token<br>    with torch.no_grad():<br>        outputs = model(input_ids)<br>        cls_embedding = outputs[0][:, 0, :]<br>    <br>    return cls_embedding.flatten()</pre><pre>st = time.time()<br><br>df[&#39;cls_bert&#39;] = df[&#39;text_cleaned&#39;].apply(lambda sentence: get_cls_sentence(sentence))<br><br>et = time.time()<br><br>print(&quot;Elapsed time: {:.2f} seconds&quot;.format(et - st))<br><br>X_cls_bert = np.vstack(df[&#39;cls_bert&#39;])</pre><p>Once we have embedded the text data, the next step is to cluster the embedded representations using a clustering algorithm. One popular clustering algorithm is K-Means, which partitions the data into K clusters based on their similarity. To apply K-Means clustering, we first need to specify the number of clusters we want to identify. In this case, we will choose K=3, as we want to identify three classes in our dataset. We call these classes centroids, and they represent the center of each cluster.</p><p>K-Means clustering works by randomly assigning each data point to one of the K centroids. Then, it iteratively reassigns each data point to the centroid that is closest to it, and updates the centroids based on the new assignments. This process continues until the centroids no longer change, or until a maximum number of iterations is reached. Once the algorithm converges, each data point will be assigned to one of the K clusters, based on which centroid it is closest to.</p><p>In summary, by applying K-Means clustering to the embedded text data, we can identify three classes or centroids that represent the different clusters of similar documents. This can be a powerful technique for analyzing large volumes of text data and uncovering patterns and insights that would be difficult to identify through manual analysis.</p><p>After we have clustered the embedded text data using K-Means clustering, we can further analyze the data by reducing the dimensionality of the embedded representations and visualizing the results. One popular technique for dimensionality reduction is Principal Component Analysis (PCA).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upJ-R8PW3nxWRF-7fgTGYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IplzQ8OkDa1XnyOaC5Cxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nyoi_cHVAiuMEjAFmEBvKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jb-bYO4gNmxyfx8MGpefag.png" /></figure><p>To evaluate the performance of a clustering algorithm like k-means, we use various metrics that compare the predicted clusters to the ground truth labels. Here are a few common metrics:</p><p>Adjusted Rand Index (ARI): measures the similarity between the predicted clusters and the ground truth labels, taking into account chance agreement. ARI ranges from -1 to 1, where 1 indicates perfect agreement and 0 indicates random clustering.</p><p>Normalized Mutual Information (NMI): measures the mutual information between the predicted clusters and the ground truth labels, normalized by the entropy of the clusters and labels. NMI ranges from 0 to 1, where 1 indicates perfect agreement.</p><p>Fowlkes-Mallows Index (FMI): measures the geometric mean of the precision and recall of the predicted clusters with respect to the ground truth labels. FMI ranges from 0 to 1, where 1 indicates perfect agreement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vn7GTO5EdDXIjkXs7OISg.png" /><figcaption>Clusters metrics per method</figcaption></figure><p>The following code performs the aforementioned steps.</p><pre>def eval_cluster(embedding):<br>    y_pred = kmeans.fit_predict(embedding)<br>    <br>    # Evaluate the performance using ARI, NMI, and FMI<br>    ari = adjusted_rand_score(df[&quot;target&quot;], y_pred)<br>    nmi = normalized_mutual_info_score(df[&quot;target&quot;], y_pred)<br>    fmi = fowlkes_mallows_score(df[&quot;target&quot;], y_pred)<br><br>    # Print Metrics scores<br>    print(&quot;Adjusted Rand Index (ARI): {:.3f}&quot;.format(ari))<br>    print(&quot;Normalized Mutual Information (NMI): {:.3f}&quot;.format(nmi))<br>    print(&quot;Fowlkes-Mallows Index (FMI): {:.3f}&quot;.format(fmi))</pre><pre>def dimension_reduction(embedding, method):<br><br>    pca = PCA(n_components=2, random_state=42)<br><br>    pca_vecs = pca.fit_transform(embedding)<br><br>    # save our two dimensions into x0 and x1<br>    x0 = pca_vecs[:, 0]<br>    x1 = pca_vecs[:, 1]<br>    <br>    df[f&#39;x0_{method}&#39;] = x0 <br>    df[f&#39;x1_{method}&#39;] = x1</pre><pre>def plot_pca(x0_name, x1_name, cluster_name, method):<br><br>    plt.figure(figsize=(12, 7))<br><br>    plt.title(f&quot;TF-IDF + KMeans 20newsgroup clustering with {method}&quot;, fontdict={&quot;fontsize&quot;: 18})<br>    plt.xlabel(&quot;X0&quot;, fontdict={&quot;fontsize&quot;: 16})<br>    plt.ylabel(&quot;X1&quot;, fontdict={&quot;fontsize&quot;: 16})<br><br>    sns.scatterplot(data=df, x=x0_name, y=x1_name, hue=cluster_name, palette=&quot;viridis&quot;)<br>    plt.show()</pre><pre>for embedding_and_method in [(X, &#39;tfidf&#39;), (X_transformers, &#39;transformers&#39;), (X_glove, &#39;glove&#39;), ((X_cls_bert, &#39;Bert-CLS&#39;)) ]:<br>    embedding, method = embedding_and_method[0], embedding_and_method[1]<br>    <br>    # initialize kmeans with 3 centroids<br>    kmeans = KMeans(n_clusters=3, random_state=42)<br><br>    # fit the model<br>    kmeans.fit(embedding)<br><br>    # store cluster labels in a variable<br>    clusters = kmeans.labels_<br><br>    # Assign clusters to our dataframe<br>    clusters_result_name = f&#39;cluster_{method}&#39;<br>    df[clusters_result_name] = clusters<br>    <br>    eval_cluster(embedding)<br>    <br>    dimension_reduction(embedding, method)<br>    <br>    plot_pca(f&#39;x0_{method}&#39;, f&#39;x1_{method}&#39;, cluster_name=clusters_result_name, method=method)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2e6b08b6e95" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>