Noemi  Sanford

Noemi Sanford

1592189160

Choosing a Prediction Modeling Technique

We encounter the results of prediction models everyday. We get offered the right incentive to buy a product. We get a text from the bank when something strange is happening with our accounts. And we rarely have to see spam in our inboxes. This is all thanks to the models built on the data that we generate everyday.

Read on to learn more about the business of prediction modeling and how you can develop and train your own.

Is predictive modeling machine learning?
Predictive modeling and machine learning are related, but have slightly different definitions. Predictive modeling is often defined as the use of statistical models to predict outcomes. Machine learning is a subset of artificial intelligence that refers to the use of computers to construct predictive models. In more recent years, however, the terms have been used synonymously.

#machine learning

What is GEEK

Buddha Community

Choosing a Prediction Modeling Technique
Ian  Robinson

Ian Robinson

1623223443

Predictive Modeling in Data Science

Predictive modeling is an integral tool used in the data science world — learn the five primary predictive models and how to use them properly.

Predictive modeling in data science is used to answer the question “What is going to happen in the future, based on known past behaviors?” Modeling is an essential part of data science, and it is mainly divided into predictive and preventive modeling. Predictive modeling, also known as predictive analytics, is the process of using data and statistical algorithms to predict outcomes with data models. Anything from sports outcomes, television ratings to technological advances, and corporate economies can be predicted using these models.

Top 5 Predictive Models

  1. Classification Model: It is the simplest of all predictive analytics models. It puts data in categories based on its historical data. Classification models are best to answer “yes or no” types of questions.
  2. Clustering Model: This model groups data points into separate groups, based on similar behavior.
  3. **Forecast Model: **One of the most widely used predictive analytics models. It deals with metric value prediction, and this model can be applied wherever historical numerical data is available.
  4. Outliers Model: This model, as the name suggests, is oriented around exceptional data entries within a dataset. It can identify exceptional figures either by themselves or in concurrence with other numbers and categories.
  5. Time Series Model: This predictive model consists of a series of data points captured, using time as the input limit. It uses the data from previous years to develop a numerical metric and predicts the next three to six weeks of data using that metric.

#big data #data science #predictive analytics #predictive analysis #predictive modeling #predictive models

Mckenzie  Osiki

Mckenzie Osiki

1623906928

How To Use “Model Stacking” To Improve Machine Learning Predictions

What is Model Stacking?

Model Stacking is a way to improve model predictions by combining the outputs of multiple models and running them through another machine learning model called a meta-learner. It is a popular strategy used to win kaggle competitions, but despite their usefulness they’re rarely talked about in data science articles — which I hope to change.

Essentially a stacked model works by running the output of multiple models through a “meta-learner” (usually a linear regressor/classifier, but can be other models like decision trees). The meta-learner attempts to minimize the weakness and maximize the strengths of every individual model. The result is usually a very robust model that generalizes well on unseen data.

The architecture for a stacked model can be illustrated by the image below:

#tensorflow #neural-networks #model-stacking #how to use “model stacking” to improve machine learning predictions #model stacking #machine learning

Iara  Simões

Iara Simões

1657268760

5 Maneiras de Realizar Análise de Sentimentos em Python

Quer você fale de Twitter, Goodreads ou Amazon – dificilmente existe um espaço digital não saturado com as opiniões das pessoas. No mundo de hoje, é crucial que as organizações se aprofundem nessas opiniões e obtenham insights sobre seus produtos ou serviços. No entanto, esses dados existem em quantidades tão surpreendentes que medi-los manualmente é uma busca quase impossível. É aqui que mais um benefício da Data Science entra em jogo  Análise de Sentimentos . Neste artigo, exploraremos o que a análise de sentimentos abrange e as várias maneiras de implementá-la em Python.

O que é Análise de Sentimentos?

A Análise de Sentimento é um caso de uso do Processamento de Linguagem Natural (NLP) e se enquadra na categoria de classificação de texto . Simplificando, a Análise de Sentimentos envolve a classificação de um texto em vários sentimentos, como positivo ou negativo, Feliz, Triste ou Neutro, etc. texto. Isso também é conhecido como Mineração de Opinião .

Vejamos como uma rápida pesquisa no Google define a Análise de Sentimento:

definição de análise de sentimento

Obtendo Insights e Tomando Decisões com Análise de Sentimentos

Bem, agora acho que estamos um pouco acostumados com o que é a análise de sentimentos. Mas qual é o seu significado e como as organizações se beneficiam dele? Vamos tentar explorar o mesmo com um exemplo. Suponha que você inicie uma empresa que vende perfumes em uma plataforma online. Você coloca uma grande variedade de fragrâncias por aí e logo os clientes começam a aparecer. Depois de algum tempo, você decide mudar a estratégia de preços dos perfumes - você planeja aumentar os preços das fragrâncias populares e, ao mesmo tempo, oferecer descontos nas impopulares . Agora, para determinar quais fragrâncias são populares, você começa a analisar as avaliações dos clientes de todas as fragrâncias. Mas você está preso! Eles são tantos que você não pode passar por todos eles em uma vida. É aqui que a análise de sentimentos pode tirá-lo do poço.

Você simplesmente reúne todas as avaliações em um só lugar e aplica a análise de sentimentos a elas. A seguir, uma representação esquemática da análise de sentimentos nas resenhas de três fragrâncias de perfumes – Lavanda, Rosa e Limão. (Observe que essas revisões podem ter ortografia, gramática e pontuação incorretas, como nos cenários do mundo real)

análise de sentimentos

A partir desses resultados, podemos ver claramente que:

Fragrance-1 (Lavender) tem avaliações altamente positivas dos clientes, o que indica que sua empresa pode aumentar seus preços devido à sua popularidade.

Fragrance-2 (Rose) tem uma perspectiva neutra entre o cliente, o que significa que sua empresa não deve alterar seus preços .

O Fragrance-3 (Lemon) tem um sentimento geral negativo associado a ele – portanto, sua empresa deve considerar oferecer um desconto para equilibrar a balança.

