Hugging Face 情感分析入门教程

原标题:Getting Started with Sentiment Analysis using Python
32AI 研判分

该文章是一篇面向初学者的 Python 情感分析入门指南,介绍了如何使用 Hugging Face 生态工具快速实现文本情感分类。内容涵盖基础概念、代码示例及社区资源链接,旨在降低 NLP 技术的使用门槛。

报道正文

本文目录17 个章节

返回文章列表

使用 Python 入门情感分析

发布于 2022 年 2 月 2 日 在 GitHub 上更新 点赞 76

Federico Pascual federicopascual

情感分析是一种根据文本的情感倾向对数据进行自动标记的过程,例如正面、负面和中性。情感分析使企业能够大规模地分析数据、洞察趋势并实现流程自动化。

过去,情感分析通常仅限于研究人员、机器学习工程师或具备自然语言处理经验的数据科学家使用。然而,近年来 AI 社区构建了强大的工具,让机器学习的门槛大幅降低,实现了技术普惠。如今,即使没有任何机器学习经验,你也能通过几行代码轻松上手情感分析!🤯

在本指南中,你将学习如何使用 Python 开始情感分析之旅,内容包括:

  1. 什么是情感分析?
  2. 如何使用预训练的情感分析模型(Python)
  3. 如何构建自己的情感分析模型
  4. 如何使用情感分析来解读推文

让我们开始吧!🚀

1. 什么是情感分析?

情感分析是一种 自然语言处理 技术,用于识别给定文本的情感极性。情感分析有多种形式,其中最广泛使用的技术之一是将数据标记为正面、负面和中性。例如,我们来看看以下提及 @VerizonSupport 的推文:

  • "dear @verizonsupport your service is straight 💩 in dallas.. been with y’all over a decade and this is all time low for y’all. i’m talking no internet at all." → 会被标记为“负面”。
  • "@verizonsupport ive sent you a dm" → 会被标记为“中性”。
  • "thanks to michelle et al at @verizonsupport who helped push my no-show-phone problem along. order canceled successfully and ordered this for pickup today at the apple store in the mall." → 会被标记为“正面”。

情感分析能够以大规模、实时的方式处理数据。例如,你想分析成千上万条推文、产品评论或支持工单吗?与其手动梳理这些数据,不如使用情感分析来自动了解人们如何谈论特定话题,获取数据驱动决策的洞察,并自动化业务流程。

情感分析广泛应用于各种场景,例如:

  • 分析社交媒体提及内容,以了解人们如何评价你的品牌与竞争对手。
  • 分析调查反馈和产品评论,快速洞察客户对你产品的喜好与不满。
  • 实时分析传入的支持工单,识别愤怒的客户并采取相应措施以防止客户流失。

2. 如何使用 Python 调用预训练的情感分析模型

既然我们已经了解了什么是情感分析,接下来就可以动手体验一些情感分析模型了!🎉

在 Hugging Face Hub 上,我们正在构建最大的公开可用模型和数据集集合,旨在推动机器学习的普及 🚀。在 Hub 中,你可以找到由 AI 社区分享的超过 27,000 个模型,这些模型在情感分析、目标检测、文本生成、语音识别等任务上均达到了最先进(state-of-the-art)的性能。Hub 免费使用,且大多数模型都提供了小部件(widget),允许你直接在浏览器中进行测试!

Hub 上有超过 215 个情感分析模型 可供公开使用,将其集成到 Python 中只需 5 行代码:

PYTHON
pip install -q transformers
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["I love you", "I hate you"]
sentiment_pipeline(data)

这段代码片段使用 pipeline 类 对 Hub 中可用的模型进行预测。它使用情感分析默认模型来分析文本列表 data,并输出以下结果:

PYTHON
[{'label': 'POSITIVE', 'score': 0.9998},
 {'label': 'NEGATIVE', 'score': 0.9991}]

你可以通过指定模型名称,使用更适合你的语言或应用场景的特定情感分析模型。例如,如果你需要一个用于推文的情感分析模型,可以指定该 model id:

