{"id":36199,"date":"2024-11-01T09:46:34","date_gmt":"2024-11-01T09:46:34","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=36199"},"modified":"2024-11-01T09:46:34","modified_gmt":"2024-11-01T09:46:34","slug":"using-hugging-face-transformers-classification-report","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/36199\/","title":{"rendered":"Using Hugging Face Transformers, Classification Report"},"content":{"rendered":"<p><body><\/p>\n<p>In recent years, the field of Natural Language Processing (NLP) has made significant advancements. At the center of this is <strong>Deep Learning<\/strong> and <strong>Transformer models<\/strong>, particularly <strong>Hugging Face<\/strong>&#8216;s <strong>Transformers<\/strong> library, which is widely used by many researchers and developers. In this article, we will explore how to train and evaluate a text classification model using Hugging Face&#8217;s Transformers library.<\/p>\n<h2>1. Introduction to Hugging Face Transformers Library<\/h2>\n<p>Hugging Face&#8217;s Transformers library is an open-source library that helps users easily utilize various pre-trained transformer models and fine-tune them according to their own data. It includes various models such as BERT, GPT-2, and RoBERTa, and its API is intuitive and easy to use.<\/p>\n<h2>2. Definition of Text Classification Problem<\/h2>\n<p>Text classification is the task of categorizing given text data into one or more class labels. For example, it involves determining whether an email is spam or not, or classifying a movie review as positive or negative. In this course, we will build a model to classify IMDB movie reviews as positive and negative using a simple example.<\/p>\n<h2>3. Data Loading and Basic Preprocessing<\/h2>\n<p>First, we will install the necessary libraries and load the IMDB dataset. The IMDB dataset includes movie reviews and their corresponding sentiment labels.<\/p>\n<pre><code>python\n# Install necessary libraries\n!pip install transformers torch datasets\n\n# Import libraries\nfrom datasets import load_dataset\n\n# Load IMDB dataset\ndataset = load_dataset('imdb')\n\nprint(dataset)\n<\/code><\/pre>\n<p>When the above code is executed, you will see that the IMDB dataset is loaded and divided into train and validation sets. Each dataset includes movie reviews and sentiment labels.<\/p>\n<h2>4. Data Preprocessing<\/h2>\n<p>To input data into the model, text tokenization and encoding are needed. We will process the text using the tokenizer provided by Hugging Face&#8217;s transformer models.<\/p>\n<pre><code>python\nfrom transformers import AutoTokenizer\n\n# Set model name\nmodel_name = 'distilbert-base-uncased'\ntokenizer = AutoTokenizer.from_pretrained(model_name)\n\n# Check sample data\nsample_text = dataset['train'][0]['text']\nencoded_input = tokenizer(sample_text, padding='max_length', truncation=True, return_tensors='pt')\n\nprint(encoded_input)\n<\/code><\/pre>\n<p>The above code tokenizes the first movie review using the DistilBERT model&#8217;s tokenizer and outputs the encoded tensor after applying padding and truncation to fit the maximum length.<\/p>\n<h2>5. Model Definition and Training<\/h2>\n<p>Now we will define the model and proceed with training. The Hugging Face Trainer API allows us to conduct the training process conveniently.<\/p>\n<pre><code>python\nfrom transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments\n\n# Load model\nmodel = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)\n\n# Define training arguments\ntraining_args = TrainingArguments(\n    output_dir='.\/results',\n    num_train_epochs=3,\n    per_device_train_batch_size=8,\n    per_device_eval_batch_size=8,\n    warmup_steps=500,\n    weight_decay=0.01,\n    logging_dir='.\/logs',\n)\n\n# Create Trainer object\ntrainer = Trainer(\n    model=model,\n    args=training_args,\n    train_dataset=dataset['train'],\n    eval_dataset=dataset['test']\n)\n\n# Train the model\ntrainer.train()\n<\/code><\/pre>\n<p>The above code defines a text classification model based on DistilBERT and trains it using the Trainer API with the IMDB dataset. Once the training is complete, the weights are saved in the .\/results folder.<\/p>\n<h2>6. Model Evaluation<\/h2>\n<p>After training the model, we will evaluate its performance using the test dataset. We will use accuracy as the evaluation metric.<\/p>\n<pre><code>python\n# Evaluate with test dataset\nresults = trainer.evaluate()\n\nprint(f\"Accuracy: {results['eval_accuracy']:.2f}\")\n<\/code><\/pre>\n<p>After model evaluation, the accuracy will be printed. This allows us to check the model&#8217;s performance.<\/p>\n<h2>7. Predictions and Classification Report<\/h2>\n<p>Now, we can use the trained model to make predictions on new data. We will check the prediction results and print the classification report with the following code.<\/p>\n<pre><code>python\nfrom sklearn.metrics import classification_report\nimport numpy as np\n\n# Prepare prediction data\npredictions = trainer.predict(dataset['test'])\npreds = np.argmax(predictions.predictions, axis=1)\n\n# Print classification report\nreport = classification_report(dataset['test']['label'], preds)\nprint(report)\n<\/code><\/pre>\n<p>The above code performs predictions on the test dataset and uses sklearn&#8217;s classification_report to output metrics such as Precision, Recall, and F1-Score. This report provides detailed information about the model&#8217;s performance.<\/p>\n<h2>8. Conclusion and Next Steps<\/h2>\n<p>In this course, we explored how to build a simple text classification model using Hugging Face&#8217;s Transformers library and evaluate it. To continuously improve the model&#8217;s performance, more diverse techniques can be applied during the data preprocessing stage, or hyperparameter tuning can be considered.<\/p>\n<p>In the future, I plan to cover various natural language processing problems and conduct advanced courses utilizing the Hugging Face Transformers library, so I appreciate your interest. Thank you!<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In recent years, the field of Natural Language Processing (NLP) has made significant advancements. At the center of this is Deep Learning and Transformer models, particularly Hugging Face&#8216;s Transformers library, which is widely used by many researchers and developers. In this article, we will explore how to train and evaluate a text classification model using &hellip; <a href=\"https:\/\/atmokpo.com\/w\/36199\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Using Hugging Face Transformers, Classification Report&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[108],"tags":[],"class_list":["post-36199","post","type-post","status-publish","format-standard","hentry","category---en"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Using Hugging Face Transformers, Classification Report - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/36199\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Using Hugging Face Transformers, Classification Report - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"In recent years, the field of Natural Language Processing (NLP) has made significant advancements. At the center of this is Deep Learning and Transformer models, particularly Hugging Face&#8216;s Transformers library, which is widely used by many researchers and developers. In this article, we will explore how to train and evaluate a text classification model using &hellip; \ub354 \ubcf4\uae30 &quot;Using Hugging Face Transformers, Classification Report&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/36199\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:46:34+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/36199\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36199\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Using Hugging Face Transformers, Classification Report\",\"datePublished\":\"2024-11-01T09:46:34+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36199\/\"},\"wordCount\":545,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Using Hugging Face\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/36199\/\",\"url\":\"https:\/\/atmokpo.com\/w\/36199\/\",\"name\":\"Using Hugging Face Transformers, Classification Report - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:46:34+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36199\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/36199\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/36199\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Using Hugging Face Transformers, Classification Report\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Using Hugging Face Transformers, Classification Report - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/36199\/","og_locale":"ko_KR","og_type":"article","og_title":"Using Hugging Face Transformers, Classification Report - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"In recent years, the field of Natural Language Processing (NLP) has made significant advancements. At the center of this is Deep Learning and Transformer models, particularly Hugging Face&#8216;s Transformers library, which is widely used by many researchers and developers. In this article, we will explore how to train and evaluate a text classification model using &hellip; \ub354 \ubcf4\uae30 \"Using Hugging Face Transformers, Classification Report\"","og_url":"https:\/\/atmokpo.com\/w\/36199\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:46:34+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/36199\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/36199\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Using Hugging Face Transformers, Classification Report","datePublished":"2024-11-01T09:46:34+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/36199\/"},"wordCount":545,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Using Hugging Face"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/36199\/","url":"https:\/\/atmokpo.com\/w\/36199\/","name":"Using Hugging Face Transformers, Classification Report - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:46:34+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/36199\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/36199\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/36199\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Using Hugging Face Transformers, Classification Report"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36199","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=36199"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36199\/revisions"}],"predecessor-version":[{"id":36200,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36199\/revisions\/36200"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=36199"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=36199"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=36199"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}