Este foi apenas um exemplo simples de como a análise de sentimentos pode ajudá-lo a obter insights sobre seus produtos/serviços e ajudar sua organização a tomar decisões.

Casos de uso de análise de sentimento

Acabamos de ver como a análise de sentimentos pode capacitar as organizações com insights que podem ajudá-las a tomar decisões baseadas em dados. Agora, vamos dar uma olhada em mais alguns casos de uso de análise de sentimentos.

  1. Monitoramento de mídia social para gerenciamento de marca: as marcas podem usar a análise de sentimentos para avaliar a perspectiva pública de sua marca. Por exemplo, uma empresa pode reunir todos os Tweets com a menção ou tag da empresa e realizar uma análise de sentimentos para conhecer a perspectiva pública da empresa.
  2. Análise de produto/serviço: as marcas/organizações podem realizar análises de sentimento nas avaliações dos clientes para ver o desempenho de um produto ou serviço no mercado e tomar decisões futuras de acordo.
  3. Previsão do preço das ações: prever se as ações de uma empresa vão subir ou descer é crucial para os investidores. Pode-se determinar o mesmo realizando uma análise de sentimento nas manchetes de notícias de artigos que contenham o nome da empresa. Se as manchetes de notícias relativas a uma determinada organização tiverem um sentimento positivo – seus preços de ações devem subir e vice-versa.

Maneiras de executar a análise de sentimentos em Python

O Python é uma das ferramentas mais poderosas quando se trata de realizar tarefas de ciência de dados — ele oferece várias maneiras de realizar  análises de sentimentos . Os mais populares estão listados aqui:

  1. Usando o Blob de Texto
  2. Usando Vader
  3. Usando modelos baseados em vetorização Bag of Words
  4. Usando modelos baseados em LSTM
  5. Usando modelos baseados em transformador

Vamos mergulhar fundo neles um por um.

Nota: Para fins de demonstração dos métodos 3 e 4 (Usando Modelos Baseados em Vetorização Bag of Words e Usando Modelos Baseados em LSTM) foi utilizada a análise de sentimentos . Compreende mais de 5.000 excretos de texto rotulados como positivos, negativos ou neutros. O conjunto de dados está sob a licença Creative Commons.

Usando o Blob de Texto

Text Blob é uma biblioteca Python para processamento de linguagem natural. Usar o Text Blob para análise de sentimentos é bastante simples. Ele recebe texto como entrada e pode retornar polaridade e subjetividade como saída.

A polaridade determina o sentimento do texto. Seus valores estão em [-1,1] onde -1 denota um sentimento altamente negativo e 1 denota um sentimento altamente positivo.

A subjetividade determina se uma entrada de texto é uma informação factual ou uma opinião pessoal. O seu valor situa-se entre [0,1] onde um valor mais próximo de 0 denota uma informação factual e um valor mais próximo de 1 denota uma opinião pessoal.

Instalação :

pip install textblob

Importando Blob de Texto:

from textblob import TextBlob

Implementação de código para análise de sentimento usando blob de texto:

Escrever código para análise de sentimentos usando TextBlob é bastante simples. Basta importar o objeto TextBlob e passar o texto a ser analisado com os devidos atributos da seguinte forma:

from textblob import TextBlob
text_1 = "The movie was so awesome."
text_2 = "The food here tastes terrible."#Determining the Polarity 
p_1 = TextBlob(text_1).sentiment.polarity
p_2 = TextBlob(text_2).sentiment.polarity#Determining the Subjectivity
s_1 = TextBlob(text_1).sentiment.subjectivity
s_2 = TextBlob(text_2).sentiment.subjectivityprint("Polarity of Text 1 is", p_1)
print("Polarity of Text 2 is", p_2)
print("Subjectivity of Text 1 is", s_1)
print("Subjectivity of Text 2 is", s_2)

Resultado:

Polarity of Text 1 is 1.0 
Polarity of Text 2 is -1.0 
Subjectivity of Text 1 is 1.0 
Subjectivity of Text 2 is 1.0

Usando VADER

O VADER (Valence Aware Dictionary and sEntiment Reasoner) é um analisador de sentimentos baseado em regras que foi treinado em texto de mídia social. Assim como o Text Blob, seu uso em Python é bastante simples. Veremos seu uso na implementação de código com um exemplo daqui a pouco.

Instalação:

pip install vaderSentiment

Importando a classe SentimentIntensityAnalyzer do Vader:

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

Código para análise de sentimentos usando o Vader:

Primeiramente, precisamos criar um objeto da classe SentimentIntensityAnalyzer; então precisamos passar o texto para a função polarity_scores() do objeto da seguinte forma:

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
sentiment = SentimentIntensityAnalyzer()
text_1 = "The book was a perfect balance between wrtiting style and plot."
text_2 =  "The pizza tastes terrible."
sent_1 = sentiment.polarity_scores(text_1)
sent_2 = sentiment.polarity_scores(text_2)
print("Sentiment of text 1:", sent_1)
print("Sentiment of text 2:", sent_2)

Saída :

Sentiment of text 1: {'neg': 0.0, 'neu': 0.73, 'pos': 0.27, 'compound': 0.5719} 
Sentiment of text 2: {'neg': 0.508, 'neu': 0.492, 'pos': 0.0, 'compound': -0.4767}

Como podemos ver, um objeto VaderSentiment retorna um dicionário de pontuações de sentimento para o texto a ser analisado.

Usando modelos baseados em vetorização Bag of Words

Nas duas abordagens discutidas até agora, ou seja, Text Blob e Vader, simplesmente usamos bibliotecas Python para realizar a análise de sentimentos. Agora discutiremos uma abordagem na qual treinaremos nosso próprio modelo para a tarefa. As etapas envolvidas na análise de sentimentos usando o método Bag of Words Vectorization são as seguintes:

  1. Pré-processe o texto dos dados de treinamento (o pré-processamento de texto envolve Normalização, Tokenização, Remoção de Stopwords e Stemming/Lematization.)
  2. Crie um Bag of Words para os dados de texto pré-processados ​​usando a abordagem Count Vectorization ou TF-IDF Vectorization.
  3. Treine um modelo de classificação adequado nos dados processados ​​para classificação de sentimentos.