PYTHON
specific_model = pipeline(model="finiteautomata/bertweet-base-sentiment-analysis")
specific_model(data)

你可以使用这个 Colab notebook 用自己的数据测试这些模型:

以下是 Hub 上一些受欢迎且我们推荐尝试的情感分析模型:

  • Twitter-roberta-base-sentiment 是一个基于 roBERTa 的模型,在约 5800 万条推文上进行训练,并针对情感分析进行了微调。微调是指获取一个预训练的大语言模型(在本例中为 roBERTa),然后使用额外的训练数据对其进行调整,使其能够执行另一项类似的任务(例如情感分析)。
  • Bert-base-multilingual-uncased-sentiment 是一个针对六种语言的产品评论情感分析进行微调的模型:英语、荷兰语、德语、法语、西班牙语和意大利语。
  • Distilbert-base-uncased-emotion 是一个针对检测文本中的情绪进行微调的模型,包括悲伤、快乐、爱、愤怒、恐惧和惊讶。

你是否对西班牙语、法语、意大利语或德语等语言的情感分析感兴趣?在 Hub 上,你可以找到许多针对不同用例微调的模型,支持约 28 种语言。你可以在这里查看完整的情感分析模型列表,并在左侧按你感兴趣的语言进行筛选。

3. 构建你自己的情感分析模型

使用 Hub 上公开可用的预训练模型是快速上手情感分析的好方法。这些模型采用 Transformer 等深度学习架构,在情感分析及其他机器学习任务中达到了最先进(state-of-the-art)的性能。不过,你也可以使用自己的数据对模型进行微调,以进一步提升情感分析结果,并在特定用例中获得额外的准确率提升。

让我们开始吧!

a. 使用 Python 微调模型

在本教程中,你将使用 IMDB 数据集来微调一个用于情感分析的 DistilBERT 模型。

IMDB 数据集包含 25,000 条带有情感标签的电影评论用于训练模型,以及另外 25,000 条评论用于测试模型。DistilBERT 是 BERT 的一个更小、更快且成本更低的版本。它比 BERT 小 40%,运行速度快 60%,同时保留了 BERT 95% 以上的性能。你将使用 IMDB 数据集微调一个能够判断电影评论是正面还是负面的 DistilBERT 模型。一旦训练完成,你就可以用它来分析新数据了!⚡️

我们已创建了此 Notebook,以便你在 Google Colab 中通过本教程直接使用。

1. 启用 GPU 并安装依赖项

作为第一步,让我们设置 Google Colab 使用 GPU(而非 CPU)来大幅加快模型训练速度。你可以通过点击菜单中的 'Runtime' > 'Change runtime type',并将硬件加速器选择为 'GPU' 来实现这一点。完成后,你应该运行以下代码来检查 Notebook 中是否可用 GPU:

PYTHON
import torch
torch.cuda.is_available()

然后,安装本教程中将使用的库:

PYTHON
!pip install datasets transformers huggingface_hub

[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]

You should also install git-lfs to use git in our model repository:

PYTHON
!apt-get install git-lfs

2. Preprocess data

You need data to fine-tune DistilBERT for sentiment analysis. So, let's use 🤗Datasets library to download and preprocess the IMDB dataset so you can then use this data for training your model:

PYTHON
from datasets import load_dataset
imdb = load_dataset("imdb")

IMDB is a huge dataset, so let's create smaller datasets to enable faster training and testing:

PYTHON
small_train_dataset = imdb["train"].shuffle(seed=42).select([i for i in list(range(3000))])
small_test_dataset = imdb["test"].shuffle(seed=42).select([i for i in list(range(300))])

To preprocess our data, you will use DistilBERT tokenizer:

PYTHON
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")

Next, you will prepare the text inputs for the model for both splits of our dataset (training and test) by using the map method:

PYTHON
def preprocess_function(examples):
   return tokenizer(examples["text"], truncation=True)

tokenized_train = small_train_dataset.map(preprocess_function, batched=True)
tokenized_test = small_test_dataset.map(preprocess_function, batched=True)

