nlp情感分析经典书籍推荐

In this tutorial, I will explain how to calculate the sentiment of a book through a Supervised Learning technique, based on Support Vector Machines (SVM).

在本教程中,我将解释如何基于支持向量机(SVM)通过监督学习技术来计算书籍的情感。

This tutorial calculates the sentiment analysis of the Saint Augustine Confessions, which can be downloaded from the Gutenberg Project Page. The masterpiece is split in 13 books (chapters). We have stored each book into a different file, named number.text (e.g. 1.txt and 2.txt). Each line of every file contains just one sentence.

本教程计算了圣奥古斯丁自白的情感分析,可以从古腾堡项目页面下载。 杰作分为13本书(每章)。 我们已经将每本书存储到一个名为number.text的不同文件中(例如1.txt和2.txt)。 每个文件的每一行仅包含一个句子。

The jupyter notebook can be download from my Github repository: https://github.com/alod83/papers/tree/master/aiucd2021

可以从我的Github存储库下载jupyter笔记本: https : //github.com/alod83/papers/tree/master/aiucd2021

A similar experiment of sentiment analysis of a book can be found at the following link: https://towardsdatascience.com/sentiment-analysis-of-a-book-through-unsupervised-learning-df876563dd1b. In this case I explain how to exploit unsupervised learning techniques to perform sentiment analysis.

可以在以下链接中找到类似的书籍情感分析实验: https : //towardsdatascience.com/sentiment-analysis-of-a-book-through-unsupervised-learning-df876563dd1b 。 在这种情况下,我解释了如何利用无监督学习技术进行情感分析。

入门 (Getting Started)

Supervised Learning needs some annotated text to train the model. Thus, the first step consists in reading the annotations file and store it into a dataframe. The annotation file contains for each sentence, the associated score, which is a positive, negative or null number.

监督学习需要一些带注释的文本来训练模型。 因此,第一步是读取注释文件并将其存储到数据框中。 注释文件包含每个句子的相关分数,分数是正数,负数或空数。

import pandas as pddf = pd.read_csv('sources/annotations.csv')df

We can calculate some statistics regarding the annotations, such as the number of positive, negative and neutral scores, as well as the total number of annotations. We can use the count() method applied to the dataframe.

我们可以计算一些有关注释的统计信息,例如正,负和中性分数的数量,以及注释的总数。 我们可以使用应用于数据框的count()方法。

df.count()df[df['score'] > 0].count()df[df['score'] < 0].count()df[df['score'] == 0].count()

准备训练和测试集 (Prepare the training and test sets)

In order to calculate the sentiment of each sentence, we will exploit a Supervised Learning technique, which exploits a binary classification model. This model takes a sentence as input and returns 1 or 0, depending whether the sentence is positively rated or not. Since our model is binary, we must remove all the annotations with a neutral score.

为了计算每个句子的情感,我们将利用一种监督学习技术,该技术利用二进制分类模型。 该模型将一个句子作为输入并返回1或0,这取决于该句子是否被正面评价。 由于我们的模型是二进制的,因此我们必须删除所有带有中性分数的注释。

import numpy as np# Remove any 'neutral' ratings equal to 0df = df[df['score'] != 0]

Now we can add a column to the dataframe, called Positively Rated, containing 1 or 0, depending on a positive or negative score. We use the where() method to assign the appropriate value to this new column of the dataframe.

现在,我们可以在数据框中添加一列,称为Positively Rated ,该列包含1或0,具体取决于正分数或负分数。 我们使用where()方法为数据框的这一新列分配适当的值。

df['Positively Rated'] = np.where(df['score'] > 0, 1, 0)

计算情绪 (Calculate the sentiment)

We define an auxiliary function, called calculate_indexes(), which receives as input the supervised learning model (which will be described later) and the CountVectorizer vector, as described later.

我们定义了一个辅助函数,称为calculate_indexes() ,该函数接收监督学习模型(将在后面描述)和CountVectorizer向量作为输入,如稍后所述。

Within the function, we open the file corresponding to each book through the open() function, we read all the lines through the function file.readlines() and for each line, we calculate the score, by applying the predict() function to the model.

在该函数中,我们通过open()函数open()与每本书对应的文件,然后通过函数file.readlines()读取所有行,并通过将predict()函数应用于该模型。

Then, we can define three indexes to calculate the sentiment of a book: the positive sentiment index (pi), the negative sentiment index (ni) and the neutral sentiment index (nui). The pi of a book corresponds to the number of positive sentences in a book divided per the total number of sentences of the book. Similarly, we can calculate the ni and nui of a book.

