Table of Contents
Start now!
Getting data
Data processing
Prepare the characteristic values ​​and target values
特征工程:文本特征处理
使用的机器学习算法
划分数据集
K-近邻算法
逻辑回归算法
支持向量机算法
随机森林算法
决策树算法
随机梯度下降算法
朴素贝叶斯算法
情感分析的最佳算法
Home Technology peripherals AI How to use machine learning to analyze sentiment

How to use machine learning to analyze sentiment

Apr 11, 2023 pm 04:49 PM
machine learning Analyze sentiment

How to use machine learning to analyze sentiment

We used different machine learning algorithms for sentiment analysis, and then compared the accuracy results of each algorithm to determine which algorithm is most suitable for this problem.

Sentiment analysis is an important content in natural language processing (NLP). Emotions are the feelings we have about an event, object, situation, or thing. Sentiment analysis is a research field that automatically extracts human emotions from text. It slowly started to develop in the early 90s.

This article will let you understand how to use machine learning (ML) for sentiment analysis and compare the results of different machine learning algorithms. The goal of this article is not to study how to improve algorithm performance.

Nowadays, we live in a fast-paced society, all goods can be purchased online, and everyone can post their own comments online. And negative online reviews of some products may damage the company's reputation, thereby affecting the company's sales. So it becomes very important for companies to use product reviews to understand what customers really want. However, there is too much comment data, and it is impossible to manually view all comments one by one. This is how sentiment analysis was born.

Now, let’s see how to use machine learning to develop a model to perform basic sentiment analysis.

Start now!

Getting data

The first step is to select a data set. You can choose from any public review, such as a tweet or a movie review. The dataset must contain at least two columns: labels and actual text segments.

The figure below shows some of the data sets we selected.

Figure 1: Data sample

Figure 1: Data sample

Next, we import the required libraries:

import pandas as pd
import numpy as np
from nltk.stem.porter import PorterStemmer
import re
import string
Copy after login

As As you can see in the above code, we imported the ​​NumPy​​ and ​​Pandas​​ libraries to process the data. As for other libraries, we will explain them when they are used.

The data set is ready and the required libraries have been imported. Next, we need to use the ​​Pandas​​ library to read the data set into our project. We use the following code to read the data set into the Pandas data frame DataFrame

sentiment_dataframe = pd.read_csv(“/content/drive/MyDrive/Data/sentiments - sentiments.tsv”,sep = ‘t’)
Copy after login

Data processing

Now the data set has been imported into our project. We then process the data so that the algorithm can better understand the characteristics of the data set. We first name the columns in the dataset, which is done with the following code:

sentiment_dataframe.columns = [“label”,”body_text”]
Copy after login

Then, we numericize the ​​label​​ column: ​​negative​ ​ comments are replaced with 1, and ​positive​​ comments are replaced with 0. The image below shows the values ​​of ​​sentiment_dataframe​​ after a basic modification.

Figure 2: Data frame with basic modifications

Figure 2: Data frame with basic modifications

Prepare the characteristic values ​​and target values

Next step It is the preprocessing of data. This is a very important step, because machine learning algorithms can only understand/process numerical data, but not text. Therefore, feature extraction is required at this time to convert strings/text into numerical data. Additionally, redundant and useless data need to be removed as these data may contaminate our trained model. We remove noisy data, missing value data, and inconsistent data in this step.

对于情感分析,我们在数据帧中添加特征文本的长度和标点符号计数。我们还要进行词干提取,即将所有相似词(如 “give”、“giving” 等)转换为单一形式。完成后,我们将数据集分为两部分:特征值 X 和 目标值 Y。

上述内容是使用以下代码完成的。下图显示了执行这些步骤后的数据帧。

Figure 3: Data frame after the division of the data set

Figure 3: Data frame after the division of the data set

def count_punct(text):
 count = sum([1 for char in text if char in string.punctuation])
 return round(count/(len(text) - text.count(“ “)),3)*100
 
tokenized_tweet = sentiment_dataframe[‘body_text’].apply(lambda x: x.split())
stemmer = PorterStemmer()
tokenized_tweet = tokenized_tweet.apply(lambda x: [stemmer.stem(i) for i in x])
for i in range(len(tokenized_tweet)):
 tokenized_tweet[i] = ‘ ‘.join(tokenized_tweet[i])
sentiment_dataframe[‘body_text’] = tokenized_tweet
sentiment_dataframe[‘body_len’] = sentiment_dataframe[‘body_text’].apply(lambda x:len(x) - x.count(“ “))
sentiment_dataframe[‘punct%’] = sentiment_dataframe[‘body_text’].apply(lambda x:count_punct(x))
X = sentiment_dataframe[‘body_text’]
y = sentiment_dataframe[‘label’]
Copy after login

