util.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. # coding: utf-8
  2. #
  3. # Natural Language Toolkit: Sentiment Analyzer
  4. #
  5. # Copyright (C) 2001-2020 NLTK Project
  6. # Author: Pierpaolo Pantone <24alsecondo@gmail.com>
  7. # URL: <http://nltk.org/>
  8. # For license information, see LICENSE.TXT
  9. """
  10. Utility methods for Sentiment Analysis.
  11. """
  12. import codecs
  13. import csv
  14. import json
  15. import pickle
  16. import random
  17. import re
  18. import sys
  19. import time
  20. from copy import deepcopy
  21. import nltk
  22. from nltk.corpus import CategorizedPlaintextCorpusReader
  23. from nltk.data import load
  24. from nltk.tokenize.casual import EMOTICON_RE
  25. # ////////////////////////////////////////////////////////////
  26. # { Regular expressions
  27. # ////////////////////////////////////////////////////////////
  28. # Regular expression for negation by Christopher Potts
  29. NEGATION = r"""
  30. (?:
  31. ^(?:never|no|nothing|nowhere|noone|none|not|
  32. havent|hasnt|hadnt|cant|couldnt|shouldnt|
  33. wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
  34. )$
  35. )
  36. |
  37. n't"""
  38. NEGATION_RE = re.compile(NEGATION, re.VERBOSE)
  39. CLAUSE_PUNCT = r"^[.:;!?]$"
  40. CLAUSE_PUNCT_RE = re.compile(CLAUSE_PUNCT)
  41. # Happy and sad emoticons
  42. HAPPY = set(
  43. [
  44. ":-)",
  45. ":)",
  46. ";)",
  47. ":o)",
  48. ":]",
  49. ":3",
  50. ":c)",
  51. ":>",
  52. "=]",
  53. "8)",
  54. "=)",
  55. ":}",
  56. ":^)",
  57. ":-D",
  58. ":D",
  59. "8-D",
  60. "8D",
  61. "x-D",
  62. "xD",
  63. "X-D",
  64. "XD",
  65. "=-D",
  66. "=D",
  67. "=-3",
  68. "=3",
  69. ":-))",
  70. ":'-)",
  71. ":')",
  72. ":*",
  73. ":^*",
  74. ">:P",
  75. ":-P",
  76. ":P",
  77. "X-P",
  78. "x-p",
  79. "xp",
  80. "XP",
  81. ":-p",
  82. ":p",
  83. "=p",
  84. ":-b",
  85. ":b",
  86. ">:)",
  87. ">;)",
  88. ">:-)",
  89. "<3",
  90. ]
  91. )
  92. SAD = set(
  93. [
  94. ":L",
  95. ":-/",
  96. ">:/",
  97. ":S",
  98. ">:[",
  99. ":@",
  100. ":-(",
  101. ":[",
  102. ":-||",
  103. "=L",
  104. ":<",
  105. ":-[",
  106. ":-<",
  107. "=\\",
  108. "=/",
  109. ">:(",
  110. ":(",
  111. ">.<",
  112. ":'-(",
  113. ":'(",
  114. ":\\",
  115. ":-c",
  116. ":c",
  117. ":{",
  118. ">:\\",
  119. ";(",
  120. ]
  121. )
  122. def timer(method):
  123. """
  124. A timer decorator to measure execution performance of methods.
  125. """
  126. def timed(*args, **kw):
  127. start = time.time()
  128. result = method(*args, **kw)
  129. end = time.time()
  130. tot_time = end - start
  131. hours = tot_time // 3600
  132. mins = tot_time // 60 % 60
  133. # in Python 2.x round() will return a float, so we convert it to int
  134. secs = int(round(tot_time % 60))
  135. if hours == 0 and mins == 0 and secs < 10:
  136. print("[TIMER] {0}(): {:.3f} seconds".format(method.__name__, tot_time))
  137. else:
  138. print(
  139. "[TIMER] {0}(): {1}h {2}m {3}s".format(
  140. method.__name__, hours, mins, secs
  141. )
  142. )
  143. return result
  144. return timed
  145. # ////////////////////////////////////////////////////////////
  146. # { Feature extractor functions
  147. # ////////////////////////////////////////////////////////////
  148. """
  149. Feature extractor functions are declared outside the SentimentAnalyzer class.
  150. Users should have the possibility to create their own feature extractors
  151. without modifying SentimentAnalyzer.
  152. """
  153. def extract_unigram_feats(document, unigrams, handle_negation=False):
  154. """
  155. Populate a dictionary of unigram features, reflecting the presence/absence in
  156. the document of each of the tokens in `unigrams`.
  157. :param document: a list of words/tokens.
  158. :param unigrams: a list of words/tokens whose presence/absence has to be
  159. checked in `document`.
  160. :param handle_negation: if `handle_negation == True` apply `mark_negation`
  161. method to `document` before checking for unigram presence/absence.
  162. :return: a dictionary of unigram features {unigram : boolean}.
  163. >>> words = ['ice', 'police', 'riot']
  164. >>> document = 'ice is melting due to global warming'.split()
  165. >>> sorted(extract_unigram_feats(document, words).items())
  166. [('contains(ice)', True), ('contains(police)', False), ('contains(riot)', False)]
  167. """
  168. features = {}
  169. if handle_negation:
  170. document = mark_negation(document)
  171. for word in unigrams:
  172. features["contains({0})".format(word)] = word in set(document)
  173. return features
  174. def extract_bigram_feats(document, bigrams):
  175. """
  176. Populate a dictionary of bigram features, reflecting the presence/absence in
  177. the document of each of the tokens in `bigrams`. This extractor function only
  178. considers contiguous bigrams obtained by `nltk.bigrams`.
  179. :param document: a list of words/tokens.
  180. :param unigrams: a list of bigrams whose presence/absence has to be
  181. checked in `document`.
  182. :return: a dictionary of bigram features {bigram : boolean}.
  183. >>> bigrams = [('global', 'warming'), ('police', 'prevented'), ('love', 'you')]
  184. >>> document = 'ice is melting due to global warming'.split()
  185. >>> sorted(extract_bigram_feats(document, bigrams).items())
  186. [('contains(global - warming)', True), ('contains(love - you)', False),
  187. ('contains(police - prevented)', False)]
  188. """
  189. features = {}
  190. for bigr in bigrams:
  191. features["contains({0} - {1})".format(bigr[0], bigr[1])] = bigr in nltk.bigrams(
  192. document
  193. )
  194. return features
  195. # ////////////////////////////////////////////////////////////
  196. # { Helper Functions
  197. # ////////////////////////////////////////////////////////////
  198. def mark_negation(document, double_neg_flip=False, shallow=False):
  199. """
  200. Append _NEG suffix to words that appear in the scope between a negation
  201. and a punctuation mark.
  202. :param document: a list of words/tokens, or a tuple (words, label).
  203. :param shallow: if True, the method will modify the original document in place.
  204. :param double_neg_flip: if True, double negation is considered affirmation
  205. (we activate/deactivate negation scope everytime we find a negation).
  206. :return: if `shallow == True` the method will modify the original document
  207. and return it. If `shallow == False` the method will return a modified
  208. document, leaving the original unmodified.
  209. >>> sent = "I didn't like this movie . It was bad .".split()
  210. >>> mark_negation(sent)
  211. ['I', "didn't", 'like_NEG', 'this_NEG', 'movie_NEG', '.', 'It', 'was', 'bad', '.']
  212. """
  213. if not shallow:
  214. document = deepcopy(document)
  215. # check if the document is labeled. If so, do not consider the label.
  216. labeled = document and isinstance(document[0], (tuple, list))
  217. if labeled:
  218. doc = document[0]
  219. else:
  220. doc = document
  221. neg_scope = False
  222. for i, word in enumerate(doc):
  223. if NEGATION_RE.search(word):
  224. if not neg_scope or (neg_scope and double_neg_flip):
  225. neg_scope = not neg_scope
  226. continue
  227. else:
  228. doc[i] += "_NEG"
  229. elif neg_scope and CLAUSE_PUNCT_RE.search(word):
  230. neg_scope = not neg_scope
  231. elif neg_scope and not CLAUSE_PUNCT_RE.search(word):
  232. doc[i] += "_NEG"
  233. return document
  234. def output_markdown(filename, **kwargs):
  235. """
  236. Write the output of an analysis to a file.
  237. """
  238. with codecs.open(filename, "at") as outfile:
  239. text = "\n*** \n\n"
  240. text += "{0} \n\n".format(time.strftime("%d/%m/%Y, %H:%M"))
  241. for k in sorted(kwargs):
  242. if isinstance(kwargs[k], dict):
  243. dictionary = kwargs[k]
  244. text += " - **{0}:**\n".format(k)
  245. for entry in sorted(dictionary):
  246. text += " - {0}: {1} \n".format(entry, dictionary[entry])
  247. elif isinstance(kwargs[k], list):
  248. text += " - **{0}:**\n".format(k)
  249. for entry in kwargs[k]:
  250. text += " - {0}\n".format(entry)
  251. else:
  252. text += " - **{0}:** {1} \n".format(k, kwargs[k])
  253. outfile.write(text)
  254. def split_train_test(all_instances, n=None):
  255. """
  256. Randomly split `n` instances of the dataset into train and test sets.
  257. :param all_instances: a list of instances (e.g. documents) that will be split.
  258. :param n: the number of instances to consider (in case we want to use only a
  259. subset).
  260. :return: two lists of instances. Train set is 8/10 of the total and test set
  261. is 2/10 of the total.
  262. """
  263. random.seed(12345)
  264. random.shuffle(all_instances)
  265. if not n or n > len(all_instances):
  266. n = len(all_instances)
  267. train_set = all_instances[: int(0.8 * n)]
  268. test_set = all_instances[int(0.8 * n) : n]
  269. return train_set, test_set
  270. def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
  271. try:
  272. import matplotlib.pyplot as plt
  273. except ImportError:
  274. raise ImportError(
  275. "The plot function requires matplotlib to be installed."
  276. "See http://matplotlib.org/"
  277. )
  278. plt.locator_params(axis="y", nbins=3)
  279. axes = plt.axes()
  280. axes.yaxis.grid()
  281. plt.plot(x_values, y_values, "ro", color="red")
  282. plt.ylim(ymin=-1.2, ymax=1.2)
  283. plt.tight_layout(pad=5)
  284. if x_labels:
  285. plt.xticks(x_values, x_labels, rotation="vertical")
  286. if y_labels:
  287. plt.yticks([-1, 0, 1], y_labels, rotation="horizontal")
  288. # Pad margins so that markers are not clipped by the axes
  289. plt.margins(0.2)
  290. plt.show()
  291. # ////////////////////////////////////////////////////////////
  292. # { Parsing and conversion functions
  293. # ////////////////////////////////////////////////////////////
  294. def json2csv_preprocess(
  295. json_file,
  296. outfile,
  297. fields,
  298. encoding="utf8",
  299. errors="replace",
  300. gzip_compress=False,
  301. skip_retweets=True,
  302. skip_tongue_tweets=True,
  303. skip_ambiguous_tweets=True,
  304. strip_off_emoticons=True,
  305. remove_duplicates=True,
  306. limit=None,
  307. ):
  308. """
  309. Convert json file to csv file, preprocessing each row to obtain a suitable
  310. dataset for tweets Semantic Analysis.
  311. :param json_file: the original json file containing tweets.
  312. :param outfile: the output csv filename.
  313. :param fields: a list of fields that will be extracted from the json file and
  314. kept in the output csv file.
  315. :param encoding: the encoding of the files.
  316. :param errors: the error handling strategy for the output writer.
  317. :param gzip_compress: if True, create a compressed GZIP file.
  318. :param skip_retweets: if True, remove retweets.
  319. :param skip_tongue_tweets: if True, remove tweets containing ":P" and ":-P"
  320. emoticons.
  321. :param skip_ambiguous_tweets: if True, remove tweets containing both happy
  322. and sad emoticons.
  323. :param strip_off_emoticons: if True, strip off emoticons from all tweets.
  324. :param remove_duplicates: if True, remove tweets appearing more than once.
  325. :param limit: an integer to set the number of tweets to convert. After the
  326. limit is reached the conversion will stop. It can be useful to create
  327. subsets of the original tweets json data.
  328. """
  329. with codecs.open(json_file, encoding=encoding) as fp:
  330. (writer, outf) = _outf_writer(outfile, encoding, errors, gzip_compress)
  331. # write the list of fields as header
  332. writer.writerow(fields)
  333. if remove_duplicates == True:
  334. tweets_cache = []
  335. i = 0
  336. for line in fp:
  337. tweet = json.loads(line)
  338. row = extract_fields(tweet, fields)
  339. try:
  340. text = row[fields.index("text")]
  341. # Remove retweets
  342. if skip_retweets == True:
  343. if re.search(r"\bRT\b", text):
  344. continue
  345. # Remove tweets containing ":P" and ":-P" emoticons
  346. if skip_tongue_tweets == True:
  347. if re.search(r"\:\-?P\b", text):
  348. continue
  349. # Remove tweets containing both happy and sad emoticons
  350. if skip_ambiguous_tweets == True:
  351. all_emoticons = EMOTICON_RE.findall(text)
  352. if all_emoticons:
  353. if (set(all_emoticons) & HAPPY) and (set(all_emoticons) & SAD):
  354. continue
  355. # Strip off emoticons from all tweets
  356. if strip_off_emoticons == True:
  357. row[fields.index("text")] = re.sub(
  358. r"(?!\n)\s+", " ", EMOTICON_RE.sub("", text)
  359. )
  360. # Remove duplicate tweets
  361. if remove_duplicates == True:
  362. if row[fields.index("text")] in tweets_cache:
  363. continue
  364. else:
  365. tweets_cache.append(row[fields.index("text")])
  366. except ValueError:
  367. pass
  368. writer.writerow(row)
  369. i += 1
  370. if limit and i >= limit:
  371. break
  372. outf.close()
  373. def parse_tweets_set(
  374. filename, label, word_tokenizer=None, sent_tokenizer=None, skip_header=True
  375. ):
  376. """
  377. Parse csv file containing tweets and output data a list of (text, label) tuples.
  378. :param filename: the input csv filename.
  379. :param label: the label to be appended to each tweet contained in the csv file.
  380. :param word_tokenizer: the tokenizer instance that will be used to tokenize
  381. each sentence into tokens (e.g. WordPunctTokenizer() or BlanklineTokenizer()).
  382. If no word_tokenizer is specified, tweets will not be tokenized.
  383. :param sent_tokenizer: the tokenizer that will be used to split each tweet into
  384. sentences.
  385. :param skip_header: if True, skip the first line of the csv file (which usually
  386. contains headers).
  387. :return: a list of (text, label) tuples.
  388. """
  389. tweets = []
  390. if not sent_tokenizer:
  391. sent_tokenizer = load("tokenizers/punkt/english.pickle")
  392. with codecs.open(filename, "rt") as csvfile:
  393. reader = csv.reader(csvfile)
  394. if skip_header == True:
  395. next(reader, None) # skip the header
  396. i = 0
  397. for tweet_id, text in reader:
  398. # text = text[1]
  399. i += 1
  400. sys.stdout.write("Loaded {0} tweets\r".format(i))
  401. # Apply sentence and word tokenizer to text
  402. if word_tokenizer:
  403. tweet = [
  404. w
  405. for sent in sent_tokenizer.tokenize(text)
  406. for w in word_tokenizer.tokenize(sent)
  407. ]
  408. else:
  409. tweet = text
  410. tweets.append((tweet, label))
  411. print("Loaded {0} tweets".format(i))
  412. return tweets
  413. # ////////////////////////////////////////////////////////////
  414. # { Demos
  415. # ////////////////////////////////////////////////////////////
  416. def demo_tweets(trainer, n_instances=None, output=None):
  417. """
  418. Train and test Naive Bayes classifier on 10000 tweets, tokenized using
  419. TweetTokenizer.
  420. Features are composed of:
  421. - 1000 most frequent unigrams
  422. - 100 top bigrams (using BigramAssocMeasures.pmi)
  423. :param trainer: `train` method of a classifier.
  424. :param n_instances: the number of total tweets that have to be used for
  425. training and testing. Tweets will be equally split between positive and
  426. negative.
  427. :param output: the output file where results have to be reported.
  428. """
  429. from nltk.tokenize import TweetTokenizer
  430. from nltk.sentiment import SentimentAnalyzer
  431. from nltk.corpus import twitter_samples, stopwords
  432. # Different customizations for the TweetTokenizer
  433. tokenizer = TweetTokenizer(preserve_case=False)
  434. # tokenizer = TweetTokenizer(preserve_case=True, strip_handles=True)
  435. # tokenizer = TweetTokenizer(reduce_len=True, strip_handles=True)
  436. if n_instances is not None:
  437. n_instances = int(n_instances / 2)
  438. fields = ["id", "text"]
  439. positive_json = twitter_samples.abspath("positive_tweets.json")
  440. positive_csv = "positive_tweets.csv"
  441. json2csv_preprocess(positive_json, positive_csv, fields, limit=n_instances)
  442. negative_json = twitter_samples.abspath("negative_tweets.json")
  443. negative_csv = "negative_tweets.csv"
  444. json2csv_preprocess(negative_json, negative_csv, fields, limit=n_instances)
  445. neg_docs = parse_tweets_set(negative_csv, label="neg", word_tokenizer=tokenizer)
  446. pos_docs = parse_tweets_set(positive_csv, label="pos", word_tokenizer=tokenizer)
  447. # We separately split subjective and objective instances to keep a balanced
  448. # uniform class distribution in both train and test sets.
  449. train_pos_docs, test_pos_docs = split_train_test(pos_docs)
  450. train_neg_docs, test_neg_docs = split_train_test(neg_docs)
  451. training_tweets = train_pos_docs + train_neg_docs
  452. testing_tweets = test_pos_docs + test_neg_docs
  453. sentim_analyzer = SentimentAnalyzer()
  454. # stopwords = stopwords.words('english')
  455. # all_words = [word for word in sentim_analyzer.all_words(training_tweets) if word.lower() not in stopwords]
  456. all_words = [word for word in sentim_analyzer.all_words(training_tweets)]
  457. # Add simple unigram word features
  458. unigram_feats = sentim_analyzer.unigram_word_feats(all_words, top_n=1000)
  459. sentim_analyzer.add_feat_extractor(extract_unigram_feats, unigrams=unigram_feats)
  460. # Add bigram collocation features
  461. bigram_collocs_feats = sentim_analyzer.bigram_collocation_feats(
  462. [tweet[0] for tweet in training_tweets], top_n=100, min_freq=12
  463. )
  464. sentim_analyzer.add_feat_extractor(
  465. extract_bigram_feats, bigrams=bigram_collocs_feats
  466. )
  467. training_set = sentim_analyzer.apply_features(training_tweets)
  468. test_set = sentim_analyzer.apply_features(testing_tweets)
  469. classifier = sentim_analyzer.train(trainer, training_set)
  470. # classifier = sentim_analyzer.train(trainer, training_set, max_iter=4)
  471. try:
  472. classifier.show_most_informative_features()
  473. except AttributeError:
  474. print(
  475. "Your classifier does not provide a show_most_informative_features() method."
  476. )
  477. results = sentim_analyzer.evaluate(test_set)
  478. if output:
  479. extr = [f.__name__ for f in sentim_analyzer.feat_extractors]
  480. output_markdown(
  481. output,
  482. Dataset="labeled_tweets",
  483. Classifier=type(classifier).__name__,
  484. Tokenizer=tokenizer.__class__.__name__,
  485. Feats=extr,
  486. Results=results,
  487. Instances=n_instances,
  488. )
  489. def demo_movie_reviews(trainer, n_instances=None, output=None):
  490. """
  491. Train classifier on all instances of the Movie Reviews dataset.
  492. The corpus has been preprocessed using the default sentence tokenizer and
  493. WordPunctTokenizer.
  494. Features are composed of:
  495. - most frequent unigrams
  496. :param trainer: `train` method of a classifier.
  497. :param n_instances: the number of total reviews that have to be used for
  498. training and testing. Reviews will be equally split between positive and
  499. negative.
  500. :param output: the output file where results have to be reported.
  501. """
  502. from nltk.corpus import movie_reviews
  503. from nltk.sentiment import SentimentAnalyzer
  504. if n_instances is not None:
  505. n_instances = int(n_instances / 2)
  506. pos_docs = [
  507. (list(movie_reviews.words(pos_id)), "pos")
  508. for pos_id in movie_reviews.fileids("pos")[:n_instances]
  509. ]
  510. neg_docs = [
  511. (list(movie_reviews.words(neg_id)), "neg")
  512. for neg_id in movie_reviews.fileids("neg")[:n_instances]
  513. ]
  514. # We separately split positive and negative instances to keep a balanced
  515. # uniform class distribution in both train and test sets.
  516. train_pos_docs, test_pos_docs = split_train_test(pos_docs)
  517. train_neg_docs, test_neg_docs = split_train_test(neg_docs)
  518. training_docs = train_pos_docs + train_neg_docs
  519. testing_docs = test_pos_docs + test_neg_docs
  520. sentim_analyzer = SentimentAnalyzer()
  521. all_words = sentim_analyzer.all_words(training_docs)
  522. # Add simple unigram word features
  523. unigram_feats = sentim_analyzer.unigram_word_feats(all_words, min_freq=4)
  524. sentim_analyzer.add_feat_extractor(extract_unigram_feats, unigrams=unigram_feats)
  525. # Apply features to obtain a feature-value representation of our datasets
  526. training_set = sentim_analyzer.apply_features(training_docs)
  527. test_set = sentim_analyzer.apply_features(testing_docs)
  528. classifier = sentim_analyzer.train(trainer, training_set)
  529. try:
  530. classifier.show_most_informative_features()
  531. except AttributeError:
  532. print(
  533. "Your classifier does not provide a show_most_informative_features() method."
  534. )
  535. results = sentim_analyzer.evaluate(test_set)
  536. if output:
  537. extr = [f.__name__ for f in sentim_analyzer.feat_extractors]
  538. output_markdown(
  539. output,
  540. Dataset="Movie_reviews",
  541. Classifier=type(classifier).__name__,
  542. Tokenizer="WordPunctTokenizer",
  543. Feats=extr,
  544. Results=results,
  545. Instances=n_instances,
  546. )
  547. def demo_subjectivity(trainer, save_analyzer=False, n_instances=None, output=None):
  548. """
  549. Train and test a classifier on instances of the Subjective Dataset by Pang and
  550. Lee. The dataset is made of 5000 subjective and 5000 objective sentences.
  551. All tokens (words and punctuation marks) are separated by a whitespace, so
  552. we use the basic WhitespaceTokenizer to parse the data.
  553. :param trainer: `train` method of a classifier.
  554. :param save_analyzer: if `True`, store the SentimentAnalyzer in a pickle file.
  555. :param n_instances: the number of total sentences that have to be used for
  556. training and testing. Sentences will be equally split between positive
  557. and negative.
  558. :param output: the output file where results have to be reported.
  559. """
  560. from nltk.sentiment import SentimentAnalyzer
  561. from nltk.corpus import subjectivity
  562. if n_instances is not None:
  563. n_instances = int(n_instances / 2)
  564. subj_docs = [
  565. (sent, "subj") for sent in subjectivity.sents(categories="subj")[:n_instances]
  566. ]
  567. obj_docs = [
  568. (sent, "obj") for sent in subjectivity.sents(categories="obj")[:n_instances]
  569. ]
  570. # We separately split subjective and objective instances to keep a balanced
  571. # uniform class distribution in both train and test sets.
  572. train_subj_docs, test_subj_docs = split_train_test(subj_docs)
  573. train_obj_docs, test_obj_docs = split_train_test(obj_docs)
  574. training_docs = train_subj_docs + train_obj_docs
  575. testing_docs = test_subj_docs + test_obj_docs
  576. sentim_analyzer = SentimentAnalyzer()
  577. all_words_neg = sentim_analyzer.all_words(
  578. [mark_negation(doc) for doc in training_docs]
  579. )
  580. # Add simple unigram word features handling negation
  581. unigram_feats = sentim_analyzer.unigram_word_feats(all_words_neg, min_freq=4)
  582. sentim_analyzer.add_feat_extractor(extract_unigram_feats, unigrams=unigram_feats)
  583. # Apply features to obtain a feature-value representation of our datasets
  584. training_set = sentim_analyzer.apply_features(training_docs)
  585. test_set = sentim_analyzer.apply_features(testing_docs)
  586. classifier = sentim_analyzer.train(trainer, training_set)
  587. try:
  588. classifier.show_most_informative_features()
  589. except AttributeError:
  590. print(
  591. "Your classifier does not provide a show_most_informative_features() method."
  592. )
  593. results = sentim_analyzer.evaluate(test_set)
  594. if save_analyzer == True:
  595. save_file(sentim_analyzer, "sa_subjectivity.pickle")
  596. if output:
  597. extr = [f.__name__ for f in sentim_analyzer.feat_extractors]
  598. output_markdown(
  599. output,
  600. Dataset="subjectivity",
  601. Classifier=type(classifier).__name__,
  602. Tokenizer="WhitespaceTokenizer",
  603. Feats=extr,
  604. Instances=n_instances,
  605. Results=results,
  606. )
  607. return sentim_analyzer
  608. def demo_sent_subjectivity(text):
  609. """
  610. Classify a single sentence as subjective or objective using a stored
  611. SentimentAnalyzer.
  612. :param text: a sentence whose subjectivity has to be classified.
  613. """
  614. from nltk.classify import NaiveBayesClassifier
  615. from nltk.tokenize import regexp
  616. word_tokenizer = regexp.WhitespaceTokenizer()
  617. try:
  618. sentim_analyzer = load("sa_subjectivity.pickle")
  619. except LookupError:
  620. print("Cannot find the sentiment analyzer you want to load.")
  621. print("Training a new one using NaiveBayesClassifier.")
  622. sentim_analyzer = demo_subjectivity(NaiveBayesClassifier.train, True)
  623. # Tokenize and convert to lower case
  624. tokenized_text = [word.lower() for word in word_tokenizer.tokenize(text)]
  625. print(sentim_analyzer.classify(tokenized_text))
  626. def demo_liu_hu_lexicon(sentence, plot=False):
  627. """
  628. Basic example of sentiment classification using Liu and Hu opinion lexicon.
  629. This function simply counts the number of positive, negative and neutral words
  630. in the sentence and classifies it depending on which polarity is more represented.
  631. Words that do not appear in the lexicon are considered as neutral.
  632. :param sentence: a sentence whose polarity has to be classified.
  633. :param plot: if True, plot a visual representation of the sentence polarity.
  634. """
  635. from nltk.corpus import opinion_lexicon
  636. from nltk.tokenize import treebank
  637. tokenizer = treebank.TreebankWordTokenizer()
  638. pos_words = 0
  639. neg_words = 0
  640. tokenized_sent = [word.lower() for word in tokenizer.tokenize(sentence)]
  641. x = list(range(len(tokenized_sent))) # x axis for the plot
  642. y = []
  643. for word in tokenized_sent:
  644. if word in opinion_lexicon.positive():
  645. pos_words += 1
  646. y.append(1) # positive
  647. elif word in opinion_lexicon.negative():
  648. neg_words += 1
  649. y.append(-1) # negative
  650. else:
  651. y.append(0) # neutral
  652. if pos_words > neg_words:
  653. print("Positive")
  654. elif pos_words < neg_words:
  655. print("Negative")
  656. elif pos_words == neg_words:
  657. print("Neutral")
  658. if plot == True:
  659. _show_plot(
  660. x, y, x_labels=tokenized_sent, y_labels=["Negative", "Neutral", "Positive"]
  661. )
  662. def demo_vader_instance(text):
  663. """
  664. Output polarity scores for a text using Vader approach.
  665. :param text: a text whose polarity has to be evaluated.
  666. """
  667. from nltk.sentiment import SentimentIntensityAnalyzer
  668. vader_analyzer = SentimentIntensityAnalyzer()
  669. print(vader_analyzer.polarity_scores(text))
  670. def demo_vader_tweets(n_instances=None, output=None):
  671. """
  672. Classify 10000 positive and negative tweets using Vader approach.
  673. :param n_instances: the number of total tweets that have to be classified.
  674. :param output: the output file where results have to be reported.
  675. """
  676. from collections import defaultdict
  677. from nltk.corpus import twitter_samples
  678. from nltk.sentiment import SentimentIntensityAnalyzer
  679. from nltk.metrics import (
  680. accuracy as eval_accuracy,
  681. precision as eval_precision,
  682. recall as eval_recall,
  683. f_measure as eval_f_measure,
  684. )
  685. if n_instances is not None:
  686. n_instances = int(n_instances / 2)
  687. fields = ["id", "text"]
  688. positive_json = twitter_samples.abspath("positive_tweets.json")
  689. positive_csv = "positive_tweets.csv"
  690. json2csv_preprocess(
  691. positive_json,
  692. positive_csv,
  693. fields,
  694. strip_off_emoticons=False,
  695. limit=n_instances,
  696. )
  697. negative_json = twitter_samples.abspath("negative_tweets.json")
  698. negative_csv = "negative_tweets.csv"
  699. json2csv_preprocess(
  700. negative_json,
  701. negative_csv,
  702. fields,
  703. strip_off_emoticons=False,
  704. limit=n_instances,
  705. )
  706. pos_docs = parse_tweets_set(positive_csv, label="pos")
  707. neg_docs = parse_tweets_set(negative_csv, label="neg")
  708. # We separately split subjective and objective instances to keep a balanced
  709. # uniform class distribution in both train and test sets.
  710. train_pos_docs, test_pos_docs = split_train_test(pos_docs)
  711. train_neg_docs, test_neg_docs = split_train_test(neg_docs)
  712. training_tweets = train_pos_docs + train_neg_docs
  713. testing_tweets = test_pos_docs + test_neg_docs
  714. vader_analyzer = SentimentIntensityAnalyzer()
  715. gold_results = defaultdict(set)
  716. test_results = defaultdict(set)
  717. acc_gold_results = []
  718. acc_test_results = []
  719. labels = set()
  720. num = 0
  721. for i, (text, label) in enumerate(testing_tweets):
  722. labels.add(label)
  723. gold_results[label].add(i)
  724. acc_gold_results.append(label)
  725. score = vader_analyzer.polarity_scores(text)["compound"]
  726. if score > 0:
  727. observed = "pos"
  728. else:
  729. observed = "neg"
  730. num += 1
  731. acc_test_results.append(observed)
  732. test_results[observed].add(i)
  733. metrics_results = {}
  734. for label in labels:
  735. accuracy_score = eval_accuracy(acc_gold_results, acc_test_results)
  736. metrics_results["Accuracy"] = accuracy_score
  737. precision_score = eval_precision(gold_results[label], test_results[label])
  738. metrics_results["Precision [{0}]".format(label)] = precision_score
  739. recall_score = eval_recall(gold_results[label], test_results[label])
  740. metrics_results["Recall [{0}]".format(label)] = recall_score
  741. f_measure_score = eval_f_measure(gold_results[label], test_results[label])
  742. metrics_results["F-measure [{0}]".format(label)] = f_measure_score
  743. for result in sorted(metrics_results):
  744. print("{0}: {1}".format(result, metrics_results[result]))
  745. if output:
  746. output_markdown(
  747. output,
  748. Approach="Vader",
  749. Dataset="labeled_tweets",
  750. Instances=n_instances,
  751. Results=metrics_results,
  752. )
  753. if __name__ == "__main__":
  754. from nltk.classify import NaiveBayesClassifier, MaxentClassifier
  755. from nltk.classify.scikitlearn import SklearnClassifier
  756. from sklearn.svm import LinearSVC
  757. from nltk.twitter.common import _outf_writer, extract_fields
  758. naive_bayes = NaiveBayesClassifier.train
  759. svm = SklearnClassifier(LinearSVC()).train
  760. maxent = MaxentClassifier.train
  761. demo_tweets(naive_bayes)
  762. # demo_movie_reviews(svm)
  763. # demo_subjectivity(svm)
  764. # demo_sent_subjectivity("she's an artist , but hasn't picked up a brush in a year . ")
  765. # demo_liu_hu_lexicon("This movie was actually neither that funny, nor super witty.", plot=True)
  766. # demo_vader_instance("This movie was actually neither that funny, nor super witty.")
  767. # demo_vader_tweets()