Código para análise de sentimentos usando a abordagem de vetorização Bag of Words:

Para construir um modelo de análise de sentimento usando a Abordagem de Vetorização BOW, precisamos de um conjunto de dados rotulado. Como afirmado anteriormente, o conjunto de dados usado para esta demonstração foi obtido do Kaggle. Nós simplesmente usamos o vetorizador de contagem do sklearn para criar o BOW. Após, treinamos um classificador Multinomial Naive Bayes, para o qual foi obtido um escore de precisão de 0,84.

O conjunto de dados pode ser obtido aqui .

#Loading the Dataset
import pandas as pd
data = pd.read_csv('Finance_data.csv')
#Pre-Prcoessing and Bag of Word Vectorization using Count Vectorizer
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(stop_words='english',ngram_range = (1,1),tokenizer = token.tokenize)
text_counts = cv.fit_transform(data['sentences'])
#Splitting the data into trainig and testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(text_counts, data['feedback'], test_size=0.25, random_state=5)
#Training the model
from sklearn.naive_bayes import MultinomialNB
MNB = MultinomialNB()
MNB.fit(X_train, Y_train)
#Caluclating the accuracy score of the model
from sklearn import metrics
predicted = MNB.predict(X_test)
accuracy_score = metrics.accuracy_score(predicted, Y_test)
print("Accuracuy Score: ",accuracy_score)

Saída :

Accuracuy Score:  0.9111675126903553

O classificador treinado pode ser usado para prever o sentimento de qualquer entrada de texto.

Usando modelos baseados em LSTM

Embora tenhamos conseguido obter uma pontuação de precisão decente com o método Bag of Words Vectorization, ele pode não produzir os mesmos resultados ao lidar com conjuntos de dados maiores. Isso dá origem à necessidade de empregar modelos baseados em deep learning para o treinamento do modelo de análise de sentimentos.

Para tarefas de PNL, geralmente usamos modelos baseados em RNN, pois são projetados para lidar com dados sequenciais. Aqui, vamos treinar um modelo LSTM (Long Short Term Memory) usando o TensorFlow com Keras . As etapas para realizar a análise de sentimento usando modelos baseados em LSTM são as seguintes:

  1. Pré-processe o texto dos dados de treinamento (o pré-processamento de texto envolve Normalização, Tokenização, Remoção de Stopwords e Stemming/Lematization.)
  2. Importe o Tokenizer de Keras.preprocessing.text e crie seu objeto. Ajuste o tokenizer em todo o texto de treinamento (para que o Tokenizer seja treinado no vocabulário de dados de treinamento). Embeddings de texto gerados usando o método text_to_sequence() do Tokenizer e armazená-los após preenchê-los com um comprimento igual. (Embeddings são representações numéricas/vetorizadas de texto. Como não podemos alimentar nosso modelo com os dados de texto diretamente, primeiro precisamos convertê-los em embeddings)
  3. Depois de gerar os embeddings, estamos prontos para construir o modelo. Construímos o modelo usando o TensorFlow — adicionamos Input, LSTM e camadas densas a ele. Adicione dropouts e ajuste os hiperparâmetros para obter uma pontuação de precisão decente. Geralmente, tendemos a usar funções de ativação ReLU ou LeakyReLU nas camadas internas dos modelos LSTM, pois evita o problema do gradiente de fuga. Na camada de saída, usamos a função de ativação Softmax ou Sigmoid.

Código para análise de sentimentos usando abordagem de modelo baseada em LSTM:

Aqui, usamos o mesmo conjunto de dados que usamos no caso da abordagem BOW. Uma precisão de treinamento de 0,90 foi obtida.

#Importing necessary libraries
import nltk
import pandas as pd
from textblob import Word
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split 
#Loading the dataset
data = pd.read_csv('Finance_data.csv')
#Pre-Processing the text 
def cleaning(df, stop_words):
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x.lower() for x in x.split()))
    # Replacing the digits/numbers
    df['sentences'] = df['sentences'].str.replace('d', '')
    # Removing stop words
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x for x in x.split() if x not in stop_words))
    # Lemmatization
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join([Word(x).lemmatize() for x in x.split()]))
    return df