然后,我们可以定义三个指数来计算一本书的情绪:正情绪指数(pi),负情绪指数(ni)和中性情绪指数(nui)。 一本书的pi对应于一本书中肯定的句子数除以该书的句子总数。 同样,我们可以计算一本书的ni和nui。

def calculte_indexes(model,vect):    pos_index = []    neg_index = []    neutral_index = []    all_text = ""    for book in range(1,14):        file = open('sources/' + str(book) + '.txt')        lines = file.readlines()        pos = 0        neg = 0        for line in lines:            score = model.predict(vect.transform([line]))            if score == 1:                pos += 1            else:                neg += 1            all_text += ' ' + line.lower()         n = len(lines)        pos_index.append(pos / n)        neg_index.append(neg / n)    return pos_index,neg_index

Now we can train the algorithm. We define two different cases: in the first case we do not consider ngrams, in the second we do. We define a function called train_algorithm(), which can be invoked by specifying the usage of ngrams.

现在我们可以训练算法了。 我们定义了两种不同的情况:在第一种情况下,我们不考虑ngram;在第二种情况下,我们考虑。 我们定义了一个名为train_algorithm()的函数,可以通过指定ngram的用法来调用它。

In the function, firstly we split the dataset in two parts, training and test set through the scikit-learn function called train_test_split(). The training set will be used to train the algorithm, the test set will be used to test the performance of the algorithm.

在函数中,首先,我们通过称为train_test_split()scikit-learn函数将数据集分为训练集和测试集两部分。 训练集将用于训练算法,测试集将用于测试算法的性能。

X_train, X_test, y_train, y_test = train_test_split(df['sentence'],                             df['Positively Rated'], random_state=0)

Then we build the matrix of tokens count, i.e. the matrix which contains for each sentence which tokens are available. This can be done through the class CountVectorizer, which receives as input the number of ngrams to consider. In this tutorial, only two ngrams are considered. We consider only tokens with a minimum document frequency equal to 5.

然后,我们建立记号计数矩阵,即每个句子包含可用记号的矩阵。 这可以通过CountVectorizer类完成,该类将输入要考虑的ngram数量作为输入。 在本教程中,仅考虑两个ngram。 我们仅考虑最小文档频率等于5的令牌。

vect = CountVectorizer(min_df=5).fit(X_train)

Then we can build the model: we use the LinearSVC() class contained in scikit-learn and we train it with the training set model.fit(X_train_vectorized, y_train).

然后,我们可以构建模型:我们使用scikit-learn包含的LinearSVC()类,并使用训练集model.fit(X_train_vectorized, y_train)对其进行训练。

model = LinearSVC()model.fit(X_train_vectorized, y_train)

Finally, we test the performance of the algorithm by predicting the output for the test set and comparing results with real output contained in the test set. As metrics, we measure the AUC, but we could calculate also other metrics.

最后,我们通过预测测试集的输出并将结果与​​测试集中包含的实际输出进行比较来测试算法的性能。 作为度量,我们可以测量AUC,但也可以计算其他度量。

predictions = model.predict(vect.transform(X_test))print('AUC: ', roc_auc_score(y_test, predictions))

Once trained the model, we can calculate the indexes, through the calculte_indexes() function. Finally, we plot results.

训练好模型后,我们可以通过calculte_indexes()函数计算索引。 最后,我们绘制结果。

Here the full the code of the function train_algorithm().

这里是函数train_algorithm()的完整代码。

from sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.svm import LinearSVCfrom sklearn.metrics import roc_auc_scoreimport matplotlib.pyplot as pltdef train_algorithm(df, ngrams=False):    # Split data into training and test sets    X_train, X_test, y_train, y_test = train_test_split(df['sentence'],                                                     df['Positively Rated'],                                                     random_state=0)    # Fit the CountVectorizer to the training data    vect = CountVectorizer(min_df=5).fit(X_train)    if ngrams:        # Fit the CountVectorizer to the training data specifiying a minimum         # document frequency of 5 and extracting 1-grams and 2-grams        vect = CountVectorizer(min_df=5, ngram_range=(1,2)).fit(X_train)        print('NGRAMS')    else:        print('WITHOUT N-GRAMS')    # transform the documents in the training data to a document-term matrix    X_train_vectorized = vect.transform(X_train)    # Train the model    model = LinearSVC()    model.fit(X_train_vectorized, y_train)    # Predict the transformed test documents    predictions = model.predict(vect.transform(X_test))print('AUC: ', roc_auc_score(y_test, predictions))    pos_index, neg_index = calculte_indexes(model,vect)    X = np.arange(1,14)    plt.plot(X,pos_index,'-.',label='pos')    plt.plot(X,neg_index, '--',label='neg')    #plt.plot(X,neutral_index,'-',label='neu')    plt.legend()    plt.xticks(X)    plt.xlabel('Libri')    plt.ylabel('Indici')    plt.grid()    if ngrams:        plt.savefig('plots/svm-ngram-bsi.png')    else:        plt.savefig('plots/svm-1gram-bsi.png')    plt.show()

