社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  机器学习算法

【火炉炼AI】机器学习041-NLP句子情感分析

炼丹老顽童 • 5 年前 • 494 次点击  
阅读 12

【火炉炼AI】机器学习041-NLP句子情感分析

【火炉炼AI】机器学习041-NLP句子情感分析

(本文所使用的Python库和版本号: Python 3.6, Numpy 1.14, scikit-learn 0.19, matplotlib 2.2 )

在NLP中有一个非常实用的应用领域--情感分析,情感分析是用NLP技术分析一段给定文本的情感类型,是积极的还是消极的,是乐观的还是悲观的等。比如在股市中,我们知道,往往大众最悲观的时候往往是股市的大底,而最乐观的时候却是股市的顶部,所以,如果我们能够掌握大众的心里情感状况,那么也就能大概知道股市的底和顶,换言之,也就能够在股市上挣得大把大把的银子了。


1. 准备数据集

本项目所使用的数据集也是由nltk内部提供,其中的corpus模块中有movies_reviews,可以给我们提供“积极”和“消极”的语句文本。

# 1, 准备数据集
from nltk.corpus import movie_reviews
pos_fileIds=movie_reviews.fileids('pos') # 加载积极文本文件
neg_fileIds=movie_reviews.fileids('neg') # 消极文本文件

print(len(pos_fileIds)) # 1000
print(len(neg_fileIds)) # 1000 

print(pos_fileIds[:5])
print(neg_fileIds[:5])

# 由此可看出,movie_reviews.fileids是加载各种类别文本的文件,
# 并返回该文件名组成的list

# 如果想要查看某个文本文件的内容,可以使用
print(movie_reviews.words(fileids=['pos/cv000_29590.txt']))
复制代码

-------------------------------------输---------出--------------------------------

1000 1000 ['pos/cv000_29590.txt', 'pos/cv001_18431.txt', 'pos/cv002_15918.txt', 'pos/cv003_11664.txt', 'pos/cv004_11636.txt'] ['neg/cv000_29416.txt', 'neg/cv001_19502.txt', 'neg/cv002_17424.txt', 'neg/cv003_12683.txt', 'neg/cv004_12641.txt'] ['films', 'adapted', 'from', 'comic', 'books', 'have', ...]

--------------------------------------------完-------------------------------------

虽然上面把文本文件的名称提取出来,但是我们还需要从这些txt文件中提取出所需要的特征,使用这些特征才能进行后续的分类器建模。

# 2, 处理数据集
def extract_features(word_list):
    '''专门一个函数来提取特征'''
    return dict([(word,True) for word in word_list]) # 此处加True的作用是构成dict,实质意义不大

pos_features=[(extract_features(movie_reviews.words(fileids=[f])),'Pos') 
              for f in pos_fileIds]
neg_features=[(extract_features(movie_reviews.words(fileids=[f])),'Neg') 
              for f in neg_fileIds]
print(pos_features[:3]) # 打印下看看内容是否正确

dataset=pos_features+neg_features # 将两部分结合起来作为一个dataset
复制代码

打印出来的结果很长,可以参考我的github里面的代码。


2. 建立模型,训练特征

# 构建模型,训练模型
from nltk import NaiveBayesClassifier
from nltk.classify import accuracy as nltk_accuracy

np.random.shuffle(dataset)
rows=int(len(dataset)*0.8) # 80%为train set
train_set,test_set=dataset[:rows],dataset[rows:]
print('Num of train_set: ',len(train_set),
      '/nNum of test_set: ',len(test_set))
clf=NaiveBayesClassifier.train(train_set)

# 查看该模型在test set上的表现
acc=nltk_accuracy(clf,test_set)
print('Accuracy: {:.2f}%'.format(acc*100))
复制代码

-------------------输---------出-----------------------

Num of train_set: 1600
Num of test_set: 400
Accuracy: 70.75%

-------------------------完---------------------------

由此可以看出该模型在测试集上的表现为:准确率70.75%

# 查看模型内部信息
# 该分类器是分析某段文本中哪些单词与“积极”的关联最大,
# 哪些与“消极”的关联最大,进而分析这些关键词的出现来判断某句话是积极或消极

# 打印这些关键词
for key_word in clf.most_informative_features()[:10]:
    print(key_word[0])
复制代码

----------------输---------出-----------------------

outstanding
insulting
ludicrous
affecting
magnificent
breathtaking
avoids
strongest
fascination
slip

------------------------完-------------------------

可以看出,这些关键词对于区分一个句子是积极还是消极有着至关重要的作用,或者说,如果某个句子中有了这些关键词,就可以区分这个句子的情感是积极还是消极,这些单词越多,模型预测的准确率就越高。


3. 用成熟模型预测新样本

# 用该模型来预测新样本,查看新句子的情感是积极还是消极
new_samples = [
        "It is an amazing movie", 
        "This is a dull movie. I would never recommend it to anyone.",
        "The cinematography is pretty great in this movie", 
        "The direction was terrible and the story was all over the place" 
    ]

for sample in new_samples:
    predict_P=clf.prob_classify(extract_features(sample.split()))
    pred_sentiment=predict_P.max()
    print('Sample: {}, Type: {}, Probability: {:.2f}%'.format(
        sample,pred_sentiment,predict_P.prob(pred_sentiment)*100))
复制代码

----------------输---------出-----------------------

Sample: It is an amazing movie, Type: Pos, Probability: 61.45%
Sample: This is a dull movie. I would never recommend it to anyone., Type: Neg, Probability: 80.12%
Sample: The cinematography is pretty great in this movie, Type: Pos, Probability: 63.63%
Sample: The direction was terrible and the story was all over the place, Type: Neg, Probability: 63.89%

------------------------完----------------------------

########################小**********结###############################

1,NLTK中所使用的分类器需要用dict类型的数据作为features来数据,故而我们需要自定义一个extract_features函数,来将单词转变为dict类型。

2,NLTK中已经集成了很多分类器,比如NaiveBayesClassifier,这些分类器已经集成了字符串处理方面的各种细节,使用起来很方便。

#################################################################


注:本部分代码已经全部上传到(我的github)上,欢迎下载。

参考资料:

1, Python机器学习经典实例,Prateek Joshi著,陶俊杰,陈小莉译


今天看啥 - 高品质阅读平台
本文地址:http://www.jintiankansha.me/t/6cHE8U45vQ
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/25195
 
494 次点击