stop_words = stopwords.words('english')
data_cleaned = cleaning(data, stop_words)
#Generating Embeddings using tokenizer
tokenizer = Tokenizer(num_words=500, split=' ') 
tokenizer.fit_on_texts(data_cleaned['verified_reviews'].values)
X = tokenizer.texts_to_sequences(data_cleaned['verified_reviews'].values)
X = pad_sequences(X)
#Model Building
model = Sequential()
model.add(Embedding(500, 120, input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(704, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(352, activation='LeakyReLU'))
model.add(Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics = ['accuracy'])
print(model.summary())
#Model Training
model.fit(X_train, y_train, epochs = 20, batch_size=32, verbose =1)
#Model Testing
model.evaluate(X_test,y_test)

Usando modelos baseados em transformador

Os modelos baseados em transformadores são uma das técnicas de processamento de linguagem natural mais avançadas. Eles seguem uma arquitetura baseada em Encoder-Decoder e empregam os conceitos de autoatenção para produzir resultados impressionantes. Embora sempre se possa construir um modelo de transformador do zero, é uma tarefa bastante tediosa. Assim, podemos usar modelos de transformadores pré-treinados disponíveis no Hugging Face . Hugging Face é uma comunidade de IA de código aberto que oferece uma infinidade de modelos pré-treinados para aplicativos de PNL. Esses modelos podem ser usados ​​como tal ou podem ser ajustados para tarefas específicas.

Instalação:

pip install transformers

Importando a classe SentimentIntensityAnalyzer do Vader:

import transformers

Código para análise de sentimentos usando modelos baseados em Transformer:

Para executar qualquer tarefa usando transformadores, primeiro precisamos importar a função pipeline dos transformadores. Então, um objeto da função pipeline é criado e a tarefa a ser executada é passada como um argumento (ou seja, análise de sentimento no nosso caso). Também podemos especificar o modelo que precisamos usar para realizar a tarefa. Aqui, como não mencionamos o modelo a ser usado, o modo destilaria-base-uncased-finetuned-sst-2-English é usado por padrão para análise de sentimentos. Você pode conferir a lista de tarefas e modelos disponíveis aqui .

from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["It was the best of times.", "t was the worst of times."]
sentiment_pipeline(data)Output:[{'label': 'POSITIVE', 'score': 0.999457061290741},  {'label': 'NEGATIVE', 'score': 0.9987301230430603}]

Conclusão

Nesta era em que os usuários podem expressar seus pontos de vista sem esforço e os dados são gerados em superfluidade em apenas frações de segundos - extrair insights desses dados é vital para as organizações tomarem decisões eficientes - e a Análise de Sentimentos prova ser a peça que faltava no quebra-cabeça!

Até agora, cobrimos em detalhes o que exatamente envolve a análise de sentimentos e os vários métodos que podemos usar para realizá-la em Python. Mas essas foram apenas algumas demonstrações rudimentares - você certamente deve ir em frente e mexer nos modelos e testá-los em seus próprios dados.

Fonte: https://www.analyticsvidhya.com/blog/2022/07/sentiment-analysis-using-python/ 

#python 

Pythonで感情分析を実行する5つの方法

Twitter、Goodreads、Amazonのいずれについて話しても、人々の意見で飽和していないデジタル空間はほとんどありません。今日の世界では、組織がこれらの意見を掘り下げて、自社の製品やサービスに関する洞察を得ることが重要です。ただし、このデータは、手動で測定することは不可能に近いほどの量で存在します。ここで、データサイエンスのもう1つの恩恵がもたらされます 感情分析。この記事では、感情分析に含まれるものと、Pythonでそれを実装するためのさまざまな方法について説明します。

感情分析とは何ですか?

感情分析自然言語処理(NLP)のユースケースであり、テキスト分類のカテゴリに分類されます。簡単に言うと、感情分析では、テキストをポジティブまたはネガティブ、ハッピー、悲しい、ニュートラルなどのさまざまな感情に分類します。したがって、感情分析の最終的な目標は、感情、感情、または感情の根底にある感情を解読することです。文章。これは、オピニオンマイニングとも呼ばれます。

クイックグーグル検索が感情分析をどのように定義するかを見てみましょう:

感情分析の定義

感情分析による洞察の獲得と意思決定

さて、今では、感情分析とは何かにある程度慣れていると思います。しかし、その重要性と、組織はそれからどのように利益を得るのでしょうか。例を挙げて同じことを試してみましょう。オンラインプラットフォームで香水を販売する会社を立ち上げたとします。さまざまなフレグランスを販売し、すぐに顧客が殺到し始めます。しばらくして、香水の価格戦略を変更することにしました。人気のあるフレグランスの価格を上げると同時に、人気のないフレグランスの割引を提供する予定です。 。ここで、人気のあるフレグランスを特定するために、すべてのフレグランスのカスタマーレビューを開始します。しかし、あなたは立ち往生しています!それらは非常に多いので、一生のうちにすべてを通過することはできません。これは、感情分析があなたをピットから追い出すことができる場所です。

すべてのレビューを1つの場所に集めて、感情分析を適用するだけです。以下は、香水の3つのフレグランス(ラベンダー、ローズ、レモン)のレビューに関する感情分析の概略図です。(これらのレビューには、実際のシナリオとは異なり、スペル、文法、句読点が正しくない可能性があることに注意してください)

感情分析

これらの結果から、次のことがはっきりとわかります。

Fragrance-1(Lavender)は顧客から非常に好意的なレビューを受けており、あなたの会社が人気を考えれば価格を上げることができることを示しています。

Fragrance-2(Rose)は、たまたま顧客の間で中立的な見通しを持っています。つまり、あなたの会社は価格を変更すべきではありません

Fragrance-3(Lemon)には、全体的にネガティブな感情があります。したがって、企業は、スケールのバランスをとるために、 Fragrance-3に割引を提供することを検討する必要があります。

これは、感情分析が製品/サービスへの洞察を得るのに役立ち、組織が意思決定を行うのにどのように役立つかを示す簡単な例にすぎません。

感情分析のユースケース

感情分析が、データ主導の意思決定に役立つ洞察を組織に与える方法を見てきました。それでは、感情分析のいくつかのユースケースを覗いてみましょう。

  1. ブランド管理のためのソーシャルメディアモニタリング:ブランドは、感情分析を使用して、ブランドの一般的な見通しを評価できます。たとえば、会社は、会社の言及またはタグを付けてすべてのツイートを収集し、感情分析を実行して、会社の一般的な見通しを知ることができます。
  2. 製品/サービス分析:ブランド/組織は、顧客レビューに対して感情分析を実行して、製品またはサービスが市場でどの程度うまく機能しているかを確認し、それに応じて将来の決定を下すことができます。
  3. 株価予測:企業の株価が上がるか下がるかを予測することは、投資家にとって非常に重要です。会社名を含む記事のニュースヘッドラインで感情分析を実行することで、同じことを判断できます。特定の組織に関連するニュースの見出しがたまたま前向きな感情を持っている場合、その株価は上昇するはずであり、その逆も同様です。

Pythonで感情分析を実行する方法

Pythonは、データサイエンスタスクの実行に関して最も強力なツールの1つであり、 感情分析を実行するためのさまざまな方法を提供します。最も人気のあるものはここに参加しています:

  1. テキストブロブの使用
  2. Vaderの使用
  3. BagofWordsのベクトル化ベースのモデルの使用
  4. LSTMベースのモデルの使用
  5. Transformerベースのモデルの使用

それらを1つずつ深く掘り下げていきましょう。

注:方法3および4(Bag of Wordsのベクトル化ベースのモデルの使用およびLSTMベースのモデルの使用)のデモンストレーションの目的で、感情分析が使用されています。これは、ポジティブ、ネガティブ、またはニュートラルとラベル付けされた5000を超えるテキストの抜粋で構成されています。データセットはクリエイティブコモンズライセンスの下にあります。

テキストブロブの使用

Text Blobは、自然言語処理用のPythonライブラリです。感情分析にTextBlobを使用するのは非常に簡単です。入力としてテキストを受け取り、出力として極性主観性を返すことができます。

極性はテキストの感情を決定します。その値は[-1,1]にあり、-1は非常に否定的な感情を示し、1は非常に肯定的な感情を示します。

主観性は、テキスト入力が事実情報であるか個人的な意見であるかを決定します。その値は[0,1]の間にあり、0に近い値は事実情報を示し、1に近い値は個人的な意見を示します。

インストール

pip install textblob

テキストブロブのインポート:

from textblob import TextBlob

テキストブロブを使用した感情分析のコード実装:

TextBlobを使用して感情分析用のコードを書くのはかなり簡単です。TextBlobオブジェクトをインポートし、分析するテキストを次のように適切な属性で渡すだけです。

from textblob import TextBlob
text_1 = "The movie was so awesome."
text_2 = "The food here tastes terrible."#Determining the Polarity 
p_1 = TextBlob(text_1).sentiment.polarity
p_2 = TextBlob(text_2).sentiment.polarity#Determining the Subjectivity
s_1 = TextBlob(text_1).sentiment.subjectivity
s_2 = TextBlob(text_2).sentiment.subjectivityprint("Polarity of Text 1 is", p_1)
print("Polarity of Text 2 is", p_2)
print("Subjectivity of Text 1 is", s_1)
print("Subjectivity of Text 2 is", s_2)

出力:

Polarity of Text 1 is 1.0 
Polarity of Text 2 is -1.0 
Subjectivity of Text 1 is 1.0 
Subjectivity of Text 2 is 1.0

VADERの使用

VADER(Valence Aware Dictionary and sEntiment Reasoner)は、ソーシャルメディアテキストでトレーニングされたルールベースの感情アナライザーです。Text Blobと同様に、Pythonでの使用法は非常に簡単です。しばらくの間、例を挙げてコード実装での使用法を見ていきます。

インストール:

pip install vaderSentiment

VaderからのSentimentIntensityAnalyzerクラスのインポート:

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

Vaderを使用した感情分析のコード:

まず、SentimentIntensityAnalyzerクラスのオブジェクトを作成する必要があります。次に、次のようにテキストをオブジェクトのpolarity_scores()関数に渡す必要があります。

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
sentiment = SentimentIntensityAnalyzer()
text_1 = "The book was a perfect balance between wrtiting style and plot."
text_2 =  "The pizza tastes terrible."
sent_1 = sentiment.polarity_scores(text_1)
sent_2 = sentiment.polarity_scores(text_2)
print("Sentiment of text 1:", sent_1)
print("Sentiment of text 2:", sent_2)

出力

Sentiment of text 1: {'neg': 0.0, 'neu': 0.73, 'pos': 0.27, 'compound': 0.5719} 
Sentiment of text 2: {'neg': 0.508, 'neu': 0.492, 'pos': 0.0, 'compound': -0.4767}

ご覧のとおり、VaderSentimentオブジェクトは、分析するテキストの感情スコアの辞書を返します。

BagofWordsのベクトル化ベースのモデルの使用

まだ説明されている2つのアプローチ、つまりText BlobとVaderでは、Pythonライブラリを使用して感情分析を実行しました。次に、タスク用に独自のモデルをトレーニングするアプローチについて説明します。Bag ofWordsVectorizationメソッドを使用して感情分析を実行する手順は次のとおりです。

  1. トレーニングデータのテキストを前処理します(テキストの前処理には、正規化、トークン化、ストップワードの削除、およびステミング/レマタイズが含まれます)。
  2. カウントベクトル化またはTF-IDFベクトル化アプローチを使用して、前処理されたテキストデータ用の単語のバッグを作成します。
  3. 感情分類のために処理されたデータで適切な分類モデルをトレーニングします。

Bag of Wordsベクトル化アプローチを使用した感情分析のコード:

BOWベクトル化アプローチを使用して感情分析モデルを構築するには、ラベル付きデータセットが必要です。前述のように、このデモンストレーションに使用されるデータセットはKaggleから取得されています。sklearnのカウントベクトライザーを使用してBOWを作成しました。その後、0.84の精度スコアが得られた多項単純ベイズ分類器をトレーニングしました。

データセットはここから取得できます。

#Loading the Dataset
import pandas as pd
data = pd.read_csv('Finance_data.csv')
#Pre-Prcoessing and Bag of Word Vectorization using Count Vectorizer
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(stop_words='english',ngram_range = (1,1),tokenizer = token.tokenize)
text_counts = cv.fit_transform(data['sentences'])
#Splitting the data into trainig and testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(text_counts, data['feedback'], test_size=0.25, random_state=5)
#Training the model
from sklearn.naive_bayes import MultinomialNB
MNB = MultinomialNB()
MNB.fit(X_train, Y_train)
#Caluclating the accuracy score of the model
from sklearn import metrics
predicted = MNB.predict(X_test)
accuracy_score = metrics.accuracy_score(predicted, Y_test)
print("Accuracuy Score: ",accuracy_score)

出力

Accuracuy Score:  0.9111675126903553

訓練された分類器は、任意のテキスト入力の感情を予測するために使用できます。

LSTMベースのモデルの使用

Bag of Words Vectorizationメソッドを使用して適切な精度スコアを取得することはできましたが、より大きなデータセットを処理する場合、同じ結果が得られない可能性があります。これにより、感情分析モデルのトレーニングにディープラーニングベースのモデルを採用する必要が生じます。

NLPタスクでは、シーケンシャルデータを処理するように設計されているため、通常はRNNベースのモデルを使用します。ここでは、KerasでTensorFlowを使用してLSTM(Long Short Term Memory)モデルをトレーニングします。LSTMベースのモデルを使用して感情分析を実行する手順は次のとおりです。

  1. トレーニングデータのテキストを前処理します(テキストの前処理には、正規化、トークン化、ストップワードの削除、およびステミング/レマタイズが含まれます)。
  2. Keras.preprocessing.textからTokenizerをインポートし、そのオブジェクトを作成します。トークナイザーをトレーニングテキスト全体に適合させます(トークナイザーがトレーニングデータの語彙でトレーニングされるようにします)。Tokenizerのtexts_to_sequence()メソッドを使用して生成されたテキスト埋め込みは、同じ長さにパディングした後に保存します。(埋め込みはテキストの数値/ベクトル化された表現です。モデルにテキストデータを直接フィードすることはできないため、最初にそれらを埋め込みに変換する必要があります)
  3. 埋め込みを生成したら、モデルを作成する準備が整います。TensorFlowを使用してモデルを構築します—入力、LSTM、および高密度レイヤーをモデルに追加します。ドロップアウトを追加し、ハイパーパラメータを調整して、適切な精度スコアを取得します。一般に、勾配消失問題を回避するため、LSTMモデルの内層でReLUまたはLeakyReLU活性化関数を使用する傾向があります。出力層では、SoftmaxまたはSigmoid活性化関数を使用します。

LSTMベースのモデルアプローチを使用した感情分析のコード:

ここでは、BOWアプローチの場合に使用したものと同じデータセットを使用しました。0.90のトレーニング精度が得られました。

#Importing necessary libraries
import nltk
import pandas as pd
from textblob import Word
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split 
#Loading the dataset
data = pd.read_csv('Finance_data.csv')
#Pre-Processing the text 
def cleaning(df, stop_words):
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x.lower() for x in x.split()))
    # Replacing the digits/numbers
    df['sentences'] = df['sentences'].str.replace('d', '')
    # Removing stop words
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x for x in x.split() if x not in stop_words))
    # Lemmatization
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join([Word(x).lemmatize() for x in x.split()]))
    return df