进行实验 (Run experiments)

Now we can run experiments with ngrams enabled and disabled.

现在,我们可以运行启用和禁用ngram的实验。

train_algorithm(df, ngrams=False)train_algorithm(df, ngrams=True)
Experiment without n-grams
没有n-gram的实验
Experiment with n-grams
用n-gram进行实验

学过的知识 (Lesson learned)

In this tutorial I have shown you how to calculate the sentiment of every chapter of a book through a Supervised Learning technique:

在本教程中,我向您展示了如何通过“监督学习”技术来计算一本书每一章的情感:

  • Supervised Learning needs some training sets, i.e. some data annotated manually. So before starting to play with models, you should do the boring task of annotating a (small) part of your data. The bigger the training set the better the performance of the algorithm;监督学习需要一些训练集,即一些手动注释的数据。 因此,在开始使用模型之前,您应该完成无聊的任务,即对数据的一小部分进行注释。 训练集越大,算法的性能越好;
  • To calculate the sentiment of a sentence, you should use a (binary) classification algorithm, such as the Support Vector Machines (SVM). The scikit-learn library provides many algorithms for classification;要计算句子的情感,应使用(二进制)分类算法,例如支持向量机(SVM)。 scikit-learn库提供了许多分类算法。
  • Once you have chosen the model, you can train it with the training set;选择模型后,即可使用训练集进行训练。
  • Don’t forget to test the performance of the model :)不要忘记测试模型的性能:)

翻译自: https://towardsdatascience.com/sentiment-analysis-of-a-book-through-supervised-learning-d56ba8946c64

nlp情感分析经典书籍推荐


http://www.taodudu.cc/news/show-2526776.html

相关文章:

  • java方法执行jvm做了什么_JVM 方法到底如何执行
  • 使用SharePoint Framework开发webpart的一些技巧汇总
  • K-均值聚类算法和二分K-均值算法
  • arm开发板开发环境搭建
  • 基于ubuntu的ARM开发环境搭建
  • ARM芯片学习内容规划及ARM开发环境的搭建
  • 几种ARM编译器及IDE开发环境
  • Go语言程序开发之ARM开发环境搭建
  • ARM开发工具介绍
  • arm 开发环境搭建-基于QEMU和Docker
  • QT5.12.1 ARM开发环境搭建 并 移植到RK3399 ubuntu16.04系统运行【完整版】
  • ARM开发比51开发高级吗—嵌入式就业技能分类
  • ARM裸机开发篇1:Cortex-A7开发环境搭建
  • qemu 搭建 ARM Linux环境
  • ARM 开发软件
  • ARM开发软件ADS教程
  • ARM开发——常见仿真器
  • arm裸机开发
  • ARM开发工具
  • Golang语言移植-ARM开发环境搭建
  • eclipse 搭建ARM开发环境
  • ARM开发初级-Windows环境下的STM32开发环境搭建(包含missing compiler version 5的解决方法)-学习笔记02
  • 基于Ubuntu 18.04打造嵌入式arm开发环境
  • 用QEMU搭建arm开发环境之一:QEMU能干啥
  • ARM7开发软件安装步骤
  • 嵌入式系统开发与应用——ARM 开发环境搭建及GPIO控制LED实验
  • ARM开发入门
  • ARM与裸机开发教程
  • ARM处理器开发详解(一)
  • ARM处理器开发详解

