{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Shashank Kapadia",
  "title_listed": "Domain Adaptation: Fine-Tune Pre-Trained NLP Models",
  "keywords": "",
  "domain": "文本处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/",
  "publish_date": "2023-07-04",
  "corpus_stage": "",
  "notes": "",
  "id": "73787309c4c1",
  "collected_at": "2026-10-02T09:56:27",
  "title": "Domain Adaptation: Fine-Tune Pre-Trained NLP Models | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# Domain Adaptation: Fine-Tune Pre-Trained NLP Models\nA step-by-step guide to fine-tuning pre-trained NLP models for any domain\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nJuly 4, 20238 min read\n![Green and red dots and lines in a mesh pattern](../images/000.jpg)\nPhoto by Pietro Jeng on Unsplash \n_Preface: This article presents a summary of information about the given topic. It should not be considered original research. The information and code included in this article may be influenced by things I have read or seen in the past from various online articles, research papers, books, and open-source code._\n_Co-Author:_[_Billy Hines_](https://medium.com/u/f6bf67256839?source=post_page---user_mention--a06659ca6668---------------------------------------)\n## Table of contents\n  * [Introduction](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Introduction)\n  * [Theoretical framework](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Theoretical-framework)\n  * [Data overview](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Data-overview)\n  * [Starting point: The baseline model](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Starting-point)\n  * [Fine-tuning the model](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Fine-tuning)\n  * [Evaluating the results](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Evaluation)\n  * [Closing thoughts](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Closing-thoughts)\n\n\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## Introduction\nIn today’s world, the availability of pre-trained NLP models has greatly simplified the interpretation of textual data using deep learning techniques. However, while these models excel in general tasks, they often lack adaptability to specific domains. This comprehensive guide aims to walk you through the process of fine-tuning pre-trained NLP models to achieve improved performance in a particular domain.\n### Motivation\nAlthough pre-trained NLP models like BERT and the Universal Sentence Encoder (USE) are effective in capturing linguistic intricacies, their performance in domain-specific applications can be limited due to the diverse range of datasets they are trained on. This limitation becomes evident when analyzing relationships within a specific domain.\nFor example, when working with employment data, we expect the model to recognize the closer proximity between the roles of ‘Data Scientist’ and ‘Machine Learning Engineer’, or the stronger association between ‘Python’ and ‘TensorFlow’. Unfortunately, general-purpose models often miss these nuanced relationships.\nThe table below demonstrates the discrepancies in the similarity obtained from a base multilingual USE model:\n![](../images/001.png)\nFig 1. Similarity score between two text vectors from base [MultiLingual Universal Sentence Encoder Model](https://tfhub.dev/google/universal-sentence-encoder-multilingual/3)\nTo address this issue, we can fine-tune pre-trained models with high-quality, domain-specific datasets. This adaptation process significantly enhances the model’s performance and precision, fully unlocking the potential of the NLP model.\n> When dealing with large pre-trained NLP models, it is advisable to initially deploy the base model and consider fine-tuning only if its performance falls short for the specific problem at hand.\nThis tutorial focuses on fine-tuning the Universal Sentence Encoder (USE) model using easily accessible open-source data.\n## Theoretical overview\nFine-tuning an ML model can be achieved through various strategies, such as supervised learning and reinforcement learning. In this tutorial, we will concentrate on a one(few)-shot learning approach combined with a Siamese architecture for the fine-tuning process.\n### Methodology\nIn this tutorial, we utilize a Siamese neural network, which is a specific type of Artificial Neural Network. This network leverages shared weights while simultaneously processing two distinct input vectors to compute comparable output vectors. Inspired by one-shot learning, this approach has proven to be particularly effective in capturing semantic similarity, although it may require longer training times and lack probabilistic output.\nA Siamese neural network creates an ‘embedding space’ where related concepts are positioned closely, enabling the model to better discern semantic relations.\n![](../images/body-ffb4f02ce32cfc46be79.png)\nFig 2. Siamese architecture to fine-tune pre-trained NLP model\n  * **Twin branches and shared weights** : The architecture consists of two identical branches, each containing an embedding layer with shared weights. These dual branches handle two inputs simultaneously, either similar or dissimilar.\n  * **Similarity and transformation** : The inputs are transformed into vector embeddings using the pre-trained NLP model. The architecture then calculates the similarity between the vectors. The similarity score, ranging between -1 and 1, quantifies the angular distance between the two vectors, serving as a metric for their semantic similarity.\n  * **Contrastive loss and learning** : The model’s learning is guided by the “Contrastive Loss,” which is the difference between the expected output (similarity score from the training data) and the computed similarity. This loss guides the adjustment of the model’s weights to minimize the loss and enhance the quality of the learned embeddings.\n\n\nTo learn more about one(few)-shot learning, siamese architecture, and contrastive loss, refer to the following resources:\n  * [A Gentle Introduction to Siamese Neural Networks Architecture](https://www.projectpro.io/article/siamese-neural-networks/718?source=post_page-----a06659ca6668---------------------------------------)\n  * [What is one-shot learning?](https://bdtechtalks.com/2020/08/12/what-is-one-shot-learning/?source=post_page-----a06659ca6668---------------------------------------)\n  * [Contrastive Loss Explained](https://towardsdatascience.com/contrastive-loss-explaned-159f2d4a87ec?source=post_page-----a06659ca6668---------------------------------------)\n\n\nThe complete code is available as a [Jupyter Notebook on GitHub](https://github.com/kapadias/medium-articles/blob/master/natural-language-processing/embedding-models/domain_adaption_fine_tune_nlp_model.ipynb).\n## Data overview\nFor the fine-tuning of pre-trained NLP models using this method, the training data should consist of pairs of text strings accompanied by similarity scores between them.\nThe training data follows the format shown below:\n![](../images/body-31ac304c1a0644a1326b.png)\nFig 3. Sample Format for Training Data\nIn this tutorial, we use a dataset sourced from the [ESCO classification dataset](https://esco.ec.europa.eu/en), which has been transformed to generate similarity scores based on the relationships between different data elements.\n> Preparing the training data is a crucial step in the fine-tuning process. It is assumed that you have access to the required data and a method to transform it into the specified format. Since the focus of this article is to demonstrate the fine-tuning process, we will omit the details of how the data was generated using the ESCO dataset.\n> The ESCO dataset is available for developers to freely utilize as a foundation for various applications that offer services like autocomplete, suggestion systems, job search algorithms, and job matching algorithms. The dataset used in this tutorial has been transformed and provided as a sample, allowing unrestricted usage for any purpose.\nLet’s start by examining the training data:\npython\n\n```\nimport pandas as pd\n\n# Read the CSV file into a pandas DataFrame\ndata = pd.read_csv(\"./data/training_data.csv\")\n\n# Print head\ndata.head()\n```\n\n![](../images/body-709061fe2e773d26e7a7.png)\nFig 4. Sample data used for fine-tuning the model\n## Starting point: The baseline model\nTo begin, we establish the [multilingual universal sentence encoder](https://tfhub.dev/google/universal-sentence-encoder-multilingual/3) as our baseline model. It is essential to set this baseline before proceeding with the fine-tuning process.\nFor this tutorial, we will use the STS benchmark and a sample similarity visualization as metrics to evaluate the changes and improvements achieved through the fine-tuning process.\n> The STS Benchmark dataset consists of English sentence pairs, each associated with a similarity score. During the model training process, we evaluate the model’s performance on this benchmark set. The persisted scores for each training run are the Pearson correlation between the predicted similarity scores and the actual similarity scores in the dataset.\n> These scores ensure that as the model is fine-tuned with our context-specific training data, it maintains some level of generalizability.\npython\n\n```\n# Loads the Universal Sentence Encoder Multilingual module from TensorFlow Hub.\nbase_model_url = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\nbase_model = tf.keras.Sequential([\n    hub.KerasLayer(base_model_url,\n                   input_shape=[],\n                   dtype=tf.string,\n                   trainable=False)\n])\n\n# Defines a list of test sentences. These sentences represent various job titles.\ntest_text = ['Data Scientist', 'Data Analyst', 'Data Engineer',\n             'Nurse Practitioner', 'Registered Nurse', 'Medical Assistant',\n             'Social Media Manager', 'Marketing Strategist', 'Product Marketing Manager']\n\n# Creates embeddings for the sentences in the test_text list. \n# The np.array() function is used to convert the result into a numpy array.\n# The .tolist() function is used to convert the numpy array into a list, which might be easier to work with.\nvectors = np.array(base_model.predict(test_text)).tolist()\n\n# Calls the plot_similarity function to create a similarity plot.\nplot_similarity(test_text, vectors, 90, \"base model\")\n\n# Computes STS benchmark score for the base model\npearsonr = sts_benchmark(base_model)\nprint(\"STS Benachmark: \" + str(pearsonr))\n```\n\n![](../images/body-71c79790265b4248fdbb.png)\nFig 5. Similarity visualizations across test words\n> STS Benchmark (dev): 0.8325\n## Fine-tuning the model\nThe next step involves constructing the siamese model architecture using the baseline model and fine-tuning it with our domain-specific data.\npython\n\n```\n# Load the pre-trained word embedding model\nembedding_layer = hub.load(base_model_url)\n\n# Create a Keras layer from the loaded embedding model\nshared_embedding_layer = hub.KerasLayer(embedding_layer, trainable=True)\n\n# Define the inputs to the model\nleft_input = keras.Input(shape=(), dtype=tf.string)\nright_input = keras.Input(shape=(), dtype=tf.string)\n\n# Pass the inputs through the shared embedding layer\nembedding_left_output = shared_embedding_layer(left_input)\nembedding_right_output = shared_embedding_layer(right_input)\n\n# Compute the cosine similarity between the embedding vectors\ncosine_similarity = tf.keras.layers.Dot(axes=-1, normalize=True)(\n    [embedding_left_output, embedding_right_output]\n)\n\n# Convert the cosine similarity to angular distance\npi = tf.constant(math.pi, dtype=tf.float32)\nclip_cosine_similarities = tf.clip_by_value(\n    cosine_similarity, -0.99999, 0.99999\n)\nacos_distance = 1.0 - (tf.acos(clip_cosine_similarities) / pi)\n\n# Package the model\nencoder = tf.keras.Model([left_input, right_input], acos_distance)\n\n# Compile the model\nencoder.compile(\n    optimizer=tf.keras.optimizers.Adam(\n        learning_rate=0.00001,\n        beta_1=0.9,\n        beta_2=0.9999,\n        epsilon=0.0000001,\n        amsgrad=False,\n        clipnorm=1.0,\n        name=\"Adam\",\n    ),\n    loss=tf.keras.losses.MeanSquaredError(\n        reduction=keras.losses.Reduction.AUTO, name=\"mean_squared_error\"\n    ),\n    metrics=[\n        tf.keras.metrics.MeanAbsoluteError(),\n        tf.keras.metrics.MeanAbsolutePercentageError(),\n    ],\n)\n\n# Print the model summary\nencoder.summary()\n```\n\n![](../images/body-202dd8cdfda101c9caa5.png)\nFig 6. Model architecture for fine-tuning\n### Fit the model\npython\n\n```\n# Define early stopping callback\nearly_stop = keras.callbacks.EarlyStopping(\n    monitor=\"loss\", patience=3, min_delta=0.001\n)\n\n# Define TensorBoard callback\nlogdir = os.path.join(\".\", \"logs/fit/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\ntensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)\n\n# Model Input\nleft_inputs, right_inputs, similarity = process_model_input(data)\n\n# Train the encoder model\nhistory = encoder.fit(\n    [left_inputs, right_inputs],\n    similarity,\n    batch_size=8,\n    epochs=20,\n    validation_split=0.2,\n    callbacks=[early_stop, tensorboard_callback],\n)\n\n# Define model input\ninputs = keras.Input(shape=[], dtype=tf.string)\n\n# Pass the input through the embedding layer\nembedding = hub.KerasLayer(embedding_layer)(inputs)\n\n# Create the tuned model\ntuned_model = keras.Model(inputs=inputs, outputs=embedding)\n```\n\n## Evaluation\nNow that we have the fine-tuned model, let’s re-evaluate it and compare the results to those of the base model.\npython\n\n```\n# Creates embeddings for the sentences in the test_text list. \n# The np.array() function is used to convert the result into a numpy array.\n# The .tolist() function is used to convert the numpy array into a list, which might be easier to work with.\nvectors = np.array(tuned_model.predict(test_text)).tolist()\n\n# Calls the plot_similarity function to create a similarity plot.\nplot_similarity(test_text, vectors, 90, \"tuned model\")\n\n# Computes STS benchmark score for the tuned model\npearsonr = sts_benchmark(tuned_model)\nprint(\"STS Benachmark: \" + str(pearsonr))\n```\n\n![](../images/body-af8d6efee7bc40ca919f.png)\n> STS Benchmark (dev): 0.8349\nBased on fine-tuning the model on the relatively small dataset, the STS benchmark score is comparable to that of the baseline model, indicating that the tuned model still exhibits generalizability. However, the similarity visualization demonstrates strengthened similarity scores between similar titles and a reduction in scores for dissimilar ones.\n## Closing thoughts\nFine-tuning pre-trained NLP models for domain adaptation is a powerful technique to improve their performance and precision in specific contexts. By utilizing quality, domain-specific datasets and leveraging siamese neural networks, we can enhance the model’s ability to capture semantic similarity.\nThis tutorial provided a step-by-step guide to the fine-tuning process, using the Universal Sentence Encoder (USE) model as an example. We explored the theoretical framework, data preparation, baseline model evaluation, and the actual fine-tuning process. The results demonstrated the effectiveness of fine-tuning in strengthening similarity scores within a domain.\nBy following this approach and adapting it to your specific domain, you can unlock the full potential of pre-trained NLP models and achieve better results in your natural language processing tasks.\nThanks for reading.  _If you have any feedback, please feel free to reach out by messaging me on_[ _LinkedIn_](https://www.linkedin.com/in/shashankkapadia/) _or shooting me an email (smhkapadia[at]gmail.com)_.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\nSK\nWritten By\n## [Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[See all from Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[NLP](https://towardsdatascience.com/tag/nlp/)[Transfer Learning](https://towardsdatascience.com/tag/transfer-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F&title=Domain%20Adaptation%3A%20Fine-Tune%20Pre-Trained%20NLP%20Models)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F&title=Domain%20Adaptation%3A%20Fine-Tune%20Pre-Trained%20NLP%20Models)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F&text=Domain%20Adaptation%3A%20Fine-Tune%20Pre-Trained%20NLP%20Models)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/002.png)](https://towardsdatascience.com/tutorial-on-surface-crack-classification-with-visual-explanation-part-1-14542d2ea7ac/)\n## [Tutorial on Surface Crack Classification with Visual Explanation (Part 1)](https://towardsdatascience.com/tutorial-on-surface-crack-classification-with-visual-explanation-part-1-14542d2ea7ac/)\n[](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/)\nA step-by-step guide to develop explainable AI to classify surface crack images with Pytorch. This is part 1 of 2 part series.\n[Muhammad Monjurul Karim](https://towardsdatascience.com/author/raju.monjurulkarim/)\nOctober 7, 202110 min read\n  * [![](../images/003.jpg)](https://towardsdatascience.com/analysis-of-the-emotion-data-a-dataset-for-emotion-recognition-tasks-6b8c9a5dfe57/)\n## [Analysis of the emotion data - a dataset for emotion recognition tasks.](https://towardsdatascience.com/analysis-of-the-emotion-data-a-dataset-for-emotion-recognition-tasks-6b8c9a5dfe57/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA dataset containing tweets exhibiting six different emotions.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nSeptember 16, 20216 min read\n  * [![](../images/004.jpeg)](https://towardsdatascience.com/how-to-stand-out-as-a-data-analyst-focus-on-these-5-key-themes-f50edd644ed3/)\n## [How to Stand Out as a Data Analyst: Focus on These 5 Key Themes](https://towardsdatascience.com/how-to-stand-out-as-a-data-analyst-focus-on-these-5-key-themes-f50edd644ed3/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nSQL, Python, and other technical skills are critical, but they are only half the battle\n[Abhi Sawhney](https://towardsdatascience.com/author/asawhney27/)\nApril 20, 20239 min read\n  * [![](../images/005.jpg)](https://towardsdatascience.com/3-ways-to-help-cmos-increase-consumer-engagement-and-drive-marketing-performance-875f412b3dfd/)\n## [3 Ways to Help CMOs Increase Consumer Engagement and Drive Marketing Performance](https://towardsdatascience.com/3-ways-to-help-cmos-increase-consumer-engagement-and-drive-marketing-performance-875f412b3dfd/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA Data Lens, personalized\n[Martin Leitner](https://towardsdatascience.com/author/martinleitner_33020/)\nJanuary 25, 20238 min read\n  * [![](../images/006.jpeg)](https://towardsdatascience.com/beginners-guide-to-reinforcement-learning-f296e8dd8260/)\n## [Mastering the Art of Reinforcement Learning: From Theory to Practice](https://towardsdatascience.com/beginners-guide-to-reinforcement-learning-f296e8dd8260/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nExploring the World of Intelligent Agents, Rewards, and Optimal Decision Making\n[Niklas Lang](https://towardsdatascience.com/author/niklas_lang/)\nJanuary 26, 20226 min read\n  * [![](../images/007.jpeg)](https://towardsdatascience.com/the-three-roles-in-a-machine-learning-team-and-two-technologies-to-connect-them-9660dccf5b57/)\n## [The Three Roles in a Machine Learning Team (and Two Technologies to Connect Them)](https://towardsdatascience.com/the-three-roles-in-a-machine-learning-team-and-two-technologies-to-connect-them-9660dccf5b57/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHenrik Skogstrom / May 04, 2021\n[Henrik Skogström](https://towardsdatascience.com/author/henrikskogstrom/)\nMay 5, 20215 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1/)\n## [5 Minute Paper Explanations: Food AI Part I](https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIntuitive deep dive of the im2recipe paper \"Learning Cross-modal Embeddings for Cooking Recipes and Food Images\"\n[Kunj Mehta](https://towardsdatascience.com/author/kunjmehta10/)\nAugust 8, 20226 min read\n  * [![](../images/009.png)](https://towardsdatascience.com/challenge-can-i-do-linear-regression-without-sklearn-3151d8fc8aa/)\n## [Linear regression: Comparing pythons sklearn with 'writing it from scratch'](https://towardsdatascience.com/challenge-can-i-do-linear-regression-without-sklearn-3151d8fc8aa/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nEver wanted to know what happens under the hood in multivariate linear regression/gradient descent in python's sklearn? You will be...\n[Shaun Enslin](https://towardsdatascience.com/author/shaun-enslin/)\nAugust 10, 20218 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/big-data-the-art-science-that-is-revolutionizing-the-world-a2a596122c55/)\n## [Big Data: The Art & Science That is Revolutionizing the World](https://towardsdatascience.com/big-data-the-art-science-that-is-revolutionizing-the-world-a2a596122c55/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nDive Deep Into the Technology that Will Improve Drastically Every Aspect of Our Lives\n[Victor Roman](https://towardsdatascience.com/author/rromanss23/)\nJune 5, 20194 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "Domain Adaptation: Fine-Tune Pre-Trained NLP Models | Towards Data Science",
    "description": "A step-by-step guide to fine-tuning pre-trained NLP models for any domain",
    "keywords": null,
    "author": "Shashank Kapadia",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Domain Adaptation: Fine-Tune Pre-Trained NLP Models",
    "og:description": "A step-by-step guide to fine-tuning pre-trained NLP models for any domain",
    "og:url": "https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation.jpg",
    "og:image:width": "1400",
    "og:image:height": "933",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Shashank Kapadia",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "8 min read",
    "article:published_time": "2023-07-04T17:06:10.000Z",
    "article:modified_time": "2023-07-04T17:06:10.000Z",
    "article:author": "https://towardsdatascience.com/author/shashank kapadia/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/73787309c4c1/code/block_000.txt",
      "chars": 138
    },
    {
      "language": "txt",
      "file": "attachments/73787309c4c1/code/block_001.txt",
      "chars": 1218
    },
    {
      "language": "txt",
      "file": "attachments/73787309c4c1/code/block_002.txt",
      "chars": 1593
    },
    {
      "language": "txt",
      "file": "attachments/73787309c4c1/code/block_003.txt",
      "chars": 853
    },
    {
      "language": "txt",
      "file": "attachments/73787309c4c1/code/block_004.txt",
      "chars": 562
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:10:14Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:10:14Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:10:14Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:10:14Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/shashank kapadia/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/contrastive-loss-explaned-159f2d4a87ec?source=post_page-----a06659ca6668---------------------------------------"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/nlp/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/transfer-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tutorial-on-surface-crack-classification-with-visual-explanation-part-1-14542d2ea7ac/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/raju.monjurulkarim/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/analysis-of-the-emotion-data-a-dataset-for-emotion-recognition-tasks-6b8c9a5dfe57/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/pandeyparul/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-stand-out-as-a-data-analyst-focus-on-these-5-key-themes-f50edd644ed3/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://medium.com/u/f6bf67256839?source=post_page---user_mention--a06659ca6668---------------------------------------"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
    },
    {
      "type": "external",
      "href": "https://www.projectpro.io/article/siamese-neural-networks/718?source=post_page-----a06659ca6668---------------------------------------"
    },
    {
      "type": "external",
      "href": "https://bdtechtalks.com/2020/08/12/what-is-one-shot-learning/?source=post_page-----a06659ca6668---------------------------------------"
    },
    {
      "type": "external",
      "href": "https://github.com/kapadias/medium-articles/blob/master/natural-language-processing/embedding-models/domain_adaption_fine_tune_nlp_model.ipynb"
    },
    {
      "type": "external",
      "href": "https://esco.ec.europa.eu/en"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/shashankkapadia/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Domain+Adaptation%3A+Fine-Tune+Pre-Trained+NLP+Models&u=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Domain+Adaptation%3A+Fine-Tune+Pre-Trained+NLP+Models&url=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Domain+Adaptation%3A+Fine-Tune+Pre-Trained+NLP+Models&url=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:34:01Z",
  "source_url": "https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# Domain Adaptation: Fine-Tune Pre-Trained NLP Models\nA step-by-step guide to fine-tuning pre-trained NLP models for any domain\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nJuly 4, 20238 min read\n![Green and red dots and lines in a mesh pattern](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation.jpg)\nPhoto by Pietro Jeng on Unsplash \n_Preface: This article presents a summary of information about the given topic. It should not be considered original research. The information and code included in this article may be influenced by things I have read or seen in the past from various online articles, research papers, books, and open-source code._\n_Co-Author:_[_Billy Hines_](https://medium.com/u/f6bf67256839?source=post_page---user_mention--a06659ca6668---------------------------------------)\n## Table of contents\n  * [Introduction](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Introduction)\n  * [Theoretical framework](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Theoretical-framework)\n  * [Data overview](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Data-overview)\n  * [Starting point: The baseline model](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Starting-point)\n  * [Fine-tuning the model](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Fine-tuning)\n  * [Evaluating the results](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Evaluation)\n  * [Closing thoughts](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/#Closing-thoughts)\n\n\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## Introduction\nIn today’s world, the availability of pre-trained NLP models has greatly simplified the interpretation of textual data using deep learning techniques. However, while these models excel in general tasks, they often lack adaptability to specific domains. This comprehensive guide aims to walk you through the process of fine-tuning pre-trained NLP models to achieve improved performance in a particular domain.\n### Motivation\nAlthough pre-trained NLP models like BERT and the Universal Sentence Encoder (USE) are effective in capturing linguistic intricacies, their performance in domain-specific applications can be limited due to the diverse range of datasets they are trained on. This limitation becomes evident when analyzing relationships within a specific domain.\nFor example, when working with employment data, we expect the model to recognize the closer proximity between the roles of ‘Data Scientist’ and ‘Machine Learning Engineer’, or the stronger association between ‘Python’ and ‘TensorFlow’. Unfortunately, general-purpose models often miss these nuanced relationships.\nThe table below demonstrates the discrepancies in the similarity obtained from a base multilingual USE model:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation-1.png)\nFig 1. Similarity score between two text vectors from base [MultiLingual Universal Sentence Encoder Model](https://tfhub.dev/google/universal-sentence-encoder-multilingual/3)\nTo address this issue, we can fine-tune pre-trained models with high-quality, domain-specific datasets. This adaptation process significantly enhances the model’s performance and precision, fully unlocking the potential of the NLP model.\n> When dealing with large pre-trained NLP models, it is advisable to initially deploy the base model and consider fine-tuning only if its performance falls short for the specific problem at hand.\nThis tutorial focuses on fine-tuning the Universal Sentence Encoder (USE) model using easily accessible open-source data.\n## Theoretical overview\nFine-tuning an ML model can be achieved through various strategies, such as supervised learning and reinforcement learning. In this tutorial, we will concentrate on a one(few)-shot learning approach combined with a Siamese architecture for the fine-tuning process.\n### Methodology\nIn this tutorial, we utilize a Siamese neural network, which is a specific type of Artificial Neural Network. This network leverages shared weights while simultaneously processing two distinct input vectors to compute comparable output vectors. Inspired by one-shot learning, this approach has proven to be particularly effective in capturing semantic similarity, although it may require longer training times and lack probabilistic output.\nA Siamese neural network creates an ‘embedding space’ where related concepts are positioned closely, enabling the model to better discern semantic relations.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation-2.png)\nFig 2. Siamese architecture to fine-tune pre-trained NLP model\n  * **Twin branches and shared weights** : The architecture consists of two identical branches, each containing an embedding layer with shared weights. These dual branches handle two inputs simultaneously, either similar or dissimilar.\n  * **Similarity and transformation** : The inputs are transformed into vector embeddings using the pre-trained NLP model. The architecture then calculates the similarity between the vectors. The similarity score, ranging between -1 and 1, quantifies the angular distance between the two vectors, serving as a metric for their semantic similarity.\n  * **Contrastive loss and learning** : The model’s learning is guided by the “Contrastive Loss,” which is the difference between the expected output (similarity score from the training data) and the computed similarity. This loss guides the adjustment of the model’s weights to minimize the loss and enhance the quality of the learned embeddings.\n\n\nTo learn more about one(few)-shot learning, siamese architecture, and contrastive loss, refer to the following resources:\n  * [A Gentle Introduction to Siamese Neural Networks Architecture](https://www.projectpro.io/article/siamese-neural-networks/718?source=post_page-----a06659ca6668---------------------------------------)\n  * [What is one-shot learning?](https://bdtechtalks.com/2020/08/12/what-is-one-shot-learning/?source=post_page-----a06659ca6668---------------------------------------)\n  * [Contrastive Loss Explained](https://towardsdatascience.com/contrastive-loss-explaned-159f2d4a87ec?source=post_page-----a06659ca6668---------------------------------------)\n\n\nThe complete code is available as a [Jupyter Notebook on GitHub](https://github.com/kapadias/medium-articles/blob/master/natural-language-processing/embedding-models/domain_adaption_fine_tune_nlp_model.ipynb).\n## Data overview\nFor the fine-tuning of pre-trained NLP models using this method, the training data should consist of pairs of text strings accompanied by similarity scores between them.\nThe training data follows the format shown below:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation-3.png)\nFig 3. Sample Format for Training Data\nIn this tutorial, we use a dataset sourced from the [ESCO classification dataset](https://esco.ec.europa.eu/en), which has been transformed to generate similarity scores based on the relationships between different data elements.\n> Preparing the training data is a crucial step in the fine-tuning process. It is assumed that you have access to the required data and a method to transform it into the specified format. Since the focus of this article is to demonstrate the fine-tuning process, we will omit the details of how the data was generated using the ESCO dataset.\n> The ESCO dataset is available for developers to freely utilize as a foundation for various applications that offer services like autocomplete, suggestion systems, job search algorithms, and job matching algorithms. The dataset used in this tutorial has been transformed and provided as a sample, allowing unrestricted usage for any purpose.\nLet’s start by examining the training data:\npython\n\n```\nimport pandas as pd\n\n# Read the CSV file into a pandas DataFrame\ndata = pd.read_csv(\"./data/training_data.csv\")\n\n# Print head\ndata.head()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation-4.png)\nFig 4. Sample data used for fine-tuning the model\n## Starting point: The baseline model\nTo begin, we establish the [multilingual universal sentence encoder](https://tfhub.dev/google/universal-sentence-encoder-multilingual/3) as our baseline model. It is essential to set this baseline before proceeding with the fine-tuning process.\nFor this tutorial, we will use the STS benchmark and a sample similarity visualization as metrics to evaluate the changes and improvements achieved through the fine-tuning process.\n> The STS Benchmark dataset consists of English sentence pairs, each associated with a similarity score. During the model training process, we evaluate the model’s performance on this benchmark set. The persisted scores for each training run are the Pearson correlation between the predicted similarity scores and the actual similarity scores in the dataset.\n> These scores ensure that as the model is fine-tuned with our context-specific training data, it maintains some level of generalizability.\npython\n\n```\n# Loads the Universal Sentence Encoder Multilingual module from TensorFlow Hub.\nbase_model_url = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\nbase_model = tf.keras.Sequential([\n    hub.KerasLayer(base_model_url,\n                   input_shape=[],\n                   dtype=tf.string,\n                   trainable=False)\n])\n\n# Defines a list of test sentences. These sentences represent various job titles.\ntest_text = ['Data Scientist', 'Data Analyst', 'Data Engineer',\n             'Nurse Practitioner', 'Registered Nurse', 'Medical Assistant',\n             'Social Media Manager', 'Marketing Strategist', 'Product Marketing Manager']\n\n# Creates embeddings for the sentences in the test_text list. \n# The np.array() function is used to convert the result into a numpy array.\n# The .tolist() function is used to convert the numpy array into a list, which might be easier to work with.\nvectors = np.array(base_model.predict(test_text)).tolist()\n\n# Calls the plot_similarity function to create a similarity plot.\nplot_similarity(test_text, vectors, 90, \"base model\")\n\n# Computes STS benchmark score for the base model\npearsonr = sts_benchmark(base_model)\nprint(\"STS Benachmark: \" + str(pearsonr))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation-5.png)\nFig 5. Similarity visualizations across test words\n> STS Benchmark (dev): 0.8325\n## Fine-tuning the model\nThe next step involves constructing the siamese model architecture using the baseline model and fine-tuning it with our domain-specific data.\npython\n\n```\n# Load the pre-trained word embedding model\nembedding_layer = hub.load(base_model_url)\n\n# Create a Keras layer from the loaded embedding model\nshared_embedding_layer = hub.KerasLayer(embedding_layer, trainable=True)\n\n# Define the inputs to the model\nleft_input = keras.Input(shape=(), dtype=tf.string)\nright_input = keras.Input(shape=(), dtype=tf.string)\n\n# Pass the inputs through the shared embedding layer\nembedding_left_output = shared_embedding_layer(left_input)\nembedding_right_output = shared_embedding_layer(right_input)\n\n# Compute the cosine similarity between the embedding vectors\ncosine_similarity = tf.keras.layers.Dot(axes=-1, normalize=True)(\n    [embedding_left_output, embedding_right_output]\n)\n\n# Convert the cosine similarity to angular distance\npi = tf.constant(math.pi, dtype=tf.float32)\nclip_cosine_similarities = tf.clip_by_value(\n    cosine_similarity, -0.99999, 0.99999\n)\nacos_distance = 1.0 - (tf.acos(clip_cosine_similarities) / pi)\n\n# Package the model\nencoder = tf.keras.Model([left_input, right_input], acos_distance)\n\n# Compile the model\nencoder.compile(\n    optimizer=tf.keras.optimizers.Adam(\n        learning_rate=0.00001,\n        beta_1=0.9,\n        beta_2=0.9999,\n        epsilon=0.0000001,\n        amsgrad=False,\n        clipnorm=1.0,\n        name=\"Adam\",\n    ),\n    loss=tf.keras.losses.MeanSquaredError(\n        reduction=keras.losses.Reduction.AUTO, name=\"mean_squared_error\"\n    ),\n    metrics=[\n        tf.keras.metrics.MeanAbsoluteError(),\n        tf.keras.metrics.MeanAbsolutePercentageError(),\n    ],\n)\n\n# Print the model summary\nencoder.summary()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation-8.png)\nFig 6. Model architecture for fine-tuning\n### Fit the model\npython\n\n```\n# Define early stopping callback\nearly_stop = keras.callbacks.EarlyStopping(\n    monitor=\"loss\", patience=3, min_delta=0.001\n)\n\n# Define TensorBoard callback\nlogdir = os.path.join(\".\", \"logs/fit/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\ntensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)\n\n# Model Input\nleft_inputs, right_inputs, similarity = process_model_input(data)\n\n# Train the encoder model\nhistory = encoder.fit(\n    [left_inputs, right_inputs],\n    similarity,\n    batch_size=8,\n    epochs=20,\n    validation_split=0.2,\n    callbacks=[early_stop, tensorboard_callback],\n)\n\n# Define model input\ninputs = keras.Input(shape=[], dtype=tf.string)\n\n# Pass the input through the embedding layer\nembedding = hub.KerasLayer(embedding_layer)(inputs)\n\n# Create the tuned model\ntuned_model = keras.Model(inputs=inputs, outputs=embedding)\n```\n\n## Evaluation\nNow that we have the fine-tuned model, let’s re-evaluate it and compare the results to those of the base model.\npython\n\n```\n# Creates embeddings for the sentences in the test_text list. \n# The np.array() function is used to convert the result into a numpy array.\n# The .tolist() function is used to convert the numpy array into a list, which might be easier to work with.\nvectors = np.array(tuned_model.predict(test_text)).tolist()\n\n# Calls the plot_similarity function to create a similarity plot.\nplot_similarity(test_text, vectors, 90, \"tuned model\")\n\n# Computes STS benchmark score for the tuned model\npearsonr = sts_benchmark(tuned_model)\nprint(\"STS Benachmark: \" + str(pearsonr))\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation-6.png)\n> STS Benchmark (dev): 0.8349\nBased on fine-tuning the model on the relatively small dataset, the STS benchmark score is comparable to that of the baseline model, indicating that the tuned model still exhibits generalizability. However, the similarity visualization demonstrates strengthened similarity scores between similar titles and a reduction in scores for dissimilar ones.\n## Closing thoughts\nFine-tuning pre-trained NLP models for domain adaptation is a powerful technique to improve their performance and precision in specific contexts. By utilizing quality, domain-specific datasets and leveraging siamese neural networks, we can enhance the model’s ability to capture semantic similarity.\nThis tutorial provided a step-by-step guide to the fine-tuning process, using the Universal Sentence Encoder (USE) model as an example. We explored the theoretical framework, data preparation, baseline model evaluation, and the actual fine-tuning process. The results demonstrated the effectiveness of fine-tuning in strengthening similarity scores within a domain.\nBy following this approach and adapting it to your specific domain, you can unlock the full potential of pre-trained NLP models and achieve better results in your natural language processing tasks.\nThanks for reading.  _If you have any feedback, please feel free to reach out by messaging me on_[ _LinkedIn_](https://www.linkedin.com/in/shashankkapadia/) _or shooting me an email (smhkapadia[at]gmail.com)_.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\nSK\nWritten By\n## [Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[See all from Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[NLP](https://towardsdatascience.com/tag/nlp/)[Transfer Learning](https://towardsdatascience.com/tag/transfer-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F&title=Domain%20Adaptation%3A%20Fine-Tune%20Pre-Trained%20NLP%20Models)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F&title=Domain%20Adaptation%3A%20Fine-Tune%20Pre-Trained%20NLP%20Models)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fdomain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668%2F&text=Domain%20Adaptation%3A%20Fine-Tune%20Pre-Trained%20NLP%20Models)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/10/16uEEdR69fdHlV57UYkez7Q.png)](https://towardsdatascience.com/tutorial-on-surface-crack-classification-with-visual-explanation-part-1-14542d2ea7ac/)\n## [Tutorial on Surface Crack Classification with Visual Explanation (Part 1)](https://towardsdatascience.com/tutorial-on-surface-crack-classification-with-visual-explanation-part-1-14542d2ea7ac/)\n[](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/)\nA step-by-step guide to develop explainable AI to classify surface crack images with Pytorch. This is part 1 of 2 part series.\n[Muhammad Monjurul Karim](https://towardsdatascience.com/author/raju.monjurulkarim/)\nOctober 7, 202110 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/09/0dwu_Yc5WWgY7fK2l-scaled.jpg)](https://towardsdatascience.com/analysis-of-the-emotion-data-a-dataset-for-emotion-recognition-tasks-6b8c9a5dfe57/)\n## [Analysis of the emotion data - a dataset for emotion recognition tasks.](https://towardsdatascience.com/analysis-of-the-emotion-data-a-dataset-for-emotion-recognition-tasks-6b8c9a5dfe57/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA dataset containing tweets exhibiting six different emotions.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nSeptember 16, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/1Z-6PNB5V8h6_86MzYdLc7A-scaled.jpeg)](https://towardsdatascience.com/how-to-stand-out-as-a-data-analyst-focus-on-these-5-key-themes-f50edd644ed3/)\n## [How to Stand Out as a Data Analyst: Focus on These 5 Key Themes](https://towardsdatascience.com/how-to-stand-out-as-a-data-analyst-focus-on-these-5-key-themes-f50edd644ed3/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nSQL, Python, and other technical skills are critical, but they are only half the battle\n[Abhi Sawhney](https://towardsdatascience.com/author/asawhney27/)\nApril 20, 20239 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/09mNCCR3ZU9KIoNwO-scaled.jpg)](https://towardsdatascience.com/3-ways-to-help-cmos-increase-consumer-engagement-and-drive-marketing-performance-875f412b3dfd/)\n## [3 Ways to Help CMOs Increase Consumer Engagement and Drive Marketing Performance](https://towardsdatascience.com/3-ways-to-help-cmos-increase-consumer-engagement-and-drive-marketing-performance-875f412b3dfd/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA Data Lens, personalized\n[Martin Leitner](https://towardsdatascience.com/author/martinleitner_33020/)\nJanuary 25, 20238 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/01/1n5Enk3dtKymRGBvI8vzSqQ-scaled.jpeg)](https://towardsdatascience.com/beginners-guide-to-reinforcement-learning-f296e8dd8260/)\n## [Mastering the Art of Reinforcement Learning: From Theory to Practice](https://towardsdatascience.com/beginners-guide-to-reinforcement-learning-f296e8dd8260/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nExploring the World of Intelligent Agents, Rewards, and Optimal Decision Making\n[Niklas Lang](https://towardsdatascience.com/author/niklas_lang/)\nJanuary 26, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/1_ovAr0NcpVJ7ZxiSDXThqg.jpeg)](https://towardsdatascience.com/the-three-roles-in-a-machine-learning-team-and-two-technologies-to-connect-them-9660dccf5b57/)\n## [The Three Roles in a Machine Learning Team (and Two Technologies to Connect Them)](https://towardsdatascience.com/the-three-roles-in-a-machine-learning-team-and-two-technologies-to-connect-them-9660dccf5b57/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHenrik Skogstrom / May 04, 2021\n[Henrik Skogström](https://towardsdatascience.com/author/henrikskogstrom/)\nMay 5, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/08/0ZqrtA7Ab65WRZnbq-scaled.jpg)](https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1/)\n## [5 Minute Paper Explanations: Food AI Part I](https://towardsdatascience.com/5-minute-paper-explanations-food-ai-part-i-9276b61873c1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIntuitive deep dive of the im2recipe paper \"Learning Cross-modal Embeddings for Cooking Recipes and Food Images\"\n[Kunj Mehta](https://towardsdatascience.com/author/kunjmehta10/)\nAugust 8, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1A_vuKQQp8YT4XV6EQVojSQ.png)](https://towardsdatascience.com/challenge-can-i-do-linear-regression-without-sklearn-3151d8fc8aa/)\n## [Linear regression: Comparing pythons sklearn with 'writing it from scratch'](https://towardsdatascience.com/challenge-can-i-do-linear-regression-without-sklearn-3151d8fc8aa/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nEver wanted to know what happens under the hood in multivariate linear regression/gradient descent in python's sklearn? You will be...\n[Shaun Enslin](https://towardsdatascience.com/author/shaun-enslin/)\nAugust 10, 20218 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/06/05fmsHwD4tncy11XQ.jpg)](https://towardsdatascience.com/big-data-the-art-science-that-is-revolutionizing-the-world-a2a596122c55/)\n## [Big Data: The Art & Science That is Revolutionizing the World](https://towardsdatascience.com/big-data-the-art-science-that-is-revolutionizing-the-world-a2a596122c55/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nDive Deep Into the Technology that Will Improve Drastically Every Aspect of Our Lives\n[Victor Roman](https://towardsdatascience.com/author/rromanss23/)\nJune 5, 20194 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/73787309c4c1/pages/",
  "body_markdown_path": "attachments/73787309c4c1/pages/archived-body.md",
  "local_html": "attachments/73787309c4c1/pages/archived-body.html",
  "body_source": "prior_capture"
}