To speed up training, let's use a data_collator to convert your training samples to PyTorch tensors and concatenate them with the correct amount of padding:

PYTHON
from transformers import DataCollatorWithPadding
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)

3. Training the model

Now that the preprocessing is done, you can go ahead and train your model 🚀

You will be throwing away the pretraining head of the DistilBERT model and replacing it with a classification head fine-tuned for sentiment analysis. This enables you to transfer the knowledge from DistilBERT to your custom model 🔥

For training, you will be using the Trainer API, which is optimized for fine-tuning Transformers🤗 models such as DistilBERT, BERT and RoBERTa.

First, let's define DistilBERT as your base model:

PYTHON
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)

Then, let's define the metrics you will be using to evaluate how good your fine-tuned model is (accuracy and f1 score):

PYTHON
import numpy as np
from datasets import load_metric

def compute_metrics(eval_pred):
   load_accuracy = load_metric("accuracy")
   load_f1 = load_metric("f1")

logits, labels = eval_pred
   predictions = np.argmax(logits, axis=-1)
   accuracy = load_accuracy.compute(predictions=predictions, references=labels)["accuracy"]
   f1 = load_f1.compute(predictions=predictions, references=labels)["f1"]
   return {"accuracy": accuracy, "f1": f1}

Next, let's login to your Hugging Face account so you can manage your model repositories. notebook_login will launch a widget in your notebook where you'll need to add your Hugging Face token:

PYTHON
from huggingface_hub import notebook_login
notebook_login()

You are almost there! Before training our model, you need to define the training arguments and define a Trainer with all the objects you constructed up to this point:

PYTHON
from transformers import TrainingArguments, Trainer

repo_name = "finetuning-sentiment-model-3000-samples"

training_args = TrainingArguments(
   output_dir=repo_name,
   learning_rate=2e-5,
   per_device_train_batch_size=16,
   per_device_eval_batch_size=16,
   num_train_epochs=2,
   weight_decay=0.01,
   save_strategy="epoch",
   push_to_hub=True,
)

trainer = Trainer(
   model=model,
   args=training_args,
   train_dataset=tokenized_train,
   eval_dataset=tokenized_test,
   tokenizer=tokenizer,
   data_collator=data_collator,
   compute_metrics=compute_metrics,
)

Now, it's time to fine-tune the model on the sentiment analysis dataset! 🙌 You just have to call the train() method of your Trainer:

PYTHON
trainer.train()

And voila! You fine-tuned a DistilBERT model for sentiment analysis! 🎉

Training time depends on the hardware you use and the number of samples in the dataset. In our case, it took almost 10 minutes using a GPU and fine-tuning the model with 3,000 samples. The more samples you use for training your model, the more accurate it will be but training could be significantly slower.

Next, let's compute the evaluation metrics to see how good your model is:

PYTHON
trainer.evaluate()

In our case, we got 88% accuracy and 89% f1 score. Quite good for a sentiment analysis model just trained with 3,000 samples!

4. Analyzing new data with the model

Now that you have trained a model for sentiment analysis, let's use it to analyze new data and get 🤖 predictions! This unlocks the power of machine learning; using a model to automatically analyze data at scale, in real-time ⚡️

First, let's upload the model to the Hub:

PYTHON
trainer.push_to_hub()

Now that you have pushed the model to the Hub, you can use it pipeline class to analyze two new movie reviews and see how your model predicts its sentiment with just two lines of code 🤯:

PYTHON
from transformers import pipeline

sentiment_model = pipeline(model="federicopascual/finetuning-sentiment-model-3000-samples")
sentiment_model(["I love this movie", "This movie sucks!"])

These are the predictions from our model:

PYTHON
[{'label': 'LABEL_1', 'score': 0.9558},
 {'label': 'LABEL_0', 'score': 0.9413}]

In the IMDB dataset, Label 1 means positive and Label 0 is negative. Quite good! 🔥

b. Training a sentiment model with AutoNLP

AutoNLP is a tool to train state-of-the-art machine learning models without code. It provides a friendly and easy-to-use user interface, where you can train custom models by simply uploading your data. AutoNLP will automatically fine-tune various pre-trained models with your data, take care of the hyperparameter tuning and find the best model for your use case. All models trained with AutoNLP are deployed and ready for production.