特征工程:文本特征处理

我们接下来进行文本特征抽取,对文本特征进行数值化。为此,我们使用计数向量器CountVectorizer,它返回词频矩阵。

在此之后,计算数据帧 X 中的文本长度和标点符号计数等特征。X 的示例如下图所示。

Figure 4: Sample of final features

Figure 4: Sample of final features

使用的机器学习算法

现在数据已经可以训练了。下一步是确定使用哪些算法来训练模型。如前所述,我们将尝试多种机器学习算法,并确定最适合情感分析的算法。由于我们打算对文本进行二元分类,因此我们使用以下算法:

  • K-近邻算法(KNN)
  • 逻辑回归算法
  • 支持向量机(SVMs)
  • 随机梯度下降(SGD)
  • 朴素贝叶斯算法
  • 决策树算法
  • 随机森林算法

划分数据集

首先,将数据集划分为训练集和测试集。使用 ​​sklearn​​ 库,详见以下代码:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.20, random_state = 99)
Copy after login

我们使用 20% 的数据进行测试,80% 的数据用于训练。划分数据的意义在于对一组新数据(即测试集)评估我们训练的模型是否有效。

K-近邻算法

现在,让我们开始训练第一个模型。首先,我们使用 KNN 算法。先训练模型,然后再评估模型的准确率(具体的代码都可以使用 Python 的 ​​sklearn​​ 库来完成)。详见以下代码,KNN 训练模型的准确率大约为 50%。

from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
model.score (X_test,y_test)
0.5056689342403629
Copy after login
逻辑回归算法

逻辑回归模型的代码十分类似——首先从库中导入函数,拟合模型,然后对模型进行评估。下面的代码使用逻辑回归算法,准确率大约为 66%。

from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit (X_train,y_train)
model.score (X_test,y_test)
0.6621315192743764
Copy after login
支持向量机算法

以下代码使用 SVM,准确率大约为 67%。

from sklearn import svm
model = svm.SVC(kernel=’linear’)
model.fit(X_train, y_train)
model.score(X_test,y_test)
0.6780045351473923
Copy after login
随机森林算法

以下的代码使用了随机森林算法,随机森林训练模型的准确率大约为 69%。

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(X_train, y_train)
model.score(X_test,y_test)
0.6938775510204082
Copy after login
决策树算法

接下来,我们使用决策树算法,其准确率约为 61%。

from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model = model.fit(X_train,y_train)
model.score(X_test,y_test)
0.6190476190476191
Copy after login
随机梯度下降算法

以下的代码使用随机梯度下降算法,其准确率大约为 49%。

from sklearn.linear_model import SGDClassifier
model = SGDClassifier()
model = model.fit(X_train,y_train)
model.score(X_test,y_test)
0.49206349206349204
Copy after login
朴素贝叶斯算法

以下的代码使用朴素贝叶斯算法,朴素贝叶斯训练模型的准确率大约为 60%。

from sklearn.naive_bayes import GaussianNB
model = GaussianNB()
model.fit(X_train, y_train)
model.score(X_test,y_test)
0.6009070294784581
Copy after login

情感分析的最佳算法

接下来,我们绘制所有算法的准确率图。如下图所示。

Figure 5: Accuracy performance of the different algorithms

Figure 5: Accuracy performance of the different algorithms

可以看到,对于情感分析这一问题,随机森林算法有最佳的准确率。由此,我们可以得出结论,随机森林算法是所有机器算法中最适合情感分析的算法。我们可以通过处理得到更好的特征、尝试其他矢量化技术、或者使用更好的数据集或更好的分类算法,来进一步提高准确率。

既然,随机森林算法是解决情感分析问题的最佳算法,我将向你展示一个预处理数据的样本。在下图中,你可以看到模型会做出正确的预测!试试这个来改进你的项目吧!

Figure 6: Sample predictions made

Figure 6: Sample predictions made

The above is the detailed content of How to use machine learning to analyze sentiment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

15 recommended open source free image annotation tools 15 recommended open source free image annotation tools Mar 28, 2024 pm 01:21 PM

Image annotation is the process of associating labels or descriptive information with images to give deeper meaning and explanation to the image content. This process is critical to machine learning, which helps train vision models to more accurately identify individual elements in images. By adding annotations to images, the computer can understand the semantics and context behind the images, thereby improving the ability to understand and analyze the image content. Image annotation has a wide range of applications, covering many fields, such as computer vision, natural language processing, and graph vision models. It has a wide range of applications, such as assisting vehicles in identifying obstacles on the road, and helping in the detection and diagnosis of diseases through medical image recognition. . This article mainly recommends some better open source and free image annotation tools. 1.Makesens