stop_words = stopwords.words('english')
data_cleaned = cleaning(data, stop_words)
#Generating Embeddings using tokenizer
tokenizer = Tokenizer(num_words=500, split=' ') 
tokenizer.fit_on_texts(data_cleaned['verified_reviews'].values)
X = tokenizer.texts_to_sequences(data_cleaned['verified_reviews'].values)
X = pad_sequences(X)
#Model Building
model = Sequential()
model.add(Embedding(500, 120, input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(704, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(352, activation='LeakyReLU'))
model.add(Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics = ['accuracy'])
print(model.summary())
#Model Training
model.fit(X_train, y_train, epochs = 20, batch_size=32, verbose =1)
#Model Testing
model.evaluate(X_test,y_test)

Transformerベースのモデルの使用

Transformerベースのモデルは、最も高度な自然言語処理技術の1つです。それらはエンコーダー-デコーダーベースのアーキテクチャーに従い、印象的な結果を生み出すために自己注意の概念を採用しています。トランスフォーマーモデルはいつでも最初から作成できますが、非常に面倒な作業です。したがって、 HuggingFaceで利用可能な事前トレーニング済みのトランスフォーマーモデルを使用できます。Hugging FaceはオープンソースのAIコミュニティであり、NLPアプリケーション用に事前にトレーニングされた多数のモデルを提供しています。これらのモデルは、そのまま使用することも、特定のタスクに合わせて微調整することもできます。

インストール:

pip install transformers

VaderからのSentimentIntensityAnalyzerクラスのインポート:

import transformers

Transformerベースのモデルを使用した感情分析のコード:

トランスフォーマーを使用してタスクを実行するには、最初にトランスフォーマーからパイプライン関数をインポートする必要があります。次に、パイプライン関数のオブジェクトが作成され、実行されるタスクが引数として渡されます(つまり、この場合は感情分析)。タスクを実行するために使用する必要のあるモデルを指定することもできます。ここでは、使用するモデルについて言及していないため、感情分析にはデフォルトでdistillery-base-uncased-finetuned-sst-2-Englishモードが使用されます。利用可能なタスクとモデルのリストは、こちらで確認できます。

from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["It was the best of times.", "t was the worst of times."]
sentiment_pipeline(data)Output:[{'label': 'POSITIVE', 'score': 0.999457061290741},  {'label': 'NEGATIVE', 'score': 0.9987301230430603}]

結論

ユーザーが自分の視点を簡単に表現でき、データがほんの数秒で過剰に生成されるこの時代では、そのようなデータから洞察を引き出すことは、組織が効率的な意思決定を行うために不可欠です。感情分析は、パズルの欠片であることがわかります。

これまでに、感情分析に必要なものと、Pythonでそれを実行するために使用できるさまざまな方法について詳しく説明してきました。しかし、これらはほんの一部の基本的なデモンストレーションでした。必ず先に進んでモデルをいじって、自分のデータで試してみる必要があります。

ソース:https ://www.analyticsvidhya.com/blog/2022/07/sentiment-analysis-using-python/

#python 

郝 玉华

郝 玉华

1657276560

在 Python 中执行情感分析的 5 种方法

无论您说的是 Twitter、Goodreads 还是亚马逊——几乎没有一个数字空间不充满人们的意见。在当今世界,组织挖掘这些意见并获得有关其产品或服务的见解至关重要。然而,这些数据以如此惊人的数量存在,以至于手动测量它几乎是不可能的追求。这就是数据科学的另一个好处 ——情绪分析。在本文中,我们将探讨情感分析包含的内容以及在 Python 中实现它的各种方法。

什么是情绪分析?

情感分析自然语言处理 (NLP)的一个用例,属于文本分类的范畴。简而言之,情感分析涉及将文本分类为各种情感,如正面或负面、快乐、悲伤或中性等。因此,情感分析的最终目标是破译一个潜在的情绪、情绪或情绪。文本。这也称为意见挖掘

让我们看看快速谷歌搜索如何定义情绪分析:

情绪分析定义

通过情绪分析获得洞察力并做出决策

好吧,现在我想我们已经有点习惯了情绪分析是什么。但它的意义是什么?组织如何从中受益?让我们尝试用一个例子来探索一下。假设您创办了一家在在线平台上销售香水的公司。你推出了种类繁多的香水,很快顾客就蜂拥而至。一段时间后,你决定改变香水的定价策略——你计划提高流行香水的价格,同时为不受欢迎的香水提供折扣. 现在,为了确定哪些香水受欢迎,您开始查看所有香水的客户评论。但是你被困住了!它们是如此之多,以至于您无法在一生中将它们全部看完。这就是情绪分析可以让你摆脱困境的地方。

您只需将所有评论收集在一个地方并对其应用情绪分析。以下是对三种香水——薰衣草、玫瑰和柠檬的评论的情感分析示意图。(请注意,这些评论可能有不正确的拼写、语法和标点符号,就像在现实世界中一样)

情绪分析

从这些结果中,我们可以清楚地看到:

Fragrance-1(薰衣草)得到了客户的高度好评,这表明贵公司可以根据其受欢迎程度提高其价格。

Fragrance-2 (Rose)恰好在客户中持中立态度,这意味着贵公司不应改变其定价

Fragrance-3(柠檬)具有与之相关的整体负面情绪 - 因此,您的公司应考虑为其提供折扣以平衡规模。

这只是一个简单的示例,说明情绪分析如何帮助您深入了解您的产品/服务并帮助您的组织做出决策。

情绪分析用例

我们刚刚看到了情绪分析如何为组织提供洞察力,帮助他们做出数据驱动的决策。现在,让我们来看看更多情感分析的用例。

  1. 品牌管理的社交媒体监控:品牌可以使用情绪分析来衡量其品牌的公众形象。例如,公司可以收集所有带有公司提及或标签的推文,并执行情绪分析以了解公司的公众前景。
  2. 产品/服务分析:品牌/组织可以对客户评论进行情绪分析,以了解产品或服务在市场上的表现,并据此做出未来决策。
  3. 股价预测:预测一家公司的股票是涨还是跌,对投资者来说至关重要。可以通过对包含公司名称的文章的新闻标题进行情绪分析来确定相同的结果。如果与特定组织有关的新闻头条恰好具有积极情绪——其股价应该会上涨,反之亦然。

在 Python 中执行情感分析的方法

在执行数据科学任务时,Python 是最强大的工具之一——它提供了多种执行 情感分析的方法。这里列出了最受欢迎的:

  1. 使用文本 Blob
  2. 使用维达
  3. 使用基于词向量化的模型
  4. 使用基于 LSTM 的模型
  5. 使用基于 Transformer 的模型

让我们一一深入了解它们。

注意:为了演示方法 3 和 4(使用基于词向量化的模型和使用基于 LSTM 的模型)的情感分析。它包含 5000 多个标记为正面、负面或中性的文本摘录。该数据集位于知识共享许可下。

使用文本 Blob

Text Blob 是一个用于自然语言处理的 Python 库。使用 Text Blob 进行情绪分析非常简单。它将文本作为输入,并可以返回极性主观性作为输出。

极性决定了文本的情绪。它的值位于 [-1,1] 中,其中 -1 表示高度负面的情绪,1 表示高度正面的情绪。

主观性决定了文本输入是事实信息还是个人观点。它的值介于 [0,1] 之间,其中接近 0 的值表示一条事实信息,接近 1 的值表示个人意见。

安装

pip install textblob

导入文本块:

from textblob import TextBlob

使用文本 Blob 进行情感分析的代码实现:

使用 TextBlob 编写情绪分析代码相当简单。只需导入 TextBlob 对象并使用适当的属性传递要分析的文本,如下所示:

from textblob import TextBlob
text_1 = "The movie was so awesome."
text_2 = "The food here tastes terrible."#Determining the Polarity 
p_1 = TextBlob(text_1).sentiment.polarity
p_2 = TextBlob(text_2).sentiment.polarity#Determining the Subjectivity
s_1 = TextBlob(text_1).sentiment.subjectivity
s_2 = TextBlob(text_2).sentiment.subjectivityprint("Polarity of Text 1 is", p_1)
print("Polarity of Text 2 is", p_2)
print("Subjectivity of Text 1 is", s_1)
print("Subjectivity of Text 2 is", s_2)

输出:

Polarity of Text 1 is 1.0 
Polarity of Text 2 is -1.0 
Subjectivity of Text 1 is 1.0 
Subjectivity of Text 2 is 1.0

使用 VADER

VADER(Valence Aware Dictionary and sEntiment Reasoner)是一个基于规则的情感分析器,已经在社交媒体文本上进行了训练。就像 Text Blob 一样,它在 Python 中的使用非常简单。稍后我们将通过一个示例来了解它在代码实现中的用法。

安装:

pip install vaderSentiment

从 Vader 导入 SentimentIntensityAnalyzer 类:

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

使用 Vader 进行情绪分析的代码:

首先,我们需要创建一个 SentimentIntensityAnalyzer 类的对象;然后我们需要将文本传递给对象的 polar_scores() 函数,如下所示:

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
sentiment = SentimentIntensityAnalyzer()
text_1 = "The book was a perfect balance between wrtiting style and plot."
text_2 =  "The pizza tastes terrible."
sent_1 = sentiment.polarity_scores(text_1)
sent_2 = sentiment.polarity_scores(text_2)
print("Sentiment of text 1:", sent_1)
print("Sentiment of text 2:", sent_2)

输出

Sentiment of text 1: {'neg': 0.0, 'neu': 0.73, 'pos': 0.27, 'compound': 0.5719} 
Sentiment of text 2: {'neg': 0.508, 'neu': 0.492, 'pos': 0.0, 'compound': -0.4767}

正如我们所见,VaderSentiment 对象返回要分析的文本的情绪分数字典。

使用基于词向量化的模型

在目前讨论的两种方法中,即 Text Blob 和 Vader,我们只是使用 Python 库来执行情绪分析。现在我们将讨论一种方法,在该方法中,我们将为该任务训练我们自己的模型。使用词袋向量化方法执行情感分析的步骤如下:

  1. 预处理训练数据的文本(文本预处理包括规范化、标记化、停用词去除和词干/词形还原。)
  2. 使用计数向量化或 TF-IDF 向量化方法为预处理的文本数据创建词袋。
  3. 在处理后的数据上训练合适的分类模型以进行情感分类。

使用词袋向量化方法进行情感分析的代码:

要使用 BOW 矢量化方法构建情绪分析模型,我们需要一个标记数据集。如前所述,用于此演示的数据集是从 Kaggle 获得的。我们简单地使用了 sklearn 的计数向量器来创建 BOW。之后,我们训练了一个多项朴素贝叶斯分类器,其准确度得分为 0.84。

数据集可以从这里获得。

#Loading the Dataset
import pandas as pd
data = pd.read_csv('Finance_data.csv')
#Pre-Prcoessing and Bag of Word Vectorization using Count Vectorizer
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(stop_words='english',ngram_range = (1,1),tokenizer = token.tokenize)
text_counts = cv.fit_transform(data['sentences'])
#Splitting the data into trainig and testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(text_counts, data['feedback'], test_size=0.25, random_state=5)
#Training the model
from sklearn.naive_bayes import MultinomialNB
MNB = MultinomialNB()
MNB.fit(X_train, Y_train)
#Caluclating the accuracy score of the model
from sklearn import metrics
predicted = MNB.predict(X_test)
accuracy_score = metrics.accuracy_score(predicted, Y_test)
print("Accuracuy Score: ",accuracy_score)

输出

Accuracuy Score:  0.9111675126903553

经过训练的分类器可用于预测任何给定文本输入的情绪。

使用基于 LSTM 的模型

虽然我们能够使用词袋矢量化方法获得不错的准确度分数,但在处理更大的数据集时可能无法产生相同的结果。这就需要使用基于深度学习的模型来训练情感分析模型。

对于 NLP 任务,我们通常使用基于 RNN 的模型,因为它们旨在处理顺序数据。在这里,我们将使用TensorFlowKeras训练一个 LSTM(长短期记忆)模型。使用基于 LSTM 的模型执行情感分析的步骤如下:

  1. 预处理训练数据的文本(文本预处理包括规范化、标记化、停用词去除和词干/词形还原。)
  2. 从 Keras.preprocessing.text导入Tokenizer并创建它的对象。在整个训练文本上拟合标记器(以便标记器在训练数据词汇表上得到训练)。使用 Tokenizer 的 texts_to_sequence() 方法生成文本嵌入,并在将它们填充到相等长度后存储它们。(嵌入是文本的数字/矢量化表示。由于我们不能直接为模型提供文本数据,我们首先需要将它们转换为嵌入)
  3. 生成嵌入后,我们就可以构建模型了。我们使用 TensorFlow 构建模型——向其中添加输入、LSTM 和密集层。添加 dropout 并调整超参数以获得不错的准确度分数。通常,我们倾向于在 LSTM 模型的内层使用ReLULeakyReLU激活函数,因为它避免了梯度消失问题。在输出层,我们使用 Softmax 或 Sigmoid 激活函数。

使用基于 LSTM 的模型方法进行情感分析的代码:

在这里,我们使用了与 BOW 方法相同的数据集。获得了 0.90 的训练准确度。

#Importing necessary libraries
import nltk
import pandas as pd
from textblob import Word
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split 
#Loading the dataset
data = pd.read_csv('Finance_data.csv')
#Pre-Processing the text 
def cleaning(df, stop_words):
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x.lower() for x in x.split()))
    # Replacing the digits/numbers
    df['sentences'] = df['sentences'].str.replace('d', '')
    # Removing stop words
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x for x in x.split() if x not in stop_words))
    # Lemmatization
    df['sentences'] = df['sentences'].apply(lambda x: ' '.join([Word(x).lemmatize() for x in x.split()]))
    return df