Training a sentiment analysis model using AutoNLP is super easy and it just takes a few clicks 🤯. Let's give it a try!

As a first step, let's get some data! You'll use Sentiment140, a popular sentiment analysis dataset that consists of Twitter messages labeled with 3 sentiments: 0 (negative), 2 (neutral), and 4 (positive). The dataset is quite big; it contains 1,600,000 tweets. As you don't need this amount of data to get your feet wet with AutoNLP and train your first models, we have prepared a smaller version of the Sentiment140 dataset with 3,000 samples that you can download from here. This is how the dataset looks like:

Sentiment 140 dataset

Next, let's create a new project on AutoNLP to train 5 candidate models:

Creating a new project on AutoNLP

Then, upload the dataset and map the text column and target columns:

Adding a dataset to AutoNLP

Once you add your dataset, go to the "Trainings" tab and accept the pricing to start training your models. AutoNLP pricing can be as low as $10 per model:

Adding a dataset to AutoNLP

After a few minutes, AutoNLP has trained all models, showing the performance metrics for all of them:

Trained sentiment analysis models by AutoNLP

The best model has 77.87% accuracy 🔥 Pretty good for a sentiment analysis model for tweets trained with just 3,000 samples!

All these models are automatically uploaded to the Hub and deployed for production. You can use any of these models to start analyzing new data right away by using the pipeline class as shown in previous sections of this post.

4. Analyzing Tweets with Sentiment Analysis and Python

In this last section, you'll take what you have learned so far in this post and put it into practice with a fun little project: analyzing tweets about NFTs with sentiment analysis!

First, you'll use Tweepy, an easy-to-use Python library for getting tweets mentioning #NFTs using the Twitter API. Then, you will use a sentiment analysis model from the 🤗Hub to analyze these tweets. Finally, you will create some visualizations to explore the results and find some interesting insights.

You can use this notebook to follow this tutorial. Let’s jump into it!

1. Install dependencies

First, let's install all the libraries you will use in this tutorial:

文本
!pip install -q transformers tweepy wordcloud matplotlib

2. Set up Twitter API credentials

Next, you will set up the credentials for interacting with the Twitter API. First, you'll need to sign up for a developer account on Twitter. Then, you have to create a new project and connect an app to get an API key and token. You can follow this step-by-step guide to get your credentials.

Once you have the API key and token, let's create a wrapper with Tweepy for interacting with the Twitter API:

PYTHON
import tweepy

consumer_key = "XXXXXX"
consumer_secret = "XXXXXX"

auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

3. Search for tweets using Tweepy

At this point, you are ready to start using the Twitter API to collect tweets 🎉. You will use Tweepy Cursor to extract 1,000 tweets mentioning #NFTs:

PYTHON

def limit_handled(cursor):
   while True:
       try:
           yield cursor.next()
       except tweepy.RateLimitError:
           print('Reached rate limite. Sleeping for >15 minutes')
           time.sleep(15 * 61)
       except StopIteration:
           break

query = '#NFTs'
query = query + ' -filter:retweets'

count = 1000

search = limit_handled(tweepy.Cursor(api.search,
                       q=query,
                       tweet_mode='extended',
                       lang='en',
                       result_type="recent").items(count))

4. Run sentiment analysis on the tweets

Now you can put our new skills to work and run sentiment analysis on your data! 🎉

You will use one of the models available on the Hub fine-tuned for sentiment analysis of tweets. Like in other sections of this post, you will use the pipeline class to make the predictions with this model:

PYTHON
from transformers import pipeline

sentiment_analysis = pipeline(model="finiteautomata/bertweet-base-sentiment-analysis")

tweets = []
for tweet in search:
   try:
     content = tweet.full_text
     sentiment = sentiment_analysis(content)
     tweets.append({'tweet': content, 'sentiment': sentiment[0]['label']})

except:
     pass

5. Explore the results of sentiment analysis

