我尝试使用Python的NLTK模块对NLP进行第一次尝试,对选定的推文进行情绪分析。我一直关注this tutorial并已下载Sentiment140 Tweet Corpus作为我的培训数据集,因为这仅用于教育目的(包含约1.6万手分类推文)。
我的代码可以找到here。请注意,这是在Python 2中的iPython Notebook中完成的。
问题第1部分 我在训练集中使用10,000行测试我的代码,看它是否在进行所有1.6m行之前是否有效。当我运行代码时,第96行返回None:
print classifier.show_most_informative_features(32)
Most Informative Features
None
但是,教程建议我应该看到如下内容:
Most Informative Features
contains(not) = False positi : negati = 1.6 : 1.0
contains(tired) = False positi : negati = 1.2 : 1.0
contains(excited) = False negati : positi = 1.2 : 1.0
contains(great) = False negati : positi = 1.2 : 1.0
contains(looking) = False positi : negati = 1.2 : 1.0
contains(like) = False positi : negati = 1.2 : 1.0
contains(love) = False negati : positi = 1.2 : 1.0
contains(amazing) = False negati : positi = 1.2 : 1.0
contains(enemy) = False positi : negati = 1.2 : 1.0
contains(about) = False negati : positi = 1.2 : 1.0
contains(best) = False negati : positi = 1.2 : 1.0
contains(forward) = False positi : negati = 1.2 : 1.0
contains(friend) = False negati : positi = 1.2 : 1.0
contains(horrible) = False positi : negati = 1.2 : 1.0
我使用第96行作为指示符告诉我分类器是否有效。就我已经尝试过的修复方面而言:我在教程中看到一条评论建议第87行:
training_set = nltk.classify.util.apply_features(extract_features, tweets)
而不是目前的情况:
training_set = nltk.classify.apply_features(extract_features, tweets)
我尝试了这两种变体。
在我运行完整的1.6米行数据集来训练分类器之前,我想解决这个问题。
以下是笔记本的所有import语句(某些import语句用于笔记本的其他区域):
import pandas as pd
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap
from pandas.tseries.resample import TimeGrouper
from pandas.tseries.offsets import DateOffset
import nltk
from nltk.corpus import stopwords
from nltk import FreqDist
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import subjectivity
from nltk.sentiment import SentimentAnalyzer
import nltk.sentiment.util
import csv
import re
import networkx as nx
import time
%matplotlib inline
%pylab inline
问题第2部分 如何调整此代码以返回极性分数。类似的东西:
compound: -0.6759, neg: 0.41, neu: 0.59, pos: 0.0
基于this NLTK page,似乎我会调用.polarity_socres()方法,但我不确定在我的代码中我甚至会这样做。以下是返回上述内容的代码:
sid = SentimentIntensityAnalyzer()
for sentence in sentences:
print(sentence)
ss = sid.polarity_scores(sentence)
for k in sorted(ss):
print('{0}: {1}, '.format(k, ss[k]), end='')