nlp情感分析经典书籍推荐_通过监督学习对书籍进行情感分析相关推荐

  1. python树莓派经典书籍推荐_树莓派教程书籍推荐:带你玩转Raspberry Pi

    随着<星球大战><复仇者联盟><NASA>等科幻电影的热映,人工制作装置也更加受到人们关注,与这些电影有关的一切设备都显得非常有科技感,格调很高.本期树莓派教程书籍 ...

  2. python数据可视化书籍推荐_数据可视化的优秀入门书籍有哪些?

    数据可视化方向 首先你需要考虑清楚"非常感兴趣的数据可视化"属于哪一类? 数据可视化是个非常宽泛的领域,大体可以分为"信息图Infographic"和" ...

  3. python软件测试书籍推荐_自学软件测试看什么书入门比较好呢?

    截止到2019年10月底,本回答已经更新3126字,分不同阶段推荐了13本经典书籍,关注我,持续更新! ----------///分割线///---------- 原回答: 书不在多,关键是精! 入门 ...

  4. python并发编程书籍推荐_《吐血整理》-顶级程序员书单集

    <程序人生>十年风雨技术人的书单整理 前言 王潇:格局决定了一个人的梦想,梦想反过来决定行为. 那格局是什么呢? 格局是你能够看见的深度.广度和密度. 王潇认为,格局是一本本书搭建起来的, ...

  5. python量化自学书籍推荐_量化投资学习推荐的书籍都有哪些?

    给大家简单推荐介绍3本书吧这些都是比较实用的,入门还是高手级别的都有. 1. 打开量化投资的黑箱 这本书的作者里什·纳兰(Rishi K. Narang)是华尔街顶级数量金融专家,资深对冲基金经理.& ...

  6. python国内书籍推荐_久等了,你要的 Python 书籍推荐,来了!

    前言 时不时有小伙伴私信问我有什么好一些的 Python 书籍推荐,想要学习学习. 那么今天就来给大伙说道说道,我会划分为以下几个分类,让不同阶段的朋友可以根据自身的情况,选择适合自己当下学习的 Py ...

  7. 交互设计专业书籍推荐(内有部分书籍电子版下载)

    整理前言: 什么书籍能帮助交互设计师更好学习交互设计,提升实战能力呢?曾经也读过很多关于交互设计与用户体验的国外书籍,但想针对实战的书籍确实比较少.交互设计是设计学科的一个分支,设计的最高境界为禅意最 ...

  8. 计算机视觉算法实战书籍推荐_岗位内推 | 字节跳动招聘NLP、计算机视觉、推荐算法实习生...

    PaperWeekly 致力于推荐最棒的工作机会,精准地为其找到最佳求职者,做连接优质企业和优质人才的桥梁.如果你需要我们帮助你发布实习或全职岗位,请添加微信号「pwbot02」. NLP算法实习生 ...

  9. python国内书籍推荐_这些都是Python官方推荐的最好的书籍

    转行学Python有前途吗?这个答案是肯定的,AI课程都已经进入小学教材了,未来Python趋势无疑是光明的,但是如何学习Python,很多Python小白都来问小编有什么适合的Python入门书籍推 ...

  10. 适合新手的python书籍推荐_推荐一本适合初学者全面自学python的书(附赠电子书)...

    原标题:推荐一本适合初学者全面自学python的书(附赠电子书) 今天一个朋友问我:有个朋友要学习 python,她属于那种特别能啃书的,让我推荐.我学 python 都是无师自通的,没有看过什么书, ...

最新文章

  1. 《疯狂Java讲义》2
  2. linux centos7开启IP转发、路由转发解决docker 端口映射 及外部无法访问问题
  3. 同为Chromium浏览器,Edge却被“特别关照”
  4. java 物理内存_聊聊Java中的内存
  5. mysql sysdate本周_oracle 、mysql 取昨天 前天 本周 数据
  6. 【opencv】【图像梯度】
  7. 如何明晰定位与责任_公司股权决定公司决策,如何设计合理公司股权架构?
  8. 本地提交到yarn_Yarn运行Flink作业 0449
  9. eclipse订制快捷键
  10. 计算机应用cad题库,cad试题库
  11. 一个简单的微信小程序支付demo
  12. 模仿LordPE写了个PE解析工具
  13. 工业相机和镜头主要参数解释
  14. android 画三角形
  15. CTE表--SQLSERVER2005看得见的性能提升
  16. 交易员都是用什么方法盈利的?
  17. React 下一代数据流 hox vs Recoil 使用对比分析
  18. 从零开始学习React——(十二):React单项数据流和混用jQuery以及函数式编程
  19. 如何才能够有效长高?避免走弯路
  20. 用javascript编写的小游戏-打砖块

热门文章

  1. 平凡的生活,不平凡的2020
  2. 详解Python曲线拟合
  3. @Autowired实现的原理
  4. win10文件夹加密_Win10系统自带加密文件夹的两种方法
  5. 贴片电阻封装规格及阻值标注方法
  6. pyautogui入门学习之消息盒子
  7. pro android python with sl4a,Pro Android Python with SL4A
  8. gta5 apk android,gta5apk
  9. 计算机专业学生参加igem,喜讯:深圳大学iGEM团队再获金奖,并获得最佳单项奖,为今年大中华地区iGEM参赛队伍最佳成绩!-深圳大学生命与海洋科学学院...
  10. [Linux]CentOS修改YUM镜像地址提高下载速度