<?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 Roytalman on Medium]]></title>
        <description><![CDATA[Stories by Roytalman on Medium]]></description>
        <link>https://medium.com/@roytalman_7701?source=rss-1d826fe603c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HfOYewa4uQh2NrDC.jpg</url>
            <title>Stories by Roytalman on Medium</title>
            <link>https://medium.com/@roytalman_7701?source=rss-1d826fe603c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:54:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roytalman_7701/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[Fine-Tuned Embedding With Contrastive Learning]]></title>
            <link>https://medium.com/@roytalman_7701/fine-tuned-embedding-with-contrastive-learning-71da7b57164d?source=rss-1d826fe603c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/71da7b57164d</guid>
            <dc:creator><![CDATA[Roytalman]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 15:40:41 GMT</pubDate>
            <atom:updated>2024-08-24T15:40:41.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Embeddings are a crucial building block that play a role in almost every deep learning project and in a variety of tasks such as retrieval, clustering, and classification. One of the biggest challenges I’ve encountered, which has happened to me many times, is embeddings that are not sufficiently relevant to my specific problem. As a result, samples or data instances that should be close in specific data are not close enough in the embedding space.</p><p>This isn’t surprising, as the embedding was trained on a wide variety of data and tasks, and is not specifically “expert” in my data and problem domain. This is one of the main reasons why Retrieval-Augmented Generation (RAG) often fails for domains that are more specific.</p><p>Since retraining an embedding model, or even fine-tuning the model, is not feasible with the small amount of data I have, and could also be costly and full of risks, I tried to develop a solution that takes the existing embedding and creates a new one that is more relevant to my problem space. This approach can work with a small amount of labeled data.</p><p>The algorithm in this article uses a simple feedforward neural network (FNN), trained with contrastive loss, to map the data from the original embedding space to a new embedding space that is better suited to my problem space.</p><p>This approach has surprisingly benefited me many times across different types of problems and in various problem domains. Additionally, the specific loss function in the GitHub repository is quite effective for this purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*Uf7tfgMo_WJ-S3ThSVjQeg.png" /><figcaption>Illustration of the algorithm: While the deep learning model can differentiate well between some domains, samples from the same domain but with different sub-domain embedding spaces may be close and difficult to differentiate. The FNN, trained on contrastive loss, can create a new embedding where sub-domains can be differentiated.</figcaption></figure><h4><strong>Contrastive loss:</strong></h4><p>Instead of training a neural network to predict a class, we will use contrastive learning to train a simple feedforward network to learn a new embedding, so that samples from the same class (positive pair) will be closer to each other, and samples from different classes (negative pair) will be farther apart. The contrastive loss equation that I found most effective is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*Y8Zdr8RIdp69VSPUQnae0Q.png" /><figcaption>Where Cn​ and Cp are the cosine similarity of the negative pair and positive pair, respectively, and M is a constant margin.</figcaption></figure><p>The complete code of the loss, NN and exampels can be found here: <a href="https://github.com/roytalman/Deep_contrastive_embedding">https://github.com/roytalman/Deep_contrastive_embedding</a></p><h4>Coding 20news classification</h4><p>I chose to demonstrate this on an NLP classification task, as it is easy to illustrate. You may find a clustering example in the GitHub repository, and I may add a RAG example in the future.</p><p>First, we will load the relevant libraries and data. I chose a subset of categories with similar topics that might be tricky to distinguish for an NLP classifier.</p><pre>import numpy as np<br>from sklearn.datasets import fetch_20newsgroups<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score, classification_report<br>from sklearn.model_selection import train_test_split<br>from sentence_transformers import SentenceTransformer<br>from tqdm import tqdm<br>import torch<br># local dependencies from git repository https://github.com/roytalman/Deep_contrastive_embedding<br>from contrastive import Contrastive_loss<br>from utils import plot_tsne,Net_embed,finetune_embeddig<br><br># Define the categories we want to classify<br>categories = [&#39;sci.space&#39;, &#39;sci.med&#39;,&#39;sci.electronics&#39;,<br>&#39;comp.os.ms-windows.misc&#39;,&#39;comp.sys.ibm.pc.hardware&#39;,&#39;comp.sys.mac.hardware&#39;]<br><br># Fetch the training dataset<br>newsgroups_train = fetch_20newsgroups(subset=&#39;train&#39;, categories=categories)<br># Fetch the testing dataset<br>newsgroups_test = fetch_20newsgroups(subset=&#39;test&#39;, categories=categories)</pre><p>Since we want to test this method on a small training set, we will drop 75% of the training data and retain around 100 samples per class. You may reduce the number of elements per class to as few as 10–20 and still benefit from this fine-tuning approach, depending on your data, your embedding model, and your neural network.</p><pre># dump 75% of data<br>X_train,X_dump,y_train,y_dump = train_test_split(newsgroups_train.data,<br>        newsgroups_train.target,train_size=0.25,random_state=0)<br><br>X_test,X_dump,y_test,y_dump =  train_test_split(newsgroups_test.data,<br>      newsgroups_test.target,train_size=0.25,random_state=0)</pre><p>We will create a helper function that trains a logistic regression classifier on the embedding features and predicts the test set performance. You may choose any classifier you want, but a logistic regression classifier does a good job on such small datasets.</p><pre>def fit_predict_embedding(embed_train,y_train,embed_test,y_test,target_names  ):<br>    clf = LogisticRegression(max_iter=10000)<br>    # Train the model on embedding:<br>    clf.fit(embed_train, y_train)<br>    # Make predictions on the test data:<br>    predicted = clf.predict(embed_test)<br>    #print performance report<br>    report = classification_report(y_test, predicted, target_names=newsgroups_test.target_names)<br>    print(&quot;Classification Report:\n&quot;, report)</pre><p>Next, we will use embeddings extracted by a deep learning model for classification. I chose ‘Alibaba-NLP/gte-base-en-v1.5’, which is one of the leading models on Hugging Face, yet it is relatively light and easy to work with. Although I didn’t use a GPU and batch processing, you may want to use them to save some time.</p><pre># load model<br>model = SentenceTransformer(&#39;Alibaba-NLP/gte-base-en-v1.5&#39;, trust_remote_code=True)<br>embedding_mat_train = np.zeros((len(X_train),768))<br>embedding_mat_test = np.zeros((len(X_test),768))<br><br># extract embedding:<br>for i in tqdm(range(len(X_train))):<br>    embedding_mat_train[i,:] = model.encode(X_train[i])<br><br>for i in tqdm(range(len(X_test))):<br>    embedding_mat_test[i,:] = model.encode(X_test[i])<br><br># predict using gte embedding:<br>fit_predict_embedding(embedding_mat_train,y_train,embedding_mat_test,y_test,newsgroups_test.target_names  )</pre><pre>Accuracy: 0.80<br>Classification Report:<br>                           precision    recall  f1-score   support<br><br> comp.os.ms-windows.misc       0.81      0.81      0.81        99<br>comp.sys.ibm.pc.hardware       0.66      0.64      0.65        99<br>   comp.sys.mac.hardware       0.71      0.74      0.72       104<br>         sci.electronics       0.74      0.75      0.74        97<br>                 sci.med       0.95      0.96      0.95        94<br>               sci.space       0.99      0.95      0.97        95<br><br>                accuracy                           0.80       588<br>               macro avg       0.81      0.81      0.81       588<br>            weighted avg       0.81      0.80      0.80       588</pre><p>Now, we will train the FNN to learn a new embedding space. We will set the new embedding space size to 32. Note that different datasets will require different hyperparameters and possibly a different backbone, but even without hyperparameter tuning, this approach works better than the original embedding. It’s important to note that this step does not use test data, so it does not lead to overfitting on the test set. However, using a training set that is too small, training for too many epochs, or choosing incorrect hyperparameters can cause overfitting on the training set and lead to poor performance on the test set.</p><pre># train neural network using deep contrastive learnig  <br>net = finetune_embeddig(embedding_mat_train, y_train,N_epoch=15,out_dim=32,<br>                   verbose=True,drop_prob = 0.3,hidden_dim = 256,margin=0.2)</pre><p>Finally, we will extract the new embedding and train a logistic regression classifier.</p><pre># calculate test data embedding and Tsne<br>net.eval()<br>embedding_out_test = <br>    net(torch.from_numpy(embedding_mat_test).float()).detach().numpy()<br><br>embedding_out_train = <br>    net(torch.from_numpy(embedding_mat_train).float()).detach().numpy()<br># classification with new embedding:<br>fit_predict_embedding(embedding_out_train,y_train,embedding_out_test,<br>y_test,newsgroups_test.target_names  )</pre><pre>Accuracy: 0.86<br>Classification Report:<br>                           precision    recall  f1-score   support<br><br> comp.os.ms-windows.misc       0.88      0.85      0.86        99<br>comp.sys.ibm.pc.hardware       0.75      0.80      0.77        99<br>   comp.sys.mac.hardware       0.78      0.80      0.79       104<br>         sci.electronics       0.81      0.81      0.81        97<br>                 sci.med       0.97      0.96      0.96        94<br>               sci.space       0.98      0.93      0.95        95<br><br>                accuracy                           0.86       588<br>               macro avg       0.86      0.86      0.86       588<br>            weighted avg       0.86      0.86      0.86       588</pre><p>We can see a significant improvement in the overall performance. Moreover, classes that had poor performance, such as ‘comp.sys.ibm.pc.hardware’ and ‘comp.sys.mac.hardware,’ show significant improvement. It seems that contrastive learning has managed to differentiate between them more effectively.</p><h4><strong>Summary</strong></h4><p>Fine-tuning embeddings may be a promising direction for the future of deep learning, as it is easy to implement, requires a small amount of data, and benefits many tasks. Training with the loss function presented here is both efficient and effective.</p><p>In a world where most companies no longer train neural networks from scratch, and off-the-shelf solutions do not fully address their needs, fine-tuning embeddings can be the answer.</p><p>You are welcome to use the code and let me know what you think, or even donate to this repository.</p><p>Git: <a href="https://github.com/roytalman/Deep_contrastive_embedding">https://github.com/roytalman/Deep_contrastive_embedding</a></p><p>Mail: roytalman@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71da7b57164d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>