人工智能:python 实现 第十章,NLP 第七天,构建语义分析器

构建语义分析器

语意分析是确定给定文本片段的语意的过程。例如,它能够被用来确定一个电影评论是积极还是负面的 。这是自然语言处理用的最广的一个应用。我们也能够根据手头的问题添加更多的类别。这种技术被广泛的使用去获取人们对一个特定的产品,牌子或主题的感觉。它被频繁使用来分析市场活动,选举投票,社会媒体形象,电子商务网站的产品评价等等。那如何确定影评的语意呢?

我们将使用朴素贝叶斯分类器来构建分类器。我们首先要提取在文本中的所有唯一单词。NLTK 分类器以数据以字典的形式排列以便分类器能够接受。我们要将文本数据分成训练集和测试集,我们训练朴素贝叶斯分类器将影评分成正面的和负面的。我们也会打印出最重要的单词来指出正面和负面的影评。这个信息是有用的,因为它告诉我们那些单词用来标识各种反应。

创建一个新的python文件,输入以下代码:

#导入如下的包
from nltk.corpus import movie_reviews
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy as nltk_accuracy

#定义函数来构建一个基于输入数据的的字典对象并返回
#从输入数据列表提取特征
def extract_features(words):
    return dict([(word,True) for word in words])

#定义主函数
if __name__ == '__main__':
    #从语料库载入影评
    fileids_pos = movie_reviews.fileids('pos')
    fileids_neg = movie_reviews.fileids('neg')

    #从影评中提取特征
    features_pos = [(extract_features(movie_reviews.words(fileids = [f])),'Positive') for f in fileids_pos]

    features_neg = [(extract_features(movie_reviews.words(fileids = [f])),'Negative') for f in fileids_neg]

    #定义训练和测试集
    threshold = 0.8
    num_pos = int(threshold*len(features_pos))
    num_neg = int(threshold*len(features_neg))

    features_train = features_pos[:num_pos]+features_neg[:num_neg]
    features_test = features_pos[num_pos:]+features_neg[num_neg:]
    
    #打印被使用的数据点数目
    print('\nNumber of Training datapoints:',len(features_train))
    print('\nNumber of Testing datapoints:',len(features_test))

    #训练一个朴素贝叶斯分类器
    classifier = NaiveBayesClassifier.train(features_train)
    print('\nAccuracy of the classifier:',nltk_accuracy(classifier,features_test))

    N =15
    print('\nTop'+str(N) + 'most information words:')
    for i,item in enumerate(classifier.most_informative_features()):
        print(str(i+1)+'.'+item[0])
        if i==N-1:
            break

    #测试输入的影评
    input_reviews = ['the costumes in this movie were great',
                      'I thik the story was terrible and the characters were very weak',
                     'People say that the director of the movie is amazing',
                     'This is such an idiotic movie. I will not recommand it to anyone']
    

    print("\nMovie review predictions:")
    for review in input_reviews:
        print("\nReview:", review)

        # Compute the probabilities
        probabilities = classifier.prob_classify(extract_features(review.split()))

        # Pick the maximum value
        predicted_sentiment = probabilities.max()

        # Print outputs
        print("Predicted sentiment:", predicted_sentiment)
        print("Probability:", round(probabilities.prob(predicted_sentiment), 2))

运行结果如下:


可以看到预测结果是正确的


  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值