How are people talking about NFTs on Twitter? Are they talking mostly positively or negatively? Let's explore the results of the sentiment analysis to find out!

First, let's load the results on a dataframe and see examples of tweets that were labeled for each sentiment:

PYTHON
import pandas as pd

df = pd.DataFrame(tweets)
pd.set_option('display.max_colwidth', None)

display(df[df["sentiment"] == 'POS'].head(1))
display(df[df["sentiment"] == 'NEU'].head(1))
display(df[df["sentiment"] == 'NEG'].head(1))

Output:

YAML
Tweet: @NFTGalIery Warm, exquisite and elegant palette of charming beauty Its price is 2401 ETH. \nhttps://t.co/Ej3BfVOAqc\n#NFTs #NFTartists #art #Bitcoin #Crypto #OpenSeaNFT #Ethereum #BTC	Sentiment: POS

Tweet: How much our followers made on #Crypto in December:\n#DAPPRadar airdrop — $200\nFree #VPAD tokens — $800\n#GasDAO airdrop — up to $1000\nStarSharks_SSS IDO — $3500\nCeloLaunch IDO — $3000\n12 Binance XMas #NFTs — $360 \nTOTAL PROFIT: $8500+\n\nJoin and earn with us https://t.co/fS30uj6SYx	Sentiment: NEU

Tweet: Stupid guy #2\nhttps://t.co/8yKzYjCYIl\n\n#NFT #NFTs #nftcollector #rarible https://t.co/O4V19gMmVk		Sentiment: NEG

Then, let's see how many tweets you got for each sentiment and visualize these results:

PYTHON

sentiment_counts = df.groupby(['sentiment']).size()
print(sentiment_counts)

fig = plt.figure(figsize=(6,6), dpi=100)
ax = plt.subplot(111)
sentiment_counts.plot.pie(ax=ax, autopct='%1.1f%%', startangle=270, fontsize=12, label="")

Interestingly, most of the tweets about NFTs are positive (56.1%) and almost none are negative (2.0%):

Sentiment analysis result of NFTs tweets

Finally, let's see what words stand out for each sentiment by creating a word cloud:

PYTHON
from wordcloud import WordCloud
from wordcloud import STOPWORDS

positive_tweets = df['tweet'][df["sentiment"] == 'POS']
stop_words = ["https", "co", "RT"] + list(STOPWORDS)
positive_wordcloud = WordCloud(max_font_size=50, max_words=100, background_color="white", stopwords = stop_words).generate(str(positive_tweets))
plt.figure()
plt.title("Positive Tweets - Wordcloud")
plt.imshow(positive_wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

negative_tweets = df['tweet'][df["sentiment"] == 'NEG']
stop_words = ["https", "co", "RT"] + list(STOPWORDS)
negative_wordcloud = WordCloud(max_font_size=50, max_words=100, background_color="white", stopwords = stop_words).generate(str(negative_tweets))
plt.figure()
plt.title("Negative Tweets - Wordcloud")
plt.imshow(negative_wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

Some of the words associated with positive tweets include Discord, Ethereum, Join, Mars4 and Shroom:

Word cloud for positive tweets

In contrast, words associated with negative tweets include: cookies chaos, Solana, and OpenseaNFT:

Word cloud for negative tweets

And that is it! With just a few lines of python code, you were able to collect tweets, analyze them with sentiment analysis and create some cool visualizations to analyze the results! Pretty cool, huh?

5. Wrapping up

Sentiment analysis with Python has never been easier! Tools such as 🤗Transformers and the 🤗Hub makes sentiment analysis accessible to all developers. You can use open source, pre-trained models for sentiment analysis in just a few lines of code 🔥

Do you want to train a custom model for sentiment analysis with your own data? Easy peasy! You can fine-tune a model using Trainer API to build on top of large language models and get state-of-the-art results. If you want something even easier, you can use AutoNLP to train custom machine learning models by simply uploading data.

If you have questions, the Hugging Face community can help answer and/or benefit from, please ask them in the Hugging Face forum. Also, join our discord server to talk with us and with the Hugging Face community.