{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Petr Koráb",
  "title_listed": "How to Fine-Tune an SLM for Emotion Recognition",
  "keywords": "",
  "domain": "文本处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/how-to-fine-tune-an-slm-for-emotion-recognition/",
  "publish_date": "2026-06-05",
  "corpus_stage": "",
  "notes": "",
  "id": "550b9f25e3e8",
  "collected_at": "2026-10-02T03:30:43",
  "title": "How to Fine-Tune an SLM for Emotion Recognition | 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# How to Fine-Tune an SLM for Emotion Recognition\nPython tutorial for fine-tuning a Mistral Small 3.1 on an imbalanced training set to classify 15 emotions in social media communication\n[Petr Koráb](https://towardsdatascience.com/author/petrkorab/)\nJune 5, 20269 min read\n![](../images/000.png)\nImage created by GPT 5.3\n## Introduction\nRecent small language models (SLMs) fine-tuned for [sentiment classification](https://huggingface.co/models?pipeline_tag=text-generation&num_parameters=min:6B&sort=trending&search=sentiment+llama) infer sentiment as a single score, capturing the overall emotional tone of the text. For many use cases, the positive-negative classification does not tell the full story a company needs. Emotion recognition models go further, decomposing sentiment into emotion classes (_“anger”, “approval”, “disappointment”_ , etc.) and assigning probabilities to a set of emotions in the text. It is then possible to model emotional content in datasets that a company receives (customer tickets, emails, brand-related discussions), and react swiftly to changing conditions.\nFor one of our recent projects, modeling emotions in online media, we required an emotion recognition model with open weights and a flexible license, maintaining high transparency standards, and, of course, benefiting from the lower costs associated with open models. We subjectively prefer European models, but Hugging Face did not offer a [Mistral alternative with](https://huggingface.co/models?sort=trending&search=emotion+mistral) a developed model card. One possible reason is that the most detailed training set for emotion recognition, the 28-emotion [GoEmotions datase](https://research.google/blog/goemotions-a-dataset-for-fine-grained-emotion-classification/)t, is highly [class-imbalanced](https://latitude.so/blog/fine-tuning-llms-on-imbalanced-data-best-practices). Fine-tuning an SLM on a high-class-imbalance data set that performs decently on the test requires a deeper focus.\nWe treated the class-imbalance problem by a combination of three techniques: (1) **undersampling** the most represented emotional category, (2) **synthetically expanding** the **minority classes** with [Nature’s 2025 ISMOTE](https://www.nature.com/articles/s41598-025-09506-w) algorithm, and (3) **weighting** the **loss function.** With this combination of techniques, [_MistralSmall-3.1.GoEmotions_](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions), now released on Hugging Face, infers most target emotions relevant to our project with F1 > 0.7.\nThis article explains in detail how to fine-tune an open-weight SLM. We’ll also figure out: \n  * _How to preprocess class-imbalanced data for LLM fine-tuning with the_[ _2025 ISMOTE_](https://www.nature.com/articles/s41598-025-09506-w) _algorithm._\n  * _How to decompose sentiment into emotion categories by finetuning a Small Language Model for emotion recognition in text data._\n\n\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## 2. Data\n[GoEmotions](https://github.com/google-research/google-research/tree/master/goemotions) is a human-annotated dataset of 58k Reddit comments extracted from English-language subreddits and labeled with [27 emotion categories](https://github.com/google-research/google-research/blob/master/goemotions/data/emotions.txt) and a _“neutral”_ label. It is a **multi-label classification dataset** in which each comment may be labeled with multiple TRUEs for emotions (e.g., _“Hitting me. That just added another funny dynamic to it even though I wasn’t actually trying to hit her”_ is True for _“amusement”_ , and _“annoyance”_).\nThe dataset was released on [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/goemotions) under the Apache 2.0 License and contains 54,263 labeled texts. Here is what it looks like:\n![](../images/001.png)\nImage 1. GoEmotions dataset. Image by author.\nAfter a quick check, we can see a high-class imbalance in the data where the _neutral_ category prevails:\n![](../images/002.png)\nImage 2. Class imbalance in GoEmotions dataset. Image by author.\n## 3. Training set preprocessing\n> __Our goal is to develop a classifier to identify 15 emotions in general-language texts. Training on class-imbalanced data can introduce bias, as the fine-tuned model tends to favor the majority class and perform worse on the minority ones, so preprocessing is essential.__\nWe used a combination of methods for the **training set;** the validation and test sets remained unchanged to address class imbalance and maximize performance on the target emotions (_fear, sadness, disgust, disapproval, annoyance, anger, disappointment, optimism, amusement, surprise, admiration, excitement, confusion, joy, love_): \n  * We thinned the data by randomly filtering the _“neutral”_ rows.\n  * We generated synthetic samples for the least-represented emotional categories using _ISMOTE (Improved Synthetic Minority Over-sampling Technique)_.\n\n\nThe _ISMOTE_ algorithm extends the common SMOTE technique by (1) expanding the sample generation space and (2) improving sampling distribution. The synthetically generated samples then have more realistic data distributions than those produced by the original method.\n![](../images/body-d8e9b0b2c266c14a4706.png)\nImage 3. The flowchart of the ISMOTE algorithm. Source: [Scientific Reports.](https://www.nature.com/articles/s41598-025-09506-w/figures/3)\nBy reducing the majority class and synthetically expanding the minority categories to 4000 samples, we constructed a relatively balanced set for fine-tuning. The code for ISMOTE oversampling is [here.](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions/tree/main)\n![](../images/body-d96d37abaf82578949da.png)\nImage 4. Label relative frequency , train (augmented), validation, and test sets. Image by author.\n## 4. SLM Fine-tuning\nAmong Mistral’s models, we chose the _Small_ class ([Small-3.1-24B-Instruct-2503](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)), which fits our GPU and provides the multilingual capabilities we need for the classifier. The [Unsloth](https://unsloth.ai/docs) framework makes the finetuning steps uncomplicated and faster than with [Transformers](https://pypi.org/project/transformers/):\n_**1. Data loading**_  _—_ _loading preprocessed training set, validation, and test sets._ We use a 60:20:20 split.\n_**2. Loading**_ _the_ _**base model**_ _— loading the Small-3.1–24B-Instruct-2503 locally._\n_**3.**__Apply_ _**LoRA**_ _—_[ _lowering hardware requirements_](https://www.ibm.com/think/topics/lora) _._\n_**4. Multilabel wrapper with focal loss function**_ _— updates the trainer for multilabel classification. Also adds focal loss to weight the loss function for a selected set of emotions, prioritizing their performance._\n_**5. Evaluation metrics**_ _and_ _**training args**_ _— specifying the evaluation metrics and hyperparameters for model training._\n_**6.**__Model_ _**training**_ _— trainer formulation and launch._\n_**7. Evaluation**_ _— evaluating the best model performance on the test set._\n## 4.1. Coding \nHere is the code implementation.\n### 4.1.1. Data loading\npython\n\n```\n# Loading augmented train, validation and test sets\nBASE = r\"augmented\"\n\ndef load_split(path: str) -> Dataset:\n    with open(path, encoding=\"utf-8\") as f:\n        d = json.load(f)\n    return Dataset.from_dict({\"input_embeds\": d[\"X\"], \"labels\": d[\"y\"]})\n\ntrain_dataset = load_split(f\"{BASE}/train.json\")\nval_dataset   = load_split(f\"{BASE}/val.json\")\ntest_dataset  = load_split(f\"{BASE}/test.json\")\n\n# Formulate embedding dimension\nEMBED_DIM = len(train_dataset[0][\"input_embeds\"])\n\n# Return Pytorch tensors\ntrain_dataset.set_format(\"torch\")\nval_dataset.set_format(\"torch\")\ntest_dataset.set_format(\"torch\")\n```\n\n### 4.1.2. Loading the base model \npython\n\n```\n# Load base model with Unsloth FastLanguageModel\nMODEL_NAME = \"unsloth/Mistral-Small-3.1-24B-Instruct-2503\"\n\nbase_model, _ = FastLanguageModel.from_pretrained(\n    model_name=MODEL_NAME,\n    max_seq_length=2,\n    load_in_4bit=True,\n    dtype=torch.bfloat16,\n)\n```\n\n### 4.1.3. Apply LoRA\npython\n\n```\n# Aply Low-rank adaptation (LoRA) \nbase_model = FastLanguageModel.get_peft_model(\n    base_model,\n    r=16,\n    lora_alpha=32,\n    lora_dropout=0,\n    bias=\"none\",\n    target_modules=[\n        \"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n        \"gate_proj\", \"up_proj\", \"down_proj\",\n    ],\n    use_gradient_checkpointing=\"unsloth\",\n    random_state = 3407,\n    use_rslora = False, \n)\n```\n\n### 4.1.4. Multilabel wrapper with focal loss function\npython\n\n```\n# Focal loss weights for preffered labels  \nFOCAL_ALPHA_DEFAULT   = 0.25\nFOCAL_ALPHA_PREFERRED = 0.75\n\nPREFERRED_LABELS = {\n    \"fear\", \"sadness\", \"disgust\", \"disapproval\", \"annoyance\",\n    \"anger\", \"disappointment\", \"optimism\", \"amusement\", \"surprise\",\n    \"admiration\", \"excitement\", \"confusion\",\"joy\",\"love\"\n}\n\nFOCAL_ALPHA_PER_LABEL: list[float] = [\n    FOCAL_ALPHA_PREFERRED if lbl in PREFERRED_LABELS else FOCAL_ALPHA_DEFAULT\n    for lbl in EMOTION_LABELS\n]\n\n\"Per-label weighted focal binary cross-entropy for multi-label problems\"\nclass FocalLossWithAlpha(nn.Module):\n        def __init__(self, alpha: list[float], gamma: float = 2.0):\n        super().__init__()\n        self.register_buffer(\"alpha\", torch.tensor(alpha, dtype=torch.float32))\n        self.gamma = gamma\n    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:\n        probs   = torch.sigmoid(logits)\n        p_t     = probs * targets + (1.0 - probs) * (1.0 - targets)\n        alpha_t = self.alpha * targets + (1.0 - self.alpha) * (1.0 - targets)\n        focal_w = alpha_t * (1.0 - p_t) ** self.gamma\n        bce     = nn.functional.binary_cross_entropy_with_logits(\n            logits, targets, reduction=\"none\"\n        )\n        return (focal_w * bce).mean()\n\n```\n\npython\n\n```\n# Multilabel classification wrapper with focal loss class weighting\nclass MistralForMultiLabel(nn.Module):\n    is_loaded_in_4bit = True\n\n    def __init__(self, backbone: nn.Module, num_labels: int,\n                 hidden_size: int, embed_dim: int):\n        super().__init__()\n        self.backbone = backbone\n        _device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        self.projection = nn.Sequential(\n            nn.Linear(embed_dim, hidden_size // 2),\n            nn.GELU(),\n            nn.Linear(hidden_size // 2, hidden_size),\n        ).to(_device)\n        self.dropout    = nn.Dropout(0.1).to(_device)\n        self.classifier = nn.Linear(hidden_size, num_labels).to(_device)\n        self.focal_loss = FocalLossWithAlpha(FOCAL_ALPHA_PER_LABEL).to(_device)\n\n    def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):\n        self.backbone.gradient_checkpointing_enable(gradient_checkpointing_kwargs)\n\n    def gradient_checkpointing_disable(self):\n        self.backbone.gradient_checkpointing_disable()\n\n    def forward(\n        self,\n        input_embeds: torch.Tensor,\n        labels: torch.Tensor | None = None,\n        **kwargs,\n    ):\n        B = input_embeds.size(0)\n        projected = self.projection(input_embeds).unsqueeze(1)\n        attn_mask = torch.ones(B, 1, device=input_embeds.device)\n\n        outputs = self.backbone.base_model.model.model(\n            inputs_embeds=projected,\n            attention_mask=attn_mask,\n            output_hidden_states=True,\n        )\n        pooled = outputs.hidden_states[-1][:, 0, :]\n        logits = self.classifier(self.dropout(pooled))\n\n        loss = self.focal_loss(logits, labels.float()) if labels is not None else None\n        return {\"loss\": loss, \"logits\": logits}\n```\n\n### 4.1.5. Evaluation metrics and training args\npython\n\n```\n# Specifiy the evaluation function\ndef compute_metrics(eval_pred):\n    logits, labels = eval_pred\n    probs = torch.sigmoid(torch.tensor(logits)).numpy()\n    preds = (probs >= 0.5).astype(int)\n    labels = labels.astype(int)\n\n    from sklearn.metrics import accuracy_score\n\n    exact_accuracy  = accuracy_score(labels, preds)\n    macro_f1        = f1_score(labels, preds, average=\"macro\", zero_division=0)\n    micro_f1        = f1_score(labels, preds, average=\"micro\", zero_division=0)\n    macro_precision = precision_score(labels, preds, average=\"macro\", zero_division=0)\n    macro_recall    = recall_score(labels, preds, average=\"macro\", zero_division=0)\n\n    per_class_f1        = f1_score(labels, preds, average=None, zero_division=0)\n    per_class_recall    = recall_score(labels, preds, average=None, zero_division=0)\n    per_class_precision = precision_score(labels, preds, average=None, zero_division=0)\n    per_class_accuracy  = (preds == labels).mean(axis=0)\n\n    per_class_metrics = {}\n    for i, emotion in enumerate(EMOTION_LABELS):\n        per_class_metrics[f\"f1_{emotion}\"]        = float(per_class_f1[i])\n        per_class_metrics[f\"recall_{emotion}\"]    = float(per_class_recall[i])\n        per_class_metrics[f\"precision_{emotion}\"] = float(per_class_precision[i])\n        per_class_metrics[f\"accuracy_{emotion}\"]  = float(per_class_accuracy[i])\n\n    return {\n        \"exact_accuracy\":   exact_accuracy,\n        \"macro_f1\":         macro_f1,\n        \"micro_f1\":         micro_f1,\n        \"macro_precision\":  macro_precision,\n        \"macro_recall\":     macro_recall,\n        **per_class_metrics,\n    }\n```\n\npython\n\n```\n# Specify hyperparameters\ntraining_args = TrainingArguments(\n    output_dir=OUTPUT_DIR,            # where checkpoints and logs are written\n    eval_strategy=\"epoch\",            # run evaluation once per epoch\n    save_strategy=\"epoch\",            # save checkpoint once per epoch\n    per_device_train_batch_size=8,    # samples per GPU per step\n    per_device_eval_batch_size=16,    # larger batch is fine — no gradients\n    gradient_accumulation_steps=4,    # effective batch = 8 × 4 = 32\n    num_train_epochs=15,              # total passes over the training data\n    learning_rate=1e-4,               # peak LR after warmup\n    bf16=True,                        # bfloat16 mixed precision\n    optim=\"adamw_8bit\",               # 8-bit AdamW\n    warmup_ratio=0.05,                # first 5 % of steps ramp LR from 0 to peak\n    lr_scheduler_type=\"cosine\",       # cosine decay from peak LR to ~0\n    logging_steps=25,                 # print loss/LR to console every 25 steps\n    logging_first_step=True,          # also log step 1 to catch early instability\n    load_best_model_at_end=True,      # restore best checkpoint after training ends\n    metric_for_best_model=\"macro_f1\", # criterion used to select the best checkpoint\n    greater_is_better=True,           # higher macro_f1 is better in evaluation\n    gradient_checkpointing=False,    \n    remove_unused_columns=False,      # keep input_embeds column\n    save_total_limit=15,              # keep all checkpoints on disk to load the best model\n    weight_decay=0.01,                # L2 regularisation on all trainable parameters\n)\n```\n\n### 4.1.6. Model training\npython\n\n```\n# Set-up the trainer for multilabel finetuning\nclass MultiLabelTrainer(Trainer):\n    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):\n        labels = inputs.pop(\"labels\")\n        outputs = model(**inputs, labels=labels)\n        loss = outputs[\"loss\"]\n        return (loss, outputs) if return_outputs else loss\n\n    def _save_checkpoint(self, model, trial, metrics=None):\n        super()._save_checkpoint(model, trial)\n        ckpt_dir = self._get_output_dir(trial)\n        # Save head\n        torch.save({\n            \"projection\": model.projection.state_dict(),\n            \"classifier\":  model.classifier.state_dict(),\n        }, os.path.join(ckpt_dir, \"head_weights.pt\"))\n        # Save LoRA adapter explicitly (bypasses bitsandbytes serialization issues)\n        model.backbone.save_pretrained(os.path.join(ckpt_dir, \"lora_adapter\"))\n\n    def _load_best_model(self):\n        best_ckpt = self.state.best_model_checkpoint\n        if not best_ckpt:\n            return\n        # Restore head\n        head_path = os.path.join(best_ckpt, \"head_weights.pt\")\n        if os.path.exists(head_path):\n            head = torch.load(head_path, map_location=\"cpu\")\n            self.model.projection.load_state_dict(head[\"projection\"])\n            self.model.classifier.load_state_dict(head[\"classifier\"])\n            print(f\"Head restored from: {best_ckpt}\")\n        else:\n            print(f\"WARNING: head_weights.pt not found in {best_ckpt}\")\n        # Restore LoRA adapter\n        lora_path = os.path.join(best_ckpt, \"lora_adapter\")\n        if os.path.exists(lora_path):\n            from peft import PeftModel\n            self.model.backbone.load_adapter(lora_path, adapter_name=\"default\")\n            print(f\"LoRA restored from: {best_ckpt}\")\n        else:\n            print(f\"WARNING: lora_adapter/ not found in {best_ckpt}\")\n\n# Launch the trainer\ntrainer = MultiLabelTrainer(\n    model=model,\n    args=training_args,\n    train_dataset=train_dataset,\n    eval_dataset=val_dataset,\n    compute_metrics=compute_metrics,\n)\n\n# Launch training\ntrainer.train()\n```\n\nFine-tuning for 15 epochs took 9 hours and 30 minutes on a machine with an NVIDIA RTX 6000 GPU and 192 GB of VRAM, with the best model loaded at the end.\n### 4.1.7. Model evaluation\nLet's show the performance on the test dataset. The standard statistics for model evaluation per class are **F1** , **Precision** , and **Recall**. We can see relatively good performance on the target emotions, with F1 scores over 0.7, for most categories. Full performance is on the [model card](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions).  \n| **Emotion**  | **Precision**  | **Recall**  | **F1**  | **N**  |  \n| --- | --- | --- | --- | --- |  \n| admiration  | 0.7415  | 0.6354  | 0.6844  | 993  |  \n| amusement  | 0.7810  | 0.7422  | 0.7611  | 543  |  \n| anger  | 0.7423  | 0.7367  | 0.7395  | 395  |  \n| annoyance  | 0.7049  | 0.5452  | 0.6148  | 609  |  \n| confusion  | 0.7576  | 0.8251  | 0.7899  | 303  |  \n| disappointment  | 0.8487  | 0.8459  | 0.8473  | 305  |  \n| disapproval  | 0.7208  | 0.5841  | 0.6453  | 517  |  \n| disgust  | 0.8396  | 0.9368  | 0.8856  | 190  |  \n| excitement  | 0.8240  | 0.9366  | 0.8767  | 205  |  \n| fear  | 0.9112  | 0.9686  | 0.9390  | 159  |  \n| joy  | 0.7577  | 0.8024  | 0.7794  | 339  |  \n| love  | 0.7424  | 0.7903  | 0.7656  | 496  |  \n| optimism  | 0.8145  | 0.7636  | 0.7882  | 368  |  \n| sadness  | 0.8534  | 0.8899  | 0.8713  | 327  |  \n| surprise  | 0.8456  | 0.8555  | 0.8505  | 256  |  \n| **Macro precision**  | **0.8295**  |   |   |   |  \n| **Macro recall**  | **0.8184**  |   |   |   |  \n| **Micro F1**  | **0.7527**  |   |   |   |  \n| **Macro F1**  | **0.8215**  |   |   |   |  \n## 5. Summary\nLet’s now summarize the key points of the article. The requirements and full code are in this [repo](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions).\n  * **Emotion recognition** modeling extends sentiment analysis by decomposing the overall sentiment score into its emotional components.\n  * **MistralSmall-3.1.GoEmotions** is on [_Hugging Face_](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions)[ ](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions)under the Apache 2.0 license. The [repo ](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions)also includes the inference guideline.\n  * **Deployment use cases** are [brand and social monitoring](https://www.meegle.com/en_us/topics/affective-computing/emotion-recognition-in-marketing-campaigns), and [email categorization](https://cobbai.com/blog/email-classification-ai-support).\n\n\n_**Petr Koráb**_ _is the founder of Text Mining Stories,_ a Prague-based development & consultancy company. Learn more about the cutting-edge NLP on [our blog.](https://textminingstories.com/blog/)\n_**AI statement**_. Some parts of the code were reviewed by Sonnet 4.6 (Cursor). No text was generated using AI.\n_**Acknowledgements**_ _._ The National Bank of Slovakia Foundation supported this development. I thank Martin Feldkircher, Václav Jež, and Michala Moravcová for comments and suggestions.\n## References\n[1] Ying Li, Yali Yang, Peihua Song, Lian Duan, Rui Ren. 2025. An improved SMOTE algorithm for enhanced imbalanced data classification by expanding sample generation space.[_Scientific Reports, 15_](https://www.nature.com/articles/s41598-025-09506-w)[(](https://www.nature.com/articles/s41598-025-09506-w)[_23521)._](https://www.nature.com/articles/s41598-025-09506-w)\n[2] Yinhan Liu _, Jiatao Gu_ , Naman Goyal, Xian Li, Sergey Edunov  \nMarjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer. 2020. [_Multilingual Denoising Pre-training for Neural Machine Translation_](https://aclanthology.org/2020.tacl-1.47.pdf). Transactions of the Association for Computational Linguistics, 8, pp. 726–742.\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* * *\n![](../images/body-9e78938b5e8b0a70213c.jpeg)\nWritten By\n## [Petr Koráb](https://towardsdatascience.com/author/petrkorab/)\n[See all from Petr Koráb](https://towardsdatascience.com/author/petrkorab/)\n[Emotion Recognition](https://towardsdatascience.com/tag/emotion-recognition/)[Fine Tuning](https://towardsdatascience.com/tag/fine-tuning/)[Llm](https://towardsdatascience.com/tag/llm/)[Sentiment Classification](https://towardsdatascience.com/tag/sentiment-classification/)[Small Language Model](https://towardsdatascience.com/tag/small-language-model/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&title=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&title=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&text=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)\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/003.jpg)](https://towardsdatascience.com/stop-choosing-between-local-and-cloud-llms-a-field-guide-to-hybrid-patterns/)\n## [Stop Choosing Between Local and Cloud LLMs: A Field Guide to Hybrid Patterns](https://towardsdatascience.com/stop-choosing-between-local-and-cloud-llms-a-field-guide-to-hybrid-patterns/)\n[LLM Applications](https://towardsdatascience.com/category/artificial-intelligence/llm-applications/)\nA hands-on walkthrough of a hybrid local-cloud workflow using Gemma 4 and GPT-5.4, with reasoning and structured outputs\n[Shuai Guo](https://towardsdatascience.com/author/shuaiguo/)\nJune 30, 202616 min read\n  * [![](../images/004.png)](https://towardsdatascience.com/transformer-xl-review-beyond-fixed-length-contexts-d4fe1d6d3c0e/)\n## [Transformer-XL Review: Beyond Fixed-Length Contexts](https://towardsdatascience.com/transformer-xl-review-beyond-fixed-length-contexts-d4fe1d6d3c0e/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nReview of \"Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context\"\n[Jiajin Li](https://towardsdatascience.com/author/lijj36/)\nOctober 12, 20207 min read\n  * [![](../images/005.jpg)](https://towardsdatascience.com/building-a-simple-agent-with-tools-and-toolkits-in-langchain-77e0f9bd1fa5/)\n## [Building a simple Agent with Tools and Toolkits in LangChain](https://towardsdatascience.com/building-a-simple-agent-with-tools-and-toolkits-in-langchain-77e0f9bd1fa5/)\n[](https://towardsdatascience.com/how-to-fine-tune-an-slm-for-emotion-recognition/)\nGet familiar with the building blocks of Agents in LangChain\n[Sami Maameri](https://towardsdatascience.com/author/ssmaameri/)\nApril 10, 202413 min read\n  * [![](../images/006.png)](https://towardsdatascience.com/googles-musiclm-from-text-description-to-music-23794ab6955c/)\n## [Google's MusicLM: from text description to music](https://towardsdatascience.com/googles-musiclm-from-text-description-to-music-23794ab6955c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA new model is generating impressive music from just text prompt\n[Salvatore Raieli](https://towardsdatascience.com/author/salvatore-raieli/)\nFebruary 1, 20237 min read\n  * [![](../images/007.gif)](https://towardsdatascience.com/state-of-video-generation-76595bf75f46/)\n## [State of Video Generation](https://towardsdatascience.com/state-of-video-generation-76595bf75f46/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nOverview of latest developments in the Video Generation area: From LLMs to MultyDiffusion. Paper's insights and Outstanding questions.\n[Nikita Kiselov](https://towardsdatascience.com/author/nikita_kiselov/)\nFebruary 16, 202416 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/understanding-arima-models-using-pycarets-time-series-module-part-1-692e10ca02f2/)\n## [Understanding ARIMA Models using PyCaret's Time Series Module - Part 1](https://towardsdatascience.com/understanding-arima-models-using-pycarets-time-series-module-part-1-692e10ca02f2/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n📚 Introduction\n[Nikhil Gupta](https://towardsdatascience.com/author/ngupta13/)\nNovember 14, 202110 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/how-to-build-graph-transformers-with-o-n-complexity-d507e103d30a/)\n## [How to Build Graph Transformers with O(N) Complexity](https://towardsdatascience.com/how-to-build-graph-transformers-with-o-n-complexity-d507e103d30a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nTutorial on Large-Graph Transformers\n[Qitian Wu](https://towardsdatascience.com/author/qitianwu228/)\nApril 19, 20238 min read\n  * [![](../images/010.png)](https://towardsdatascience.com/llm-routing-intuitively-and-exhaustively-explained-5b0789fe27aa/)\n## [LLM Routing - Intuitively and Exhaustively Explained](https://towardsdatascience.com/llm-routing-intuitively-and-exhaustively-explained-5b0789fe27aa/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nDynamically Choosing the Right LLM\n[Daniel Warfield](https://towardsdatascience.com/author/danielwarfield1/)\nNovember 22, 202459 min read\n  * [![](../images/011.jpg)](https://towardsdatascience.com/the-untaught-lessons-of-rag-question-parsing-structure-before-you-search/)\n## [6 RAG question-parsing mistakes we keep seeing in production](https://towardsdatascience.com/the-untaught-lessons-of-rag-question-parsing-structure-before-you-search/)\n[Large Language Model](https://towardsdatascience.com/category/large-language-model/)\nEnterprise Document Intelligence [Vol.1 #6ter] - Six positions on the question-parsing brick that contradict the mainstream RAG playbook\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nJuly 2, 202611 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",
  "metadata": {
    "title": "How to Fine-Tune an SLM for Emotion Recognition | Towards Data Science",
    "description": "Python tutorial for fine-tuning a Mistral Small 3.1 on an imbalanced training set to classify 15 emotions in social media communication",
    "keywords": null,
    "author": "Petr Koráb",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "How to Fine-Tune an SLM for Emotion Recognition",
    "og:description": "Python tutorial for fine-tuning a Mistral Small 3.1 on an imbalanced training set to classify 15 emotions in social media communication",
    "og:url": "https://towardsdatascience.com/how-to-fine-tune-an-slm-for-emotion-recognition/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/06/cover-picture-II.png",
    "og:image:width": "1536",
    "og:image:height": "560",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Petr Koráb",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "9 min read",
    "article:published_time": "2026-06-05T06:00:06.000Z",
    "article:modified_time": "2026-06-05T06:00:06.000Z",
    "article:author": "https://towardsdatascience.com/author/petrkorab/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_000.txt",
      "chars": 606
    },
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_001.txt",
      "chars": 260
    },
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_002.txt",
      "chars": 379
    },
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_003.txt",
      "chars": 1261
    },
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_004.txt",
      "chars": 1777
    },
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_005.txt",
      "chars": 1619
    },
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_006.txt",
      "chars": 1594
    },
    {
      "language": "txt",
      "file": "attachments/550b9f25e3e8/code/block_007.txt",
      "chars": 2072
    }
  ],
  "images": [
    {
      "status": "ok",
      "url": "https://cdn-cookieyes.com/assets/images/revisit.svg",
      "bytes": 2339,
      "reused": false,
      "content_type": "image/svg+xml",
      "local_path": "attachments/550b9f25e3e8/images/body-df29beacd7496220cc94.svg",
      "src": "https://cdn-cookieyes.com/assets/images/revisit.svg",
      "alt": "Revisit consent button",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn-cookieyes.com/assets/images/close.svg",
      "bytes": 1345,
      "reused": false,
      "content_type": "image/svg+xml",
      "local_path": "attachments/550b9f25e3e8/images/body-2159bb67f3de8ad870eb.svg",
      "src": "https://cdn-cookieyes.com/assets/images/close.svg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/06/cover-picture-II.png",
      "bytes": 332455,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/000.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/06/cover-picture-II.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/data_head-1024x340.png",
      "bytes": 162579,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/001.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/data_head-1024x340.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/emotion_label_distribution-1-1024x434.png",
      "bytes": 91547,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/002.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/emotion_label_distribution-1-1024x434.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/ISMOTE-diagram.png",
      "bytes": 155163,
      "reused": false,
      "content_type": "image/png",
      "local_path": "attachments/550b9f25e3e8/images/body-d8e9b0b2c266c14a4706.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/ISMOTE-diagram.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/eda_relative_freq_all_sets-1024x508.png",
      "bytes": 73356,
      "reused": false,
      "content_type": "image/png",
      "local_path": "attachments/550b9f25e3e8/images/body-d96d37abaf82578949da.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/eda_relative_freq_all_sets-1024x508.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/1787657190540_3p82kv.jpeg",
      "bytes": 288490,
      "reused": false,
      "content_type": "image/jpeg",
      "local_path": "attachments/550b9f25e3e8/images/body-9e78938b5e8b0a70213c.jpeg",
      "src": "https://assets.insightmediagroup.io/media/1787657190540_3p82kv.jpeg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/06/hybrid_pattern.jpg",
      "bytes": 283626,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/003.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/06/hybrid_pattern.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0TmITO92QHlhKKiov.png",
      "bytes": 241538,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/004.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0TmITO92QHlhKKiov.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/0XQaSfBvcMnEB4AWI-scaled.jpg",
      "bytes": 437054,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/005.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/0XQaSfBvcMnEB4AWI-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/02/16IWb_FuYyv9uXKhrRDFuIw.png",
      "bytes": 1444467,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/006.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/02/16IWb_FuYyv9uXKhrRDFuIw.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1G1bEwT1czd5gOTyTae54Lw.gif",
      "bytes": 15902835,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/007.gif",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1G1bEwT1czd5gOTyTae54Lw.gif",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0Dra8YUNCvq01x5IJ-scaled.jpg",
      "bytes": 478170,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/008.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0Dra8YUNCvq01x5IJ-scaled.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/0eKIxcnve9eYE7Q23.jpg",
      "bytes": 110306,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/009.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/0eKIxcnve9eYE7Q23.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/11/1Aja1M1MtLsRmsFCTdPeoJg.png",
      "bytes": 1197790,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/010.png",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/11/1Aja1M1MtLsRmsFCTdPeoJg.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/catalog_drawers_11121083_v3_card.jpg",
      "bytes": 196150,
      "reused": true,
      "local_path": "attachments/550b9f25e3e8/images/011.jpg",
      "src": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/catalog_drawers_11121083_v3_card.jpg",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    }
  ],
  "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/petrkorab/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/emotion-recognition/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/fine-tuning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/llm/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/sentiment-classification/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/small-language-model/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/stop-choosing-between-local-and-cloud-llms-a-field-guide-to-hybrid-patterns/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/llm-applications/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/shuaiguo/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/transformer-xl-review-beyond-fixed-length-contexts-d4fe1d6d3c0e/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/lijj36/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/building-a-simple-agent-with-tools-and-toolkits-in-langchain-77e0f9bd1fa5/"
    },
    {
      "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://huggingface.co/models?num_parameters=min%3A6B&pipeline_tag=text-generation&search=sentiment+llama&sort=trending"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/models?search=emotion+mistral&sort=trending"
    },
    {
      "type": "external",
      "href": "https://research.google/blog/goemotions-a-dataset-for-fine-grained-emotion-classification/"
    },
    {
      "type": "external",
      "href": "https://latitude.so/blog/fine-tuning-llms-on-imbalanced-data-best-practices"
    },
    {
      "type": "external",
      "href": "https://www.nature.com/articles/s41598-025-09506-w"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://github.com/google-research/google-research/tree/master/goemotions"
    },
    {
      "type": "external",
      "href": "https://github.com/google-research/google-research/blob/master/goemotions/data/emotions.txt"
    },
    {
      "type": "external",
      "href": "https://www.tensorflow.org/datasets/catalog/goemotions"
    },
    {
      "type": "external",
      "href": "https://www.nature.com/articles/s41598-025-09506-w/figures/3"
    },
    {
      "type": "external",
      "href": "https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions/tree/main"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503"
    },
    {
      "type": "external",
      "href": "https://unsloth.ai/docs"
    },
    {
      "type": "external",
      "href": "https://pypi.org/project/transformers/"
    },
    {
      "type": "external",
      "href": "https://www.ibm.com/think/topics/lora"
    },
    {
      "type": "external",
      "href": "https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:23:10Z",
  "source_url": "https://towardsdatascience.com/how-to-fine-tune-an-slm-for-emotion-recognition/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "http_403",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 17,
  "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# How to Fine-Tune an SLM for Emotion Recognition\nPython tutorial for fine-tuning a Mistral Small 3.1 on an imbalanced training set to classify 15 emotions in social media communication\n[Petr Koráb](https://towardsdatascience.com/author/petrkorab/)\nJune 5, 20269 min read\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/06/cover-picture-II.png)\nImage created by GPT 5.3\n## Introduction\nRecent small language models (SLMs) fine-tuned for [sentiment classification](https://huggingface.co/models?pipeline_tag=text-generation&num_parameters=min:6B&sort=trending&search=sentiment+llama) infer sentiment as a single score, capturing the overall emotional tone of the text. For many use cases, the positive-negative classification does not tell the full story a company needs. Emotion recognition models go further, decomposing sentiment into emotion classes (_“anger”, “approval”, “disappointment”_ , etc.) and assigning probabilities to a set of emotions in the text. It is then possible to model emotional content in datasets that a company receives (customer tickets, emails, brand-related discussions), and react swiftly to changing conditions.\nFor one of our recent projects, modeling emotions in online media, we required an emotion recognition model with open weights and a flexible license, maintaining high transparency standards, and, of course, benefiting from the lower costs associated with open models. We subjectively prefer European models, but Hugging Face did not offer a [Mistral alternative with](https://huggingface.co/models?sort=trending&search=emotion+mistral) a developed model card. One possible reason is that the most detailed training set for emotion recognition, the 28-emotion [GoEmotions datase](https://research.google/blog/goemotions-a-dataset-for-fine-grained-emotion-classification/)t, is highly [class-imbalanced](https://latitude.so/blog/fine-tuning-llms-on-imbalanced-data-best-practices). Fine-tuning an SLM on a high-class-imbalance data set that performs decently on the test requires a deeper focus.\nWe treated the class-imbalance problem by a combination of three techniques: (1) **undersampling** the most represented emotional category, (2) **synthetically expanding** the **minority classes** with [Nature’s 2025 ISMOTE](https://www.nature.com/articles/s41598-025-09506-w) algorithm, and (3) **weighting** the **loss function.** With this combination of techniques, [_MistralSmall-3.1.GoEmotions_](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions), now released on Hugging Face, infers most target emotions relevant to our project with F1 > 0.7.\nThis article explains in detail how to fine-tune an open-weight SLM. We’ll also figure out: \n  * _How to preprocess class-imbalanced data for LLM fine-tuning with the_[ _2025 ISMOTE_](https://www.nature.com/articles/s41598-025-09506-w) _algorithm._\n  * _How to decompose sentiment into emotion categories by finetuning a Small Language Model for emotion recognition in text data._\n\n\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## 2. Data\n[GoEmotions](https://github.com/google-research/google-research/tree/master/goemotions) is a human-annotated dataset of 58k Reddit comments extracted from English-language subreddits and labeled with [27 emotion categories](https://github.com/google-research/google-research/blob/master/goemotions/data/emotions.txt) and a _“neutral”_ label. It is a **multi-label classification dataset** in which each comment may be labeled with multiple TRUEs for emotions (e.g., _“Hitting me. That just added another funny dynamic to it even though I wasn’t actually trying to hit her”_ is True for _“amusement”_ , and _“annoyance”_).\nThe dataset was released on [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/goemotions) under the Apache 2.0 License and contains 54,263 labeled texts. Here is what it looks like:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/data_head-1024x340.png)\nImage 1. GoEmotions dataset. Image by author.\nAfter a quick check, we can see a high-class imbalance in the data where the _neutral_ category prevails:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/emotion_label_distribution-1-1024x434.png)\nImage 2. Class imbalance in GoEmotions dataset. Image by author.\n## 3. Training set preprocessing\n> __Our goal is to develop a classifier to identify 15 emotions in general-language texts. Training on class-imbalanced data can introduce bias, as the fine-tuned model tends to favor the majority class and perform worse on the minority ones, so preprocessing is essential.__\nWe used a combination of methods for the **training set;** the validation and test sets remained unchanged to address class imbalance and maximize performance on the target emotions (_fear, sadness, disgust, disapproval, annoyance, anger, disappointment, optimism, amusement, surprise, admiration, excitement, confusion, joy, love_): \n  * We thinned the data by randomly filtering the _“neutral”_ rows.\n  * We generated synthetic samples for the least-represented emotional categories using _ISMOTE (Improved Synthetic Minority Over-sampling Technique)_.\n\n\nThe _ISMOTE_ algorithm extends the common SMOTE technique by (1) expanding the sample generation space and (2) improving sampling distribution. The synthetically generated samples then have more realistic data distributions than those produced by the original method.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/ISMOTE-diagram.png)\nImage 3. The flowchart of the ISMOTE algorithm. Source: [Scientific Reports.](https://www.nature.com/articles/s41598-025-09506-w/figures/3)\nBy reducing the majority class and synthetically expanding the minority categories to 4000 samples, we constructed a relatively balanced set for fine-tuning. The code for ISMOTE oversampling is [here.](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions/tree/main)\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/eda_relative_freq_all_sets-1024x508.png)\nImage 4. Label relative frequency , train (augmented), validation, and test sets. Image by author.\n## 4. SLM Fine-tuning\nAmong Mistral’s models, we chose the _Small_ class ([Small-3.1-24B-Instruct-2503](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)), which fits our GPU and provides the multilingual capabilities we need for the classifier. The [Unsloth](https://unsloth.ai/docs) framework makes the finetuning steps uncomplicated and faster than with [Transformers](https://pypi.org/project/transformers/):\n_**1. Data loading**_  _—_ _loading preprocessed training set, validation, and test sets._ We use a 60:20:20 split.\n_**2. Loading**_ _the_ _**base model**_ _— loading the Small-3.1–24B-Instruct-2503 locally._\n_**3.**__Apply_ _**LoRA**_ _—_[ _lowering hardware requirements_](https://www.ibm.com/think/topics/lora) _._\n_**4. Multilabel wrapper with focal loss function**_ _— updates the trainer for multilabel classification. Also adds focal loss to weight the loss function for a selected set of emotions, prioritizing their performance._\n_**5. Evaluation metrics**_ _and_ _**training args**_ _— specifying the evaluation metrics and hyperparameters for model training._\n_**6.**__Model_ _**training**_ _— trainer formulation and launch._\n_**7. Evaluation**_ _— evaluating the best model performance on the test set._\n## 4.1. Coding \nHere is the code implementation.\n### 4.1.1. Data loading\npython\n\n```\n# Loading augmented train, validation and test sets\nBASE = r\"augmented\"\n\ndef load_split(path: str) -> Dataset:\n    with open(path, encoding=\"utf-8\") as f:\n        d = json.load(f)\n    return Dataset.from_dict({\"input_embeds\": d[\"X\"], \"labels\": d[\"y\"]})\n\ntrain_dataset = load_split(f\"{BASE}/train.json\")\nval_dataset   = load_split(f\"{BASE}/val.json\")\ntest_dataset  = load_split(f\"{BASE}/test.json\")\n\n# Formulate embedding dimension\nEMBED_DIM = len(train_dataset[0][\"input_embeds\"])\n\n# Return Pytorch tensors\ntrain_dataset.set_format(\"torch\")\nval_dataset.set_format(\"torch\")\ntest_dataset.set_format(\"torch\")\n```\n\n### 4.1.2. Loading the base model \npython\n\n```\n# Load base model with Unsloth FastLanguageModel\nMODEL_NAME = \"unsloth/Mistral-Small-3.1-24B-Instruct-2503\"\n\nbase_model, _ = FastLanguageModel.from_pretrained(\n    model_name=MODEL_NAME,\n    max_seq_length=2,\n    load_in_4bit=True,\n    dtype=torch.bfloat16,\n)\n```\n\n### 4.1.3. Apply LoRA\npython\n\n```\n# Aply Low-rank adaptation (LoRA) \nbase_model = FastLanguageModel.get_peft_model(\n    base_model,\n    r=16,\n    lora_alpha=32,\n    lora_dropout=0,\n    bias=\"none\",\n    target_modules=[\n        \"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n        \"gate_proj\", \"up_proj\", \"down_proj\",\n    ],\n    use_gradient_checkpointing=\"unsloth\",\n    random_state = 3407,\n    use_rslora = False, \n)\n```\n\n### 4.1.4. Multilabel wrapper with focal loss function\npython\n\n```\n# Focal loss weights for preffered labels  \nFOCAL_ALPHA_DEFAULT   = 0.25\nFOCAL_ALPHA_PREFERRED = 0.75\n\nPREFERRED_LABELS = {\n    \"fear\", \"sadness\", \"disgust\", \"disapproval\", \"annoyance\",\n    \"anger\", \"disappointment\", \"optimism\", \"amusement\", \"surprise\",\n    \"admiration\", \"excitement\", \"confusion\",\"joy\",\"love\"\n}\n\nFOCAL_ALPHA_PER_LABEL: list[float] = [\n    FOCAL_ALPHA_PREFERRED if lbl in PREFERRED_LABELS else FOCAL_ALPHA_DEFAULT\n    for lbl in EMOTION_LABELS\n]\n\n\"Per-label weighted focal binary cross-entropy for multi-label problems\"\nclass FocalLossWithAlpha(nn.Module):\n        def __init__(self, alpha: list[float], gamma: float = 2.0):\n        super().__init__()\n        self.register_buffer(\"alpha\", torch.tensor(alpha, dtype=torch.float32))\n        self.gamma = gamma\n    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:\n        probs   = torch.sigmoid(logits)\n        p_t     = probs * targets + (1.0 - probs) * (1.0 - targets)\n        alpha_t = self.alpha * targets + (1.0 - self.alpha) * (1.0 - targets)\n        focal_w = alpha_t * (1.0 - p_t) ** self.gamma\n        bce     = nn.functional.binary_cross_entropy_with_logits(\n            logits, targets, reduction=\"none\"\n        )\n        return (focal_w * bce).mean()\n\n```\n\npython\n\n```\n# Multilabel classification wrapper with focal loss class weighting\nclass MistralForMultiLabel(nn.Module):\n    is_loaded_in_4bit = True\n\n    def __init__(self, backbone: nn.Module, num_labels: int,\n                 hidden_size: int, embed_dim: int):\n        super().__init__()\n        self.backbone = backbone\n        _device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        self.projection = nn.Sequential(\n            nn.Linear(embed_dim, hidden_size // 2),\n            nn.GELU(),\n            nn.Linear(hidden_size // 2, hidden_size),\n        ).to(_device)\n        self.dropout    = nn.Dropout(0.1).to(_device)\n        self.classifier = nn.Linear(hidden_size, num_labels).to(_device)\n        self.focal_loss = FocalLossWithAlpha(FOCAL_ALPHA_PER_LABEL).to(_device)\n\n    def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):\n        self.backbone.gradient_checkpointing_enable(gradient_checkpointing_kwargs)\n\n    def gradient_checkpointing_disable(self):\n        self.backbone.gradient_checkpointing_disable()\n\n    def forward(\n        self,\n        input_embeds: torch.Tensor,\n        labels: torch.Tensor | None = None,\n        **kwargs,\n    ):\n        B = input_embeds.size(0)\n        projected = self.projection(input_embeds).unsqueeze(1)\n        attn_mask = torch.ones(B, 1, device=input_embeds.device)\n\n        outputs = self.backbone.base_model.model.model(\n            inputs_embeds=projected,\n            attention_mask=attn_mask,\n            output_hidden_states=True,\n        )\n        pooled = outputs.hidden_states[-1][:, 0, :]\n        logits = self.classifier(self.dropout(pooled))\n\n        loss = self.focal_loss(logits, labels.float()) if labels is not None else None\n        return {\"loss\": loss, \"logits\": logits}\n```\n\n### 4.1.5. Evaluation metrics and training args\npython\n\n```\n# Specifiy the evaluation function\ndef compute_metrics(eval_pred):\n    logits, labels = eval_pred\n    probs = torch.sigmoid(torch.tensor(logits)).numpy()\n    preds = (probs >= 0.5).astype(int)\n    labels = labels.astype(int)\n\n    from sklearn.metrics import accuracy_score\n\n    exact_accuracy  = accuracy_score(labels, preds)\n    macro_f1        = f1_score(labels, preds, average=\"macro\", zero_division=0)\n    micro_f1        = f1_score(labels, preds, average=\"micro\", zero_division=0)\n    macro_precision = precision_score(labels, preds, average=\"macro\", zero_division=0)\n    macro_recall    = recall_score(labels, preds, average=\"macro\", zero_division=0)\n\n    per_class_f1        = f1_score(labels, preds, average=None, zero_division=0)\n    per_class_recall    = recall_score(labels, preds, average=None, zero_division=0)\n    per_class_precision = precision_score(labels, preds, average=None, zero_division=0)\n    per_class_accuracy  = (preds == labels).mean(axis=0)\n\n    per_class_metrics = {}\n    for i, emotion in enumerate(EMOTION_LABELS):\n        per_class_metrics[f\"f1_{emotion}\"]        = float(per_class_f1[i])\n        per_class_metrics[f\"recall_{emotion}\"]    = float(per_class_recall[i])\n        per_class_metrics[f\"precision_{emotion}\"] = float(per_class_precision[i])\n        per_class_metrics[f\"accuracy_{emotion}\"]  = float(per_class_accuracy[i])\n\n    return {\n        \"exact_accuracy\":   exact_accuracy,\n        \"macro_f1\":         macro_f1,\n        \"micro_f1\":         micro_f1,\n        \"macro_precision\":  macro_precision,\n        \"macro_recall\":     macro_recall,\n        **per_class_metrics,\n    }\n```\n\npython\n\n```\n# Specify hyperparameters\ntraining_args = TrainingArguments(\n    output_dir=OUTPUT_DIR,            # where checkpoints and logs are written\n    eval_strategy=\"epoch\",            # run evaluation once per epoch\n    save_strategy=\"epoch\",            # save checkpoint once per epoch\n    per_device_train_batch_size=8,    # samples per GPU per step\n    per_device_eval_batch_size=16,    # larger batch is fine — no gradients\n    gradient_accumulation_steps=4,    # effective batch = 8 × 4 = 32\n    num_train_epochs=15,              # total passes over the training data\n    learning_rate=1e-4,               # peak LR after warmup\n    bf16=True,                        # bfloat16 mixed precision\n    optim=\"adamw_8bit\",               # 8-bit AdamW\n    warmup_ratio=0.05,                # first 5 % of steps ramp LR from 0 to peak\n    lr_scheduler_type=\"cosine\",       # cosine decay from peak LR to ~0\n    logging_steps=25,                 # print loss/LR to console every 25 steps\n    logging_first_step=True,          # also log step 1 to catch early instability\n    load_best_model_at_end=True,      # restore best checkpoint after training ends\n    metric_for_best_model=\"macro_f1\", # criterion used to select the best checkpoint\n    greater_is_better=True,           # higher macro_f1 is better in evaluation\n    gradient_checkpointing=False,    \n    remove_unused_columns=False,      # keep input_embeds column\n    save_total_limit=15,              # keep all checkpoints on disk to load the best model\n    weight_decay=0.01,                # L2 regularisation on all trainable parameters\n)\n```\n\n### 4.1.6. Model training\npython\n\n```\n# Set-up the trainer for multilabel finetuning\nclass MultiLabelTrainer(Trainer):\n    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):\n        labels = inputs.pop(\"labels\")\n        outputs = model(**inputs, labels=labels)\n        loss = outputs[\"loss\"]\n        return (loss, outputs) if return_outputs else loss\n\n    def _save_checkpoint(self, model, trial, metrics=None):\n        super()._save_checkpoint(model, trial)\n        ckpt_dir = self._get_output_dir(trial)\n        # Save head\n        torch.save({\n            \"projection\": model.projection.state_dict(),\n            \"classifier\":  model.classifier.state_dict(),\n        }, os.path.join(ckpt_dir, \"head_weights.pt\"))\n        # Save LoRA adapter explicitly (bypasses bitsandbytes serialization issues)\n        model.backbone.save_pretrained(os.path.join(ckpt_dir, \"lora_adapter\"))\n\n    def _load_best_model(self):\n        best_ckpt = self.state.best_model_checkpoint\n        if not best_ckpt:\n            return\n        # Restore head\n        head_path = os.path.join(best_ckpt, \"head_weights.pt\")\n        if os.path.exists(head_path):\n            head = torch.load(head_path, map_location=\"cpu\")\n            self.model.projection.load_state_dict(head[\"projection\"])\n            self.model.classifier.load_state_dict(head[\"classifier\"])\n            print(f\"Head restored from: {best_ckpt}\")\n        else:\n            print(f\"WARNING: head_weights.pt not found in {best_ckpt}\")\n        # Restore LoRA adapter\n        lora_path = os.path.join(best_ckpt, \"lora_adapter\")\n        if os.path.exists(lora_path):\n            from peft import PeftModel\n            self.model.backbone.load_adapter(lora_path, adapter_name=\"default\")\n            print(f\"LoRA restored from: {best_ckpt}\")\n        else:\n            print(f\"WARNING: lora_adapter/ not found in {best_ckpt}\")\n\n# Launch the trainer\ntrainer = MultiLabelTrainer(\n    model=model,\n    args=training_args,\n    train_dataset=train_dataset,\n    eval_dataset=val_dataset,\n    compute_metrics=compute_metrics,\n)\n\n# Launch training\ntrainer.train()\n```\n\nFine-tuning for 15 epochs took 9 hours and 30 minutes on a machine with an NVIDIA RTX 6000 GPU and 192 GB of VRAM, with the best model loaded at the end.\n### 4.1.7. Model evaluation\nLet's show the performance on the test dataset. The standard statistics for model evaluation per class are **F1** , **Precision** , and **Recall**. We can see relatively good performance on the target emotions, with F1 scores over 0.7, for most categories. Full performance is on the [model card](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions).  \n| **Emotion**  | **Precision**  | **Recall**  | **F1**  | **N**  |  \n| --- | --- | --- | --- | --- |  \n| admiration  | 0.7415  | 0.6354  | 0.6844  | 993  |  \n| amusement  | 0.7810  | 0.7422  | 0.7611  | 543  |  \n| anger  | 0.7423  | 0.7367  | 0.7395  | 395  |  \n| annoyance  | 0.7049  | 0.5452  | 0.6148  | 609  |  \n| confusion  | 0.7576  | 0.8251  | 0.7899  | 303  |  \n| disappointment  | 0.8487  | 0.8459  | 0.8473  | 305  |  \n| disapproval  | 0.7208  | 0.5841  | 0.6453  | 517  |  \n| disgust  | 0.8396  | 0.9368  | 0.8856  | 190  |  \n| excitement  | 0.8240  | 0.9366  | 0.8767  | 205  |  \n| fear  | 0.9112  | 0.9686  | 0.9390  | 159  |  \n| joy  | 0.7577  | 0.8024  | 0.7794  | 339  |  \n| love  | 0.7424  | 0.7903  | 0.7656  | 496  |  \n| optimism  | 0.8145  | 0.7636  | 0.7882  | 368  |  \n| sadness  | 0.8534  | 0.8899  | 0.8713  | 327  |  \n| surprise  | 0.8456  | 0.8555  | 0.8505  | 256  |  \n| **Macro precision**  | **0.8295**  |   |   |   |  \n| **Macro recall**  | **0.8184**  |   |   |   |  \n| **Micro F1**  | **0.7527**  |   |   |   |  \n| **Macro F1**  | **0.8215**  |   |   |   |  \n## 5. Summary\nLet’s now summarize the key points of the article. The requirements and full code are in this [repo](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions).\n  * **Emotion recognition** modeling extends sentiment analysis by decomposing the overall sentiment score into its emotional components.\n  * **MistralSmall-3.1.GoEmotions** is on [_Hugging Face_](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions)[ ](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions)under the Apache 2.0 license. The [repo ](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions)also includes the inference guideline.\n  * **Deployment use cases** are [brand and social monitoring](https://www.meegle.com/en_us/topics/affective-computing/emotion-recognition-in-marketing-campaigns), and [email categorization](https://cobbai.com/blog/email-classification-ai-support).\n\n\n_**Petr Koráb**_ _is the founder of Text Mining Stories,_ a Prague-based development & consultancy company. Learn more about the cutting-edge NLP on [our blog.](https://textminingstories.com/blog/)\n_**AI statement**_. Some parts of the code were reviewed by Sonnet 4.6 (Cursor). No text was generated using AI.\n_**Acknowledgements**_ _._ The National Bank of Slovakia Foundation supported this development. I thank Martin Feldkircher, Václav Jež, and Michala Moravcová for comments and suggestions.\n## References\n[1] Ying Li, Yali Yang, Peihua Song, Lian Duan, Rui Ren. 2025. An improved SMOTE algorithm for enhanced imbalanced data classification by expanding sample generation space.[_Scientific Reports, 15_](https://www.nature.com/articles/s41598-025-09506-w)[(](https://www.nature.com/articles/s41598-025-09506-w)[_23521)._](https://www.nature.com/articles/s41598-025-09506-w)\n[2] Yinhan Liu _, Jiatao Gu_ , Naman Goyal, Xian Li, Sergey Edunov  \nMarjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer. 2020. [_Multilingual Denoising Pre-training for Neural Machine Translation_](https://aclanthology.org/2020.tacl-1.47.pdf). Transactions of the Association for Computational Linguistics, 8, pp. 726–742.\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* * *\n![](https://assets.insightmediagroup.io/media/1787657190540_3p82kv.jpeg)\nWritten By\n## [Petr Koráb](https://towardsdatascience.com/author/petrkorab/)\n[See all from Petr Koráb](https://towardsdatascience.com/author/petrkorab/)\n[Emotion Recognition](https://towardsdatascience.com/tag/emotion-recognition/)[Fine Tuning](https://towardsdatascience.com/tag/fine-tuning/)[Llm](https://towardsdatascience.com/tag/llm/)[Sentiment Classification](https://towardsdatascience.com/tag/sentiment-classification/)[Small Language Model](https://towardsdatascience.com/tag/small-language-model/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&title=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&title=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&text=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)\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/2026/06/hybrid_pattern.jpg)](https://towardsdatascience.com/stop-choosing-between-local-and-cloud-llms-a-field-guide-to-hybrid-patterns/)\n## [Stop Choosing Between Local and Cloud LLMs: A Field Guide to Hybrid Patterns](https://towardsdatascience.com/stop-choosing-between-local-and-cloud-llms-a-field-guide-to-hybrid-patterns/)\n[LLM Applications](https://towardsdatascience.com/category/artificial-intelligence/llm-applications/)\nA hands-on walkthrough of a hybrid local-cloud workflow using Gemma 4 and GPT-5.4, with reasoning and structured outputs\n[Shuai Guo](https://towardsdatascience.com/author/shuaiguo/)\nJune 30, 202616 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/0TmITO92QHlhKKiov.png)](https://towardsdatascience.com/transformer-xl-review-beyond-fixed-length-contexts-d4fe1d6d3c0e/)\n## [Transformer-XL Review: Beyond Fixed-Length Contexts](https://towardsdatascience.com/transformer-xl-review-beyond-fixed-length-contexts-d4fe1d6d3c0e/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nReview of \"Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context\"\n[Jiajin Li](https://towardsdatascience.com/author/lijj36/)\nOctober 12, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/0XQaSfBvcMnEB4AWI-scaled.jpg)](https://towardsdatascience.com/building-a-simple-agent-with-tools-and-toolkits-in-langchain-77e0f9bd1fa5/)\n## [Building a simple Agent with Tools and Toolkits in LangChain](https://towardsdatascience.com/building-a-simple-agent-with-tools-and-toolkits-in-langchain-77e0f9bd1fa5/)\n[](https://towardsdatascience.com/how-to-fine-tune-an-slm-for-emotion-recognition/)\nGet familiar with the building blocks of Agents in LangChain\n[Sami Maameri](https://towardsdatascience.com/author/ssmaameri/)\nApril 10, 202413 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/02/16IWb_FuYyv9uXKhrRDFuIw.png)](https://towardsdatascience.com/googles-musiclm-from-text-description-to-music-23794ab6955c/)\n## [Google's MusicLM: from text description to music](https://towardsdatascience.com/googles-musiclm-from-text-description-to-music-23794ab6955c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA new model is generating impressive music from just text prompt\n[Salvatore Raieli](https://towardsdatascience.com/author/salvatore-raieli/)\nFebruary 1, 20237 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/02/1G1bEwT1czd5gOTyTae54Lw.gif)](https://towardsdatascience.com/state-of-video-generation-76595bf75f46/)\n## [State of Video Generation](https://towardsdatascience.com/state-of-video-generation-76595bf75f46/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nOverview of latest developments in the Video Generation area: From LLMs to MultyDiffusion. Paper's insights and Outstanding questions.\n[Nikita Kiselov](https://towardsdatascience.com/author/nikita_kiselov/)\nFebruary 16, 202416 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/11/0Dra8YUNCvq01x5IJ-scaled.jpg)](https://towardsdatascience.com/understanding-arima-models-using-pycarets-time-series-module-part-1-692e10ca02f2/)\n## [Understanding ARIMA Models using PyCaret's Time Series Module - Part 1](https://towardsdatascience.com/understanding-arima-models-using-pycarets-time-series-module-part-1-692e10ca02f2/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n📚 Introduction\n[Nikhil Gupta](https://towardsdatascience.com/author/ngupta13/)\nNovember 14, 202110 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/04/0eKIxcnve9eYE7Q23.jpg)](https://towardsdatascience.com/how-to-build-graph-transformers-with-o-n-complexity-d507e103d30a/)\n## [How to Build Graph Transformers with O(N) Complexity](https://towardsdatascience.com/how-to-build-graph-transformers-with-o-n-complexity-d507e103d30a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nTutorial on Large-Graph Transformers\n[Qitian Wu](https://towardsdatascience.com/author/qitianwu228/)\nApril 19, 20238 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/11/1Aja1M1MtLsRmsFCTdPeoJg.png)](https://towardsdatascience.com/llm-routing-intuitively-and-exhaustively-explained-5b0789fe27aa/)\n## [LLM Routing - Intuitively and Exhaustively Explained](https://towardsdatascience.com/llm-routing-intuitively-and-exhaustively-explained-5b0789fe27aa/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nDynamically Choosing the Right LLM\n[Daniel Warfield](https://towardsdatascience.com/author/danielwarfield1/)\nNovember 22, 202459 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/catalog_drawers_11121083_v3_card.jpg)](https://towardsdatascience.com/the-untaught-lessons-of-rag-question-parsing-structure-before-you-search/)\n## [6 RAG question-parsing mistakes we keep seeing in production](https://towardsdatascience.com/the-untaught-lessons-of-rag-question-parsing-structure-before-you-search/)\n[Large Language Model](https://towardsdatascience.com/category/large-language-model/)\nEnterprise Document Intelligence [Vol.1 #6ter] - Six positions on the question-parsing brick that contradict the mainstream RAG playbook\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nJuly 2, 202611 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",
  "body_base_path": "attachments/550b9f25e3e8/pages/",
  "body_markdown_path": "attachments/550b9f25e3e8/pages/archived-body.md",
  "local_html": "attachments/550b9f25e3e8/pages/archived-body.html",
  "body_source": "prior_capture"
}