stop_words = stopwords.words('english')
data_cleaned = cleaning(data, stop_words)
#Generating Embeddings using tokenizer
tokenizer = Tokenizer(num_words=500, split=' ') 
tokenizer.fit_on_texts(data_cleaned['verified_reviews'].values)
X = tokenizer.texts_to_sequences(data_cleaned['verified_reviews'].values)
X = pad_sequences(X)
#Model Building
model = Sequential()
model.add(Embedding(500, 120, input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(704, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(352, activation='LeakyReLU'))
model.add(Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics = ['accuracy'])
print(model.summary())
#Model Training
model.fit(X_train, y_train, epochs = 20, batch_size=32, verbose =1)
#Model Testing
model.evaluate(X_test,y_test)

使用基于 Transformer 的模型

基于 Transformer 的模型是最先进的自然语言处理技术之一。它们遵循基于编码器-解码器的架构,并采用自我注意的概念来产生令人印象深刻的结果。虽然总是可以从头开始构建变压器模型,但这是一项相当乏味的任务。因此,我们可以使用Hugging Face上可用的预训练变压器模型。Hugging Face 是一个开源 AI 社区,为 NLP 应用程序提供大量预训练模型。这些模型可以原样使用,也可以针对特定任务进行微调。

安装:

pip install transformers

从 Vader 导入 SentimentIntensityAnalyzer 类:

import transformers

使用基于 Transformer 的模型进行情绪分析的代码:

要使用转换器执行任何任务,我们首先需要从转换器导入管道功能。然后,创建管道函数的对象并将要执行的任务作为参数传递(即在我们的案例中进行情感分析)。我们还可以指定我们需要用来执行任务的模型。这里,由于我们没有提到要使用的模型,所以默认使用 distillery-base-uncased-finetuned-sst-2-English 模式进行情感分析。您可以在此处查看可用任务和模型的列表。

from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["It was the best of times.", "t was the worst of times."]
sentiment_pipeline(data)Output:[{'label': 'POSITIVE', 'score': 0.999457061290741},  {'label': 'NEGATIVE', 'score': 0.9987301230430603}]

结论

在这个用户可以毫不费力地表达他们的观点并且在几分之一秒内生成多余的数据的时代——从这些数据中获得洞察力对于组织做出有效决策至关重要——而情绪分析被证明是拼图中缺失的部分!

到目前为止,我们已经非常详细地介绍了情感分析的确切含义以及可以用来在 Python 中执行它的各种方法。但这些只是一些基本的演示——你一定要继续摆弄模型,并在你自己的数据上进行尝试。

资料来源:https ://www.analyticsvidhya.com/blog/2022/07/sentiment-analysis-using-python/

#python