This article will take you to understand SHAP: model explanation for machine learning This article will take you to understand SHAP: model explanation for machine learning Jun 01, 2024 am 10:58 AM

In the fields of machine learning and data science, model interpretability has always been a focus of researchers and practitioners. With the widespread application of complex models such as deep learning and ensemble methods, understanding the model's decision-making process has become particularly important. Explainable AI|XAI helps build trust and confidence in machine learning models by increasing the transparency of the model. Improving model transparency can be achieved through methods such as the widespread use of multiple complex models, as well as the decision-making processes used to explain the models. These methods include feature importance analysis, model prediction interval estimation, local interpretability algorithms, etc. Feature importance analysis can explain the decision-making process of a model by evaluating the degree of influence of the model on the input features. Model prediction interval estimate

Transparent! An in-depth analysis of the principles of major machine learning models! Transparent! An in-depth analysis of the principles of major machine learning models! Apr 12, 2024 pm 05:55 PM

In layman’s terms, a machine learning model is a mathematical function that maps input data to a predicted output. More specifically, a machine learning model is a mathematical function that adjusts model parameters by learning from training data to minimize the error between the predicted output and the true label. There are many models in machine learning, such as logistic regression models, decision tree models, support vector machine models, etc. Each model has its applicable data types and problem types. At the same time, there are many commonalities between different models, or there is a hidden path for model evolution. Taking the connectionist perceptron as an example, by increasing the number of hidden layers of the perceptron, we can transform it into a deep neural network. If a kernel function is added to the perceptron, it can be converted into an SVM. this one

Identify overfitting and underfitting through learning curves Identify overfitting and underfitting through learning curves Apr 29, 2024 pm 06:50 PM

This article will introduce how to effectively identify overfitting and underfitting in machine learning models through learning curves. Underfitting and overfitting 1. Overfitting If a model is overtrained on the data so that it learns noise from it, then the model is said to be overfitting. An overfitted model learns every example so perfectly that it will misclassify an unseen/new example. For an overfitted model, we will get a perfect/near-perfect training set score and a terrible validation set/test score. Slightly modified: "Cause of overfitting: Use a complex model to solve a simple problem and extract noise from the data. Because a small data set as a training set may not represent the correct representation of all data." 2. Underfitting Heru

The evolution of artificial intelligence in space exploration and human settlement engineering The evolution of artificial intelligence in space exploration and human settlement engineering Apr 29, 2024 pm 03:25 PM

In the 1950s, artificial intelligence (AI) was born. That's when researchers discovered that machines could perform human-like tasks, such as thinking. Later, in the 1960s, the U.S. Department of Defense funded artificial intelligence and established laboratories for further development. Researchers are finding applications for artificial intelligence in many areas, such as space exploration and survival in extreme environments. Space exploration is the study of the universe, which covers the entire universe beyond the earth. Space is classified as an extreme environment because its conditions are different from those on Earth. To survive in space, many factors must be considered and precautions must be taken. Scientists and researchers believe that exploring space and understanding the current state of everything can help understand how the universe works and prepare for potential environmental crises

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Explainable AI: Explaining complex AI/ML models Explainable AI: Explaining complex AI/ML models Jun 03, 2024 pm 10:08 PM

Translator | Reviewed by Li Rui | Chonglou Artificial intelligence (AI) and machine learning (ML) models are becoming increasingly complex today, and the output produced by these models is a black box – unable to be explained to stakeholders. Explainable AI (XAI) aims to solve this problem by enabling stakeholders to understand how these models work, ensuring they understand how these models actually make decisions, and ensuring transparency in AI systems, Trust and accountability to address this issue. This article explores various explainable artificial intelligence (XAI) techniques to illustrate their underlying principles. Several reasons why explainable AI is crucial Trust and transparency: For AI systems to be widely accepted and trusted, users need to understand how decisions are made

Is Flash Attention stable? Meta and Harvard found that their model weight deviations fluctuated by orders of magnitude Is Flash Attention stable? Meta and Harvard found that their model weight deviations fluctuated by orders of magnitude May 30, 2024 pm 01:24 PM

MetaFAIR teamed up with Harvard to provide a new research framework for optimizing the data bias generated when large-scale machine learning is performed. It is known that the training of large language models often takes months and uses hundreds or even thousands of GPUs. Taking the LLaMA270B model as an example, its training requires a total of 1,720,320 GPU hours. Training large models presents unique systemic challenges due to the scale and complexity of these workloads. Recently, many institutions have reported instability in the training process when training SOTA generative AI models. They usually appear in the form of loss spikes. For example, Google's PaLM model experienced up to 20 loss spikes during the training process. Numerical bias is the root cause of this training inaccuracy,

See all articles