You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2520 lines
88 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Probability and Statistics
  3. #
  4. # Copyright (C) 2001-2019 NLTK Project
  5. # Author: Edward Loper <edloper@gmail.com>
  6. # Steven Bird <stevenbird1@gmail.com> (additions)
  7. # Trevor Cohn <tacohn@cs.mu.oz.au> (additions)
  8. # Peter Ljunglöf <peter.ljunglof@heatherleaf.se> (additions)
  9. # Liang Dong <ldong@clemson.edu> (additions)
  10. # Geoffrey Sampson <sampson@cantab.net> (additions)
  11. # Ilia Kurenkov <ilia.kurenkov@gmail.com> (additions)
  12. #
  13. # URL: <http://nltk.org/>
  14. # For license information, see LICENSE.TXT
  15. """
  16. Classes for representing and processing probabilistic information.
  17. The ``FreqDist`` class is used to encode "frequency distributions",
  18. which count the number of times that each outcome of an experiment
  19. occurs.
  20. The ``ProbDistI`` class defines a standard interface for "probability
  21. distributions", which encode the probability of each outcome for an
  22. experiment. There are two types of probability distribution:
  23. - "derived probability distributions" are created from frequency
  24. distributions. They attempt to model the probability distribution
  25. that generated the frequency distribution.
  26. - "analytic probability distributions" are created directly from
  27. parameters (such as variance).
  28. The ``ConditionalFreqDist`` class and ``ConditionalProbDistI`` interface
  29. are used to encode conditional distributions. Conditional probability
  30. distributions can be derived or analytic; but currently the only
  31. implementation of the ``ConditionalProbDistI`` interface is
  32. ``ConditionalProbDist``, a derived distribution.
  33. """
  34. from __future__ import print_function, unicode_literals, division
  35. import math
  36. import random
  37. import warnings
  38. import array
  39. from collections import defaultdict, Counter
  40. from functools import reduce
  41. from abc import ABCMeta, abstractmethod
  42. from six import itervalues, text_type, add_metaclass
  43. from nltk import compat
  44. from nltk.internals import raise_unorderable_types
  45. _NINF = float('-1e300')
  46. ##//////////////////////////////////////////////////////
  47. ## Frequency Distributions
  48. ##//////////////////////////////////////////////////////
  49. @compat.python_2_unicode_compatible
  50. class FreqDist(Counter):
  51. """
  52. A frequency distribution for the outcomes of an experiment. A
  53. frequency distribution records the number of times each outcome of
  54. an experiment has occurred. For example, a frequency distribution
  55. could be used to record the frequency of each word type in a
  56. document. Formally, a frequency distribution can be defined as a
  57. function mapping from each sample to the number of times that
  58. sample occurred as an outcome.
  59. Frequency distributions are generally constructed by running a
  60. number of experiments, and incrementing the count for a sample
  61. every time it is an outcome of an experiment. For example, the
  62. following code will produce a frequency distribution that encodes
  63. how often each word occurs in a text:
  64. >>> from nltk.tokenize import word_tokenize
  65. >>> from nltk.probability import FreqDist
  66. >>> sent = 'This is an example sentence'
  67. >>> fdist = FreqDist()
  68. >>> for word in word_tokenize(sent):
  69. ... fdist[word.lower()] += 1
  70. An equivalent way to do this is with the initializer:
  71. >>> fdist = FreqDist(word.lower() for word in word_tokenize(sent))
  72. """
  73. def __init__(self, samples=None):
  74. """
  75. Construct a new frequency distribution. If ``samples`` is
  76. given, then the frequency distribution will be initialized
  77. with the count of each object in ``samples``; otherwise, it
  78. will be initialized to be empty.
  79. In particular, ``FreqDist()`` returns an empty frequency
  80. distribution; and ``FreqDist(samples)`` first creates an empty
  81. frequency distribution, and then calls ``update`` with the
  82. list ``samples``.
  83. :param samples: The samples to initialize the frequency
  84. distribution with.
  85. :type samples: Sequence
  86. """
  87. Counter.__init__(self, samples)
  88. # Cached number of samples in this FreqDist
  89. self._N = None
  90. def N(self):
  91. """
  92. Return the total number of sample outcomes that have been
  93. recorded by this FreqDist. For the number of unique
  94. sample values (or bins) with counts greater than zero, use
  95. ``FreqDist.B()``.
  96. :rtype: int
  97. """
  98. if self._N is None:
  99. # Not already cached, or cache has been invalidated
  100. self._N = sum(self.values())
  101. return self._N
  102. def __setitem__(self, key, val):
  103. """
  104. Override ``Counter.__setitem__()`` to invalidate the cached N
  105. """
  106. self._N = None
  107. super(FreqDist, self).__setitem__(key, val)
  108. def __delitem__(self, key):
  109. """
  110. Override ``Counter.__delitem__()`` to invalidate the cached N
  111. """
  112. self._N = None
  113. super(FreqDist, self).__delitem__(key)
  114. def update(self, *args, **kwargs):
  115. """
  116. Override ``Counter.update()`` to invalidate the cached N
  117. """
  118. self._N = None
  119. super(FreqDist, self).update(*args, **kwargs)
  120. def setdefault(self, key, val):
  121. """
  122. Override ``Counter.setdefault()`` to invalidate the cached N
  123. """
  124. self._N = None
  125. super(FreqDist, self).setdefault(key, val)
  126. def B(self):
  127. """
  128. Return the total number of sample values (or "bins") that
  129. have counts greater than zero. For the total
  130. number of sample outcomes recorded, use ``FreqDist.N()``.
  131. (FreqDist.B() is the same as len(FreqDist).)
  132. :rtype: int
  133. """
  134. return len(self)
  135. def hapaxes(self):
  136. """
  137. Return a list of all samples that occur once (hapax legomena)
  138. :rtype: list
  139. """
  140. return [item for item in self if self[item] == 1]
  141. def Nr(self, r, bins=None):
  142. return self.r_Nr(bins)[r]
  143. def r_Nr(self, bins=None):
  144. """
  145. Return the dictionary mapping r to Nr, the number of samples with frequency r, where Nr > 0.
  146. :type bins: int
  147. :param bins: The number of possible sample outcomes. ``bins``
  148. is used to calculate Nr(0). In particular, Nr(0) is
  149. ``bins-self.B()``. If ``bins`` is not specified, it
  150. defaults to ``self.B()`` (so Nr(0) will be 0).
  151. :rtype: int
  152. """
  153. _r_Nr = defaultdict(int)
  154. for count in self.values():
  155. _r_Nr[count] += 1
  156. # Special case for Nr[0]:
  157. _r_Nr[0] = bins - self.B() if bins is not None else 0
  158. return _r_Nr
  159. def _cumulative_frequencies(self, samples):
  160. """
  161. Return the cumulative frequencies of the specified samples.
  162. If no samples are specified, all counts are returned, starting
  163. with the largest.
  164. :param samples: the samples whose frequencies should be returned.
  165. :type samples: any
  166. :rtype: list(float)
  167. """
  168. cf = 0.0
  169. for sample in samples:
  170. cf += self[sample]
  171. yield cf
  172. # slightly odd nomenclature freq() if FreqDist does counts and ProbDist does probs,
  173. # here, freq() does probs
  174. def freq(self, sample):
  175. """
  176. Return the frequency of a given sample. The frequency of a
  177. sample is defined as the count of that sample divided by the
  178. total number of sample outcomes that have been recorded by
  179. this FreqDist. The count of a sample is defined as the
  180. number of times that sample outcome was recorded by this
  181. FreqDist. Frequencies are always real numbers in the range
  182. [0, 1].
  183. :param sample: the sample whose frequency
  184. should be returned.
  185. :type sample: any
  186. :rtype: float
  187. """
  188. n = self.N()
  189. if n == 0:
  190. return 0
  191. return self[sample] / n
  192. def max(self):
  193. """
  194. Return the sample with the greatest number of outcomes in this
  195. frequency distribution. If two or more samples have the same
  196. number of outcomes, return one of them; which sample is
  197. returned is undefined. If no outcomes have occurred in this
  198. frequency distribution, return None.
  199. :return: The sample with the maximum number of outcomes in this
  200. frequency distribution.
  201. :rtype: any or None
  202. """
  203. if len(self) == 0:
  204. raise ValueError(
  205. 'A FreqDist must have at least one sample before max is defined.'
  206. )
  207. return self.most_common(1)[0][0]
  208. def plot(self, *args, **kwargs):
  209. """
  210. Plot samples from the frequency distribution
  211. displaying the most frequent sample first. If an integer
  212. parameter is supplied, stop after this many samples have been
  213. plotted. For a cumulative plot, specify cumulative=True.
  214. (Requires Matplotlib to be installed.)
  215. :param title: The title for the graph
  216. :type title: str
  217. :param cumulative: A flag to specify whether the plot is cumulative (default = False)
  218. :type title: bool
  219. """
  220. try:
  221. from matplotlib import pylab
  222. except ImportError:
  223. raise ValueError(
  224. 'The plot function requires matplotlib to be installed.'
  225. 'See http://matplotlib.org/'
  226. )
  227. if len(args) == 0:
  228. args = [len(self)]
  229. samples = [item for item, _ in self.most_common(*args)]
  230. cumulative = _get_kwarg(kwargs, 'cumulative', False)
  231. percents = _get_kwarg(kwargs, 'percents', False)
  232. if cumulative:
  233. freqs = list(self._cumulative_frequencies(samples))
  234. ylabel = "Cumulative Counts"
  235. if percents:
  236. freqs = [f / freqs[len(freqs) - 1] * 100 for f in freqs]
  237. ylabel = "Cumulative Percents"
  238. else:
  239. freqs = [self[sample] for sample in samples]
  240. ylabel = "Counts"
  241. # percents = [f * 100 for f in freqs] only in ProbDist?
  242. pylab.grid(True, color="silver")
  243. if "linewidth" not in kwargs:
  244. kwargs["linewidth"] = 2
  245. if "title" in kwargs:
  246. pylab.title(kwargs["title"])
  247. del kwargs["title"]
  248. pylab.plot(freqs, **kwargs)
  249. pylab.xticks(range(len(samples)), [text_type(s) for s in samples], rotation=90)
  250. pylab.xlabel("Samples")
  251. pylab.ylabel(ylabel)
  252. pylab.show()
  253. def tabulate(self, *args, **kwargs):
  254. """
  255. Tabulate the given samples from the frequency distribution (cumulative),
  256. displaying the most frequent sample first. If an integer
  257. parameter is supplied, stop after this many samples have been
  258. plotted.
  259. :param samples: The samples to plot (default is all samples)
  260. :type samples: list
  261. :param cumulative: A flag to specify whether the freqs are cumulative (default = False)
  262. :type title: bool
  263. """
  264. if len(args) == 0:
  265. args = [len(self)]
  266. samples = [item for item, _ in self.most_common(*args)]
  267. cumulative = _get_kwarg(kwargs, 'cumulative', False)
  268. if cumulative:
  269. freqs = list(self._cumulative_frequencies(samples))
  270. else:
  271. freqs = [self[sample] for sample in samples]
  272. # percents = [f * 100 for f in freqs] only in ProbDist?
  273. width = max(len("%s" % s) for s in samples)
  274. width = max(width, max(len("%d" % f) for f in freqs))
  275. for i in range(len(samples)):
  276. print("%*s" % (width, samples[i]), end=' ')
  277. print()
  278. for i in range(len(samples)):
  279. print("%*d" % (width, freqs[i]), end=' ')
  280. print()
  281. def copy(self):
  282. """
  283. Create a copy of this frequency distribution.
  284. :rtype: FreqDist
  285. """
  286. return self.__class__(self)
  287. # Mathematical operatiors
  288. def __add__(self, other):
  289. """
  290. Add counts from two counters.
  291. >>> FreqDist('abbb') + FreqDist('bcc')
  292. FreqDist({'b': 4, 'c': 2, 'a': 1})
  293. """
  294. return self.__class__(super(FreqDist, self).__add__(other))
  295. def __sub__(self, other):
  296. """
  297. Subtract count, but keep only results with positive counts.
  298. >>> FreqDist('abbbc') - FreqDist('bccd')
  299. FreqDist({'b': 2, 'a': 1})
  300. """
  301. return self.__class__(super(FreqDist, self).__sub__(other))
  302. def __or__(self, other):
  303. """
  304. Union is the maximum of value in either of the input counters.
  305. >>> FreqDist('abbb') | FreqDist('bcc')
  306. FreqDist({'b': 3, 'c': 2, 'a': 1})
  307. """
  308. return self.__class__(super(FreqDist, self).__or__(other))
  309. def __and__(self, other):
  310. """
  311. Intersection is the minimum of corresponding counts.
  312. >>> FreqDist('abbb') & FreqDist('bcc')
  313. FreqDist({'b': 1})
  314. """
  315. return self.__class__(super(FreqDist, self).__and__(other))
  316. def __le__(self, other):
  317. if not isinstance(other, FreqDist):
  318. raise_unorderable_types("<=", self, other)
  319. return set(self).issubset(other) and all(
  320. self[key] <= other[key] for key in self
  321. )
  322. # @total_ordering doesn't work here, since the class inherits from a builtin class
  323. __ge__ = lambda self, other: not self <= other or self == other
  324. __lt__ = lambda self, other: self <= other and not self == other
  325. __gt__ = lambda self, other: not self <= other
  326. def __repr__(self):
  327. """
  328. Return a string representation of this FreqDist.
  329. :rtype: string
  330. """
  331. return self.pformat()
  332. def pprint(self, maxlen=10, stream=None):
  333. """
  334. Print a string representation of this FreqDist to 'stream'
  335. :param maxlen: The maximum number of items to print
  336. :type maxlen: int
  337. :param stream: The stream to print to. stdout by default
  338. """
  339. print(self.pformat(maxlen=maxlen), file=stream)
  340. def pformat(self, maxlen=10):
  341. """
  342. Return a string representation of this FreqDist.
  343. :param maxlen: The maximum number of items to display
  344. :type maxlen: int
  345. :rtype: string
  346. """
  347. items = ['{0!r}: {1!r}'.format(*item) for item in self.most_common(maxlen)]
  348. if len(self) > maxlen:
  349. items.append('...')
  350. return 'FreqDist({{{0}}})'.format(', '.join(items))
  351. def __str__(self):
  352. """
  353. Return a string representation of this FreqDist.
  354. :rtype: string
  355. """
  356. return '<FreqDist with %d samples and %d outcomes>' % (len(self), self.N())
  357. ##//////////////////////////////////////////////////////
  358. ## Probability Distributions
  359. ##//////////////////////////////////////////////////////
  360. @add_metaclass(ABCMeta)
  361. class ProbDistI(object):
  362. """
  363. A probability distribution for the outcomes of an experiment. A
  364. probability distribution specifies how likely it is that an
  365. experiment will have any given outcome. For example, a
  366. probability distribution could be used to predict the probability
  367. that a token in a document will have a given type. Formally, a
  368. probability distribution can be defined as a function mapping from
  369. samples to nonnegative real numbers, such that the sum of every
  370. number in the function's range is 1.0. A ``ProbDist`` is often
  371. used to model the probability distribution of the experiment used
  372. to generate a frequency distribution.
  373. """
  374. SUM_TO_ONE = True
  375. """True if the probabilities of the samples in this probability
  376. distribution will always sum to one."""
  377. @abstractmethod
  378. def __init__(self):
  379. """
  380. Classes inheriting from ProbDistI should implement __init__.
  381. """
  382. @abstractmethod
  383. def prob(self, sample):
  384. """
  385. Return the probability for a given sample. Probabilities
  386. are always real numbers in the range [0, 1].
  387. :param sample: The sample whose probability
  388. should be returned.
  389. :type sample: any
  390. :rtype: float
  391. """
  392. def logprob(self, sample):
  393. """
  394. Return the base 2 logarithm of the probability for a given sample.
  395. :param sample: The sample whose probability
  396. should be returned.
  397. :type sample: any
  398. :rtype: float
  399. """
  400. # Default definition, in terms of prob()
  401. p = self.prob(sample)
  402. return math.log(p, 2) if p != 0 else _NINF
  403. @abstractmethod
  404. def max(self):
  405. """
  406. Return the sample with the greatest probability. If two or
  407. more samples have the same probability, return one of them;
  408. which sample is returned is undefined.
  409. :rtype: any
  410. """
  411. @abstractmethod
  412. def samples(self):
  413. """
  414. Return a list of all samples that have nonzero probabilities.
  415. Use ``prob`` to find the probability of each sample.
  416. :rtype: list
  417. """
  418. # cf self.SUM_TO_ONE
  419. def discount(self):
  420. """
  421. Return the ratio by which counts are discounted on average: c*/c
  422. :rtype: float
  423. """
  424. return 0.0
  425. # Subclasses should define more efficient implementations of this,
  426. # where possible.
  427. def generate(self):
  428. """
  429. Return a randomly selected sample from this probability distribution.
  430. The probability of returning each sample ``samp`` is equal to
  431. ``self.prob(samp)``.
  432. """
  433. p = random.random()
  434. p_init = p
  435. for sample in self.samples():
  436. p -= self.prob(sample)
  437. if p <= 0:
  438. return sample
  439. # allow for some rounding error:
  440. if p < 0.0001:
  441. return sample
  442. # we *should* never get here
  443. if self.SUM_TO_ONE:
  444. warnings.warn(
  445. "Probability distribution %r sums to %r; generate()"
  446. " is returning an arbitrary sample." % (self, p_init - p)
  447. )
  448. return random.choice(list(self.samples()))
  449. @compat.python_2_unicode_compatible
  450. class UniformProbDist(ProbDistI):
  451. """
  452. A probability distribution that assigns equal probability to each
  453. sample in a given set; and a zero probability to all other
  454. samples.
  455. """
  456. def __init__(self, samples):
  457. """
  458. Construct a new uniform probability distribution, that assigns
  459. equal probability to each sample in ``samples``.
  460. :param samples: The samples that should be given uniform
  461. probability.
  462. :type samples: list
  463. :raise ValueError: If ``samples`` is empty.
  464. """
  465. if len(samples) == 0:
  466. raise ValueError(
  467. 'A Uniform probability distribution must ' + 'have at least one sample.'
  468. )
  469. self._sampleset = set(samples)
  470. self._prob = 1.0 / len(self._sampleset)
  471. self._samples = list(self._sampleset)
  472. def prob(self, sample):
  473. return self._prob if sample in self._sampleset else 0
  474. def max(self):
  475. return self._samples[0]
  476. def samples(self):
  477. return self._samples
  478. def __repr__(self):
  479. return '<UniformProbDist with %d samples>' % len(self._sampleset)
  480. @compat.python_2_unicode_compatible
  481. class RandomProbDist(ProbDistI):
  482. """
  483. Generates a random probability distribution whereby each sample
  484. will be between 0 and 1 with equal probability (uniform random distribution.
  485. Also called a continuous uniform distribution).
  486. """
  487. def __init__(self, samples):
  488. if len(samples) == 0:
  489. raise ValueError(
  490. 'A probability distribution must ' + 'have at least one sample.'
  491. )
  492. self._probs = self.unirand(samples)
  493. self._samples = list(self._probs.keys())
  494. @classmethod
  495. def unirand(cls, samples):
  496. """
  497. The key function that creates a randomized initial distribution
  498. that still sums to 1. Set as a dictionary of prob values so that
  499. it can still be passed to MutableProbDist and called with identical
  500. syntax to UniformProbDist
  501. """
  502. samples = set(samples)
  503. randrow = [random.random() for i in range(len(samples))]
  504. total = sum(randrow)
  505. for i, x in enumerate(randrow):
  506. randrow[i] = x / total
  507. total = sum(randrow)
  508. if total != 1:
  509. # this difference, if present, is so small (near NINF) that it
  510. # can be subtracted from any element without risking probs not (0 1)
  511. randrow[-1] -= total - 1
  512. return dict((s, randrow[i]) for i, s in enumerate(samples))
  513. def max(self):
  514. if not hasattr(self, '_max'):
  515. self._max = max((p, v) for (v, p) in self._probs.items())[1]
  516. return self._max
  517. def prob(self, sample):
  518. return self._probs.get(sample, 0)
  519. def samples(self):
  520. return self._samples
  521. def __repr__(self):
  522. return '<RandomUniformProbDist with %d samples>' % len(self._probs)
  523. @compat.python_2_unicode_compatible
  524. class DictionaryProbDist(ProbDistI):
  525. """
  526. A probability distribution whose probabilities are directly
  527. specified by a given dictionary. The given dictionary maps
  528. samples to probabilities.
  529. """
  530. def __init__(self, prob_dict=None, log=False, normalize=False):
  531. """
  532. Construct a new probability distribution from the given
  533. dictionary, which maps values to probabilities (or to log
  534. probabilities, if ``log`` is true). If ``normalize`` is
  535. true, then the probability values are scaled by a constant
  536. factor such that they sum to 1.
  537. If called without arguments, the resulting probability
  538. distribution assigns zero probability to all values.
  539. """
  540. self._prob_dict = prob_dict.copy() if prob_dict is not None else {}
  541. self._log = log
  542. # Normalize the distribution, if requested.
  543. if normalize:
  544. if len(prob_dict) == 0:
  545. raise ValueError(
  546. 'A DictionaryProbDist must have at least one sample '
  547. + 'before it can be normalized.'
  548. )
  549. if log:
  550. value_sum = sum_logs(list(self._prob_dict.values()))
  551. if value_sum <= _NINF:
  552. logp = math.log(1.0 / len(prob_dict), 2)
  553. for x in prob_dict:
  554. self._prob_dict[x] = logp
  555. else:
  556. for (x, p) in self._prob_dict.items():
  557. self._prob_dict[x] -= value_sum
  558. else:
  559. value_sum = sum(self._prob_dict.values())
  560. if value_sum == 0:
  561. p = 1.0 / len(prob_dict)
  562. for x in prob_dict:
  563. self._prob_dict[x] = p
  564. else:
  565. norm_factor = 1.0 / value_sum
  566. for (x, p) in self._prob_dict.items():
  567. self._prob_dict[x] *= norm_factor
  568. def prob(self, sample):
  569. if self._log:
  570. return 2 ** (self._prob_dict[sample]) if sample in self._prob_dict else 0
  571. else:
  572. return self._prob_dict.get(sample, 0)
  573. def logprob(self, sample):
  574. if self._log:
  575. return self._prob_dict.get(sample, _NINF)
  576. else:
  577. if sample not in self._prob_dict:
  578. return _NINF
  579. elif self._prob_dict[sample] == 0:
  580. return _NINF
  581. else:
  582. return math.log(self._prob_dict[sample], 2)
  583. def max(self):
  584. if not hasattr(self, '_max'):
  585. self._max = max((p, v) for (v, p) in self._prob_dict.items())[1]
  586. return self._max
  587. def samples(self):
  588. return self._prob_dict.keys()
  589. def __repr__(self):
  590. return '<ProbDist with %d samples>' % len(self._prob_dict)
  591. @compat.python_2_unicode_compatible
  592. class MLEProbDist(ProbDistI):
  593. """
  594. The maximum likelihood estimate for the probability distribution
  595. of the experiment used to generate a frequency distribution. The
  596. "maximum likelihood estimate" approximates the probability of
  597. each sample as the frequency of that sample in the frequency
  598. distribution.
  599. """
  600. def __init__(self, freqdist, bins=None):
  601. """
  602. Use the maximum likelihood estimate to create a probability
  603. distribution for the experiment used to generate ``freqdist``.
  604. :type freqdist: FreqDist
  605. :param freqdist: The frequency distribution that the
  606. probability estimates should be based on.
  607. """
  608. self._freqdist = freqdist
  609. def freqdist(self):
  610. """
  611. Return the frequency distribution that this probability
  612. distribution is based on.
  613. :rtype: FreqDist
  614. """
  615. return self._freqdist
  616. def prob(self, sample):
  617. return self._freqdist.freq(sample)
  618. def max(self):
  619. return self._freqdist.max()
  620. def samples(self):
  621. return self._freqdist.keys()
  622. def __repr__(self):
  623. """
  624. :rtype: str
  625. :return: A string representation of this ``ProbDist``.
  626. """
  627. return '<MLEProbDist based on %d samples>' % self._freqdist.N()
  628. @compat.python_2_unicode_compatible
  629. class LidstoneProbDist(ProbDistI):
  630. """
  631. The Lidstone estimate for the probability distribution of the
  632. experiment used to generate a frequency distribution. The
  633. "Lidstone estimate" is parameterized by a real number *gamma*,
  634. which typically ranges from 0 to 1. The Lidstone estimate
  635. approximates the probability of a sample with count *c* from an
  636. experiment with *N* outcomes and *B* bins as
  637. ``c+gamma)/(N+B*gamma)``. This is equivalent to adding
  638. *gamma* to the count for each bin, and taking the maximum
  639. likelihood estimate of the resulting frequency distribution.
  640. """
  641. SUM_TO_ONE = False
  642. def __init__(self, freqdist, gamma, bins=None):
  643. """
  644. Use the Lidstone estimate to create a probability distribution
  645. for the experiment used to generate ``freqdist``.
  646. :type freqdist: FreqDist
  647. :param freqdist: The frequency distribution that the
  648. probability estimates should be based on.
  649. :type gamma: float
  650. :param gamma: A real number used to parameterize the
  651. estimate. The Lidstone estimate is equivalent to adding
  652. *gamma* to the count for each bin, and taking the
  653. maximum likelihood estimate of the resulting frequency
  654. distribution.
  655. :type bins: int
  656. :param bins: The number of sample values that can be generated
  657. by the experiment that is described by the probability
  658. distribution. This value must be correctly set for the
  659. probabilities of the sample values to sum to one. If
  660. ``bins`` is not specified, it defaults to ``freqdist.B()``.
  661. """
  662. if (bins == 0) or (bins is None and freqdist.N() == 0):
  663. name = self.__class__.__name__[:-8]
  664. raise ValueError(
  665. 'A %s probability distribution ' % name + 'must have at least one bin.'
  666. )
  667. if (bins is not None) and (bins < freqdist.B()):
  668. name = self.__class__.__name__[:-8]
  669. raise ValueError(
  670. '\nThe number of bins in a %s distribution ' % name
  671. + '(%d) must be greater than or equal to\n' % bins
  672. + 'the number of bins in the FreqDist used '
  673. + 'to create it (%d).' % freqdist.B()
  674. )
  675. self._freqdist = freqdist
  676. self._gamma = float(gamma)
  677. self._N = self._freqdist.N()
  678. if bins is None:
  679. bins = freqdist.B()
  680. self._bins = bins
  681. self._divisor = self._N + bins * gamma
  682. if self._divisor == 0.0:
  683. # In extreme cases we force the probability to be 0,
  684. # which it will be, since the count will be 0:
  685. self._gamma = 0
  686. self._divisor = 1
  687. def freqdist(self):
  688. """
  689. Return the frequency distribution that this probability
  690. distribution is based on.
  691. :rtype: FreqDist
  692. """
  693. return self._freqdist
  694. def prob(self, sample):
  695. c = self._freqdist[sample]
  696. return (c + self._gamma) / self._divisor
  697. def max(self):
  698. # For Lidstone distributions, probability is monotonic with
  699. # frequency, so the most probable sample is the one that
  700. # occurs most frequently.
  701. return self._freqdist.max()
  702. def samples(self):
  703. return self._freqdist.keys()
  704. def discount(self):
  705. gb = self._gamma * self._bins
  706. return gb / (self._N + gb)
  707. def __repr__(self):
  708. """
  709. Return a string representation of this ``ProbDist``.
  710. :rtype: str
  711. """
  712. return '<LidstoneProbDist based on %d samples>' % self._freqdist.N()
  713. @compat.python_2_unicode_compatible
  714. class LaplaceProbDist(LidstoneProbDist):
  715. """
  716. The Laplace estimate for the probability distribution of the
  717. experiment used to generate a frequency distribution. The
  718. "Laplace estimate" approximates the probability of a sample with
  719. count *c* from an experiment with *N* outcomes and *B* bins as
  720. *(c+1)/(N+B)*. This is equivalent to adding one to the count for
  721. each bin, and taking the maximum likelihood estimate of the
  722. resulting frequency distribution.
  723. """
  724. def __init__(self, freqdist, bins=None):
  725. """
  726. Use the Laplace estimate to create a probability distribution
  727. for the experiment used to generate ``freqdist``.
  728. :type freqdist: FreqDist
  729. :param freqdist: The frequency distribution that the
  730. probability estimates should be based on.
  731. :type bins: int
  732. :param bins: The number of sample values that can be generated
  733. by the experiment that is described by the probability
  734. distribution. This value must be correctly set for the
  735. probabilities of the sample values to sum to one. If
  736. ``bins`` is not specified, it defaults to ``freqdist.B()``.
  737. """
  738. LidstoneProbDist.__init__(self, freqdist, 1, bins)
  739. def __repr__(self):
  740. """
  741. :rtype: str
  742. :return: A string representation of this ``ProbDist``.
  743. """
  744. return '<LaplaceProbDist based on %d samples>' % self._freqdist.N()
  745. @compat.python_2_unicode_compatible
  746. class ELEProbDist(LidstoneProbDist):
  747. """
  748. The expected likelihood estimate for the probability distribution
  749. of the experiment used to generate a frequency distribution. The
  750. "expected likelihood estimate" approximates the probability of a
  751. sample with count *c* from an experiment with *N* outcomes and
  752. *B* bins as *(c+0.5)/(N+B/2)*. This is equivalent to adding 0.5
  753. to the count for each bin, and taking the maximum likelihood
  754. estimate of the resulting frequency distribution.
  755. """
  756. def __init__(self, freqdist, bins=None):
  757. """
  758. Use the expected likelihood estimate to create a probability
  759. distribution for the experiment used to generate ``freqdist``.
  760. :type freqdist: FreqDist
  761. :param freqdist: The frequency distribution that the
  762. probability estimates should be based on.
  763. :type bins: int
  764. :param bins: The number of sample values that can be generated
  765. by the experiment that is described by the probability
  766. distribution. This value must be correctly set for the
  767. probabilities of the sample values to sum to one. If
  768. ``bins`` is not specified, it defaults to ``freqdist.B()``.
  769. """
  770. LidstoneProbDist.__init__(self, freqdist, 0.5, bins)
  771. def __repr__(self):
  772. """
  773. Return a string representation of this ``ProbDist``.
  774. :rtype: str
  775. """
  776. return '<ELEProbDist based on %d samples>' % self._freqdist.N()
  777. @compat.python_2_unicode_compatible
  778. class HeldoutProbDist(ProbDistI):
  779. """
  780. The heldout estimate for the probability distribution of the
  781. experiment used to generate two frequency distributions. These
  782. two frequency distributions are called the "heldout frequency
  783. distribution" and the "base frequency distribution." The
  784. "heldout estimate" uses uses the "heldout frequency
  785. distribution" to predict the probability of each sample, given its
  786. frequency in the "base frequency distribution".
  787. In particular, the heldout estimate approximates the probability
  788. for a sample that occurs *r* times in the base distribution as
  789. the average frequency in the heldout distribution of all samples
  790. that occur *r* times in the base distribution.
  791. This average frequency is *Tr[r]/(Nr[r].N)*, where:
  792. - *Tr[r]* is the total count in the heldout distribution for
  793. all samples that occur *r* times in the base distribution.
  794. - *Nr[r]* is the number of samples that occur *r* times in
  795. the base distribution.
  796. - *N* is the number of outcomes recorded by the heldout
  797. frequency distribution.
  798. In order to increase the efficiency of the ``prob`` member
  799. function, *Tr[r]/(Nr[r].N)* is precomputed for each value of *r*
  800. when the ``HeldoutProbDist`` is created.
  801. :type _estimate: list(float)
  802. :ivar _estimate: A list mapping from *r*, the number of
  803. times that a sample occurs in the base distribution, to the
  804. probability estimate for that sample. ``_estimate[r]`` is
  805. calculated by finding the average frequency in the heldout
  806. distribution of all samples that occur *r* times in the base
  807. distribution. In particular, ``_estimate[r]`` =
  808. *Tr[r]/(Nr[r].N)*.
  809. :type _max_r: int
  810. :ivar _max_r: The maximum number of times that any sample occurs
  811. in the base distribution. ``_max_r`` is used to decide how
  812. large ``_estimate`` must be.
  813. """
  814. SUM_TO_ONE = False
  815. def __init__(self, base_fdist, heldout_fdist, bins=None):
  816. """
  817. Use the heldout estimate to create a probability distribution
  818. for the experiment used to generate ``base_fdist`` and
  819. ``heldout_fdist``.
  820. :type base_fdist: FreqDist
  821. :param base_fdist: The base frequency distribution.
  822. :type heldout_fdist: FreqDist
  823. :param heldout_fdist: The heldout frequency distribution.
  824. :type bins: int
  825. :param bins: The number of sample values that can be generated
  826. by the experiment that is described by the probability
  827. distribution. This value must be correctly set for the
  828. probabilities of the sample values to sum to one. If
  829. ``bins`` is not specified, it defaults to ``freqdist.B()``.
  830. """
  831. self._base_fdist = base_fdist
  832. self._heldout_fdist = heldout_fdist
  833. # The max number of times any sample occurs in base_fdist.
  834. self._max_r = base_fdist[base_fdist.max()]
  835. # Calculate Tr, Nr, and N.
  836. Tr = self._calculate_Tr()
  837. r_Nr = base_fdist.r_Nr(bins)
  838. Nr = [r_Nr[r] for r in range(self._max_r + 1)]
  839. N = heldout_fdist.N()
  840. # Use Tr, Nr, and N to compute the probability estimate for
  841. # each value of r.
  842. self._estimate = self._calculate_estimate(Tr, Nr, N)
  843. def _calculate_Tr(self):
  844. """
  845. Return the list *Tr*, where *Tr[r]* is the total count in
  846. ``heldout_fdist`` for all samples that occur *r*
  847. times in ``base_fdist``.
  848. :rtype: list(float)
  849. """
  850. Tr = [0.0] * (self._max_r + 1)
  851. for sample in self._heldout_fdist:
  852. r = self._base_fdist[sample]
  853. Tr[r] += self._heldout_fdist[sample]
  854. return Tr
  855. def _calculate_estimate(self, Tr, Nr, N):
  856. """
  857. Return the list *estimate*, where *estimate[r]* is the probability
  858. estimate for any sample that occurs *r* times in the base frequency
  859. distribution. In particular, *estimate[r]* is *Tr[r]/(N[r].N)*.
  860. In the special case that *N[r]=0*, *estimate[r]* will never be used;
  861. so we define *estimate[r]=None* for those cases.
  862. :rtype: list(float)
  863. :type Tr: list(float)
  864. :param Tr: the list *Tr*, where *Tr[r]* is the total count in
  865. the heldout distribution for all samples that occur *r*
  866. times in base distribution.
  867. :type Nr: list(float)
  868. :param Nr: The list *Nr*, where *Nr[r]* is the number of
  869. samples that occur *r* times in the base distribution.
  870. :type N: int
  871. :param N: The total number of outcomes recorded by the heldout
  872. frequency distribution.
  873. """
  874. estimate = []
  875. for r in range(self._max_r + 1):
  876. if Nr[r] == 0:
  877. estimate.append(None)
  878. else:
  879. estimate.append(Tr[r] / (Nr[r] * N))
  880. return estimate
  881. def base_fdist(self):
  882. """
  883. Return the base frequency distribution that this probability
  884. distribution is based on.
  885. :rtype: FreqDist
  886. """
  887. return self._base_fdist
  888. def heldout_fdist(self):
  889. """
  890. Return the heldout frequency distribution that this
  891. probability distribution is based on.
  892. :rtype: FreqDist
  893. """
  894. return self._heldout_fdist
  895. def samples(self):
  896. return self._base_fdist.keys()
  897. def prob(self, sample):
  898. # Use our precomputed probability estimate.
  899. r = self._base_fdist[sample]
  900. return self._estimate[r]
  901. def max(self):
  902. # Note: the Heldout estimation is *not* necessarily monotonic;
  903. # so this implementation is currently broken. However, it
  904. # should give the right answer *most* of the time. :)
  905. return self._base_fdist.max()
  906. def discount(self):
  907. raise NotImplementedError()
  908. def __repr__(self):
  909. """
  910. :rtype: str
  911. :return: A string representation of this ``ProbDist``.
  912. """
  913. s = '<HeldoutProbDist: %d base samples; %d heldout samples>'
  914. return s % (self._base_fdist.N(), self._heldout_fdist.N())
  915. @compat.python_2_unicode_compatible
  916. class CrossValidationProbDist(ProbDistI):
  917. """
  918. The cross-validation estimate for the probability distribution of
  919. the experiment used to generate a set of frequency distribution.
  920. The "cross-validation estimate" for the probability of a sample
  921. is found by averaging the held-out estimates for the sample in
  922. each pair of frequency distributions.
  923. """
  924. SUM_TO_ONE = False
  925. def __init__(self, freqdists, bins):
  926. """
  927. Use the cross-validation estimate to create a probability
  928. distribution for the experiment used to generate
  929. ``freqdists``.
  930. :type freqdists: list(FreqDist)
  931. :param freqdists: A list of the frequency distributions
  932. generated by the experiment.
  933. :type bins: int
  934. :param bins: The number of sample values that can be generated
  935. by the experiment that is described by the probability
  936. distribution. This value must be correctly set for the
  937. probabilities of the sample values to sum to one. If
  938. ``bins`` is not specified, it defaults to ``freqdist.B()``.
  939. """
  940. self._freqdists = freqdists
  941. # Create a heldout probability distribution for each pair of
  942. # frequency distributions in freqdists.
  943. self._heldout_probdists = []
  944. for fdist1 in freqdists:
  945. for fdist2 in freqdists:
  946. if fdist1 is not fdist2:
  947. probdist = HeldoutProbDist(fdist1, fdist2, bins)
  948. self._heldout_probdists.append(probdist)
  949. def freqdists(self):
  950. """
  951. Return the list of frequency distributions that this ``ProbDist`` is based on.
  952. :rtype: list(FreqDist)
  953. """
  954. return self._freqdists
  955. def samples(self):
  956. # [xx] nb: this is not too efficient
  957. return set(sum([list(fd) for fd in self._freqdists], []))
  958. def prob(self, sample):
  959. # Find the average probability estimate returned by each
  960. # heldout distribution.
  961. prob = 0.0
  962. for heldout_probdist in self._heldout_probdists:
  963. prob += heldout_probdist.prob(sample)
  964. return prob / len(self._heldout_probdists)
  965. def discount(self):
  966. raise NotImplementedError()
  967. def __repr__(self):
  968. """
  969. Return a string representation of this ``ProbDist``.
  970. :rtype: str
  971. """
  972. return '<CrossValidationProbDist: %d-way>' % len(self._freqdists)
  973. @compat.python_2_unicode_compatible
  974. class WittenBellProbDist(ProbDistI):
  975. """
  976. The Witten-Bell estimate of a probability distribution. This distribution
  977. allocates uniform probability mass to as yet unseen events by using the
  978. number of events that have only been seen once. The probability mass
  979. reserved for unseen events is equal to *T / (N + T)*
  980. where *T* is the number of observed event types and *N* is the total
  981. number of observed events. This equates to the maximum likelihood estimate
  982. of a new type event occurring. The remaining probability mass is discounted
  983. such that all probability estimates sum to one, yielding:
  984. - *p = T / Z (N + T)*, if count = 0
  985. - *p = c / (N + T)*, otherwise
  986. """
  987. def __init__(self, freqdist, bins=None):
  988. """
  989. Creates a distribution of Witten-Bell probability estimates. This
  990. distribution allocates uniform probability mass to as yet unseen
  991. events by using the number of events that have only been seen once. The
  992. probability mass reserved for unseen events is equal to *T / (N + T)*
  993. where *T* is the number of observed event types and *N* is the total
  994. number of observed events. This equates to the maximum likelihood
  995. estimate of a new type event occurring. The remaining probability mass
  996. is discounted such that all probability estimates sum to one,
  997. yielding:
  998. - *p = T / Z (N + T)*, if count = 0
  999. - *p = c / (N + T)*, otherwise
  1000. The parameters *T* and *N* are taken from the ``freqdist`` parameter
  1001. (the ``B()`` and ``N()`` values). The normalizing factor *Z* is
  1002. calculated using these values along with the ``bins`` parameter.
  1003. :param freqdist: The frequency counts upon which to base the
  1004. estimation.
  1005. :type freqdist: FreqDist
  1006. :param bins: The number of possible event types. This must be at least
  1007. as large as the number of bins in the ``freqdist``. If None, then
  1008. it's assumed to be equal to that of the ``freqdist``
  1009. :type bins: int
  1010. """
  1011. assert bins is None or bins >= freqdist.B(), (
  1012. 'bins parameter must not be less than %d=freqdist.B()' % freqdist.B()
  1013. )
  1014. if bins is None:
  1015. bins = freqdist.B()
  1016. self._freqdist = freqdist
  1017. self._T = self._freqdist.B()
  1018. self._Z = bins - self._freqdist.B()
  1019. self._N = self._freqdist.N()
  1020. # self._P0 is P(0), precalculated for efficiency:
  1021. if self._N == 0:
  1022. # if freqdist is empty, we approximate P(0) by a UniformProbDist:
  1023. self._P0 = 1.0 / self._Z
  1024. else:
  1025. self._P0 = self._T / (self._Z * (self._N + self._T))
  1026. def prob(self, sample):
  1027. # inherit docs from ProbDistI
  1028. c = self._freqdist[sample]
  1029. return c / (self._N + self._T) if c != 0 else self._P0
  1030. def max(self):
  1031. return self._freqdist.max()
  1032. def samples(self):
  1033. return self._freqdist.keys()
  1034. def freqdist(self):
  1035. return self._freqdist
  1036. def discount(self):
  1037. raise NotImplementedError()
  1038. def __repr__(self):
  1039. """
  1040. Return a string representation of this ``ProbDist``.
  1041. :rtype: str
  1042. """
  1043. return '<WittenBellProbDist based on %d samples>' % self._freqdist.N()
  1044. ##//////////////////////////////////////////////////////
  1045. ## Good-Turing Probability Distributions
  1046. ##//////////////////////////////////////////////////////
  1047. # Good-Turing frequency estimation was contributed by Alan Turing and
  1048. # his statistical assistant I.J. Good, during their collaboration in
  1049. # the WWII. It is a statistical technique for predicting the
  1050. # probability of occurrence of objects belonging to an unknown number
  1051. # of species, given past observations of such objects and their
  1052. # species. (In drawing balls from an urn, the 'objects' would be balls
  1053. # and the 'species' would be the distinct colors of the balls (finite
  1054. # but unknown in number).
  1055. #
  1056. # Good-Turing method calculates the probability mass to assign to
  1057. # events with zero or low counts based on the number of events with
  1058. # higher counts. It does so by using the adjusted count *c\**:
  1059. #
  1060. # - *c\* = (c + 1) N(c + 1) / N(c)* for c >= 1
  1061. # - *things with frequency zero in training* = N(1) for c == 0
  1062. #
  1063. # where *c* is the original count, *N(i)* is the number of event types
  1064. # observed with count *i*. We can think the count of unseen as the count
  1065. # of frequency one (see Jurafsky & Martin 2nd Edition, p101).
  1066. #
  1067. # This method is problematic because the situation ``N(c+1) == 0``
  1068. # is quite common in the original Good-Turing estimation; smoothing or
  1069. # interpolation of *N(i)* values is essential in practice.
  1070. #
  1071. # Bill Gale and Geoffrey Sampson present a simple and effective approach,
  1072. # Simple Good-Turing. As a smoothing curve they simply use a power curve:
  1073. #
  1074. # Nr = a*r^b (with b < -1 to give the appropriate hyperbolic
  1075. # relationship)
  1076. #
  1077. # They estimate a and b by simple linear regression technique on the
  1078. # logarithmic form of the equation:
  1079. #
  1080. # log Nr = a + b*log(r)
  1081. #
  1082. # However, they suggest that such a simple curve is probably only
  1083. # appropriate for high values of r. For low values of r, they use the
  1084. # measured Nr directly. (see M&S, p.213)
  1085. #
  1086. # Gale and Sampson propose to use r while the difference between r and
  1087. # r* is 1.96 greater than the standard deviation, and switch to r* if
  1088. # it is less or equal:
  1089. #
  1090. # |r - r*| > 1.96 * sqrt((r + 1)^2 (Nr+1 / Nr^2) (1 + Nr+1 / Nr))
  1091. #
  1092. # The 1.96 coefficient correspond to a 0.05 significance criterion,
  1093. # some implementations can use a coefficient of 1.65 for a 0.1
  1094. # significance criterion.
  1095. #
  1096. ##//////////////////////////////////////////////////////
  1097. ## Simple Good-Turing Probablity Distributions
  1098. ##//////////////////////////////////////////////////////
  1099. @compat.python_2_unicode_compatible
  1100. class SimpleGoodTuringProbDist(ProbDistI):
  1101. """
  1102. SimpleGoodTuring ProbDist approximates from frequency to frequency of
  1103. frequency into a linear line under log space by linear regression.
  1104. Details of Simple Good-Turing algorithm can be found in:
  1105. - Good Turing smoothing without tears" (Gale & Sampson 1995),
  1106. Journal of Quantitative Linguistics, vol. 2 pp. 217-237.
  1107. - "Speech and Language Processing (Jurafsky & Martin),
  1108. 2nd Edition, Chapter 4.5 p103 (log(Nc) = a + b*log(c))
  1109. - http://www.grsampson.net/RGoodTur.html
  1110. Given a set of pair (xi, yi), where the xi denotes the frequency and
  1111. yi denotes the frequency of frequency, we want to minimize their
  1112. square variation. E(x) and E(y) represent the mean of xi and yi.
  1113. - slope: b = sigma ((xi-E(x)(yi-E(y))) / sigma ((xi-E(x))(xi-E(x)))
  1114. - intercept: a = E(y) - b.E(x)
  1115. """
  1116. SUM_TO_ONE = False
  1117. def __init__(self, freqdist, bins=None):
  1118. """
  1119. :param freqdist: The frequency counts upon which to base the
  1120. estimation.
  1121. :type freqdist: FreqDist
  1122. :param bins: The number of possible event types. This must be
  1123. larger than the number of bins in the ``freqdist``. If None,
  1124. then it's assumed to be equal to ``freqdist``.B() + 1
  1125. :type bins: int
  1126. """
  1127. assert (
  1128. bins is None or bins > freqdist.B()
  1129. ), 'bins parameter must not be less than %d=freqdist.B()+1' % (freqdist.B() + 1)
  1130. if bins is None:
  1131. bins = freqdist.B() + 1
  1132. self._freqdist = freqdist
  1133. self._bins = bins
  1134. r, nr = self._r_Nr()
  1135. self.find_best_fit(r, nr)
  1136. self._switch(r, nr)
  1137. self._renormalize(r, nr)
  1138. def _r_Nr_non_zero(self):
  1139. r_Nr = self._freqdist.r_Nr()
  1140. del r_Nr[0]
  1141. return r_Nr
  1142. def _r_Nr(self):
  1143. """
  1144. Split the frequency distribution in two list (r, Nr), where Nr(r) > 0
  1145. """
  1146. nonzero = self._r_Nr_non_zero()
  1147. if not nonzero:
  1148. return [], []
  1149. return zip(*sorted(nonzero.items()))
  1150. def find_best_fit(self, r, nr):
  1151. """
  1152. Use simple linear regression to tune parameters self._slope and
  1153. self._intercept in the log-log space based on count and Nr(count)
  1154. (Work in log space to avoid floating point underflow.)
  1155. """
  1156. # For higher sample frequencies the data points becomes horizontal
  1157. # along line Nr=1. To create a more evident linear model in log-log
  1158. # space, we average positive Nr values with the surrounding zero
  1159. # values. (Church and Gale, 1991)
  1160. if not r or not nr:
  1161. # Empty r or nr?
  1162. return
  1163. zr = []
  1164. for j in range(len(r)):
  1165. i = r[j - 1] if j > 0 else 0
  1166. k = 2 * r[j] - i if j == len(r) - 1 else r[j + 1]
  1167. zr_ = 2.0 * nr[j] / (k - i)
  1168. zr.append(zr_)
  1169. log_r = [math.log(i) for i in r]
  1170. log_zr = [math.log(i) for i in zr]
  1171. xy_cov = x_var = 0.0
  1172. x_mean = sum(log_r) / len(log_r)
  1173. y_mean = sum(log_zr) / len(log_zr)
  1174. for (x, y) in zip(log_r, log_zr):
  1175. xy_cov += (x - x_mean) * (y - y_mean)
  1176. x_var += (x - x_mean) ** 2
  1177. self._slope = xy_cov / x_var if x_var != 0 else 0.0
  1178. if self._slope >= -1:
  1179. warnings.warn(
  1180. 'SimpleGoodTuring did not find a proper best fit '
  1181. 'line for smoothing probabilities of occurrences. '
  1182. 'The probability estimates are likely to be '
  1183. 'unreliable.'
  1184. )
  1185. self._intercept = y_mean - self._slope * x_mean
  1186. def _switch(self, r, nr):
  1187. """
  1188. Calculate the r frontier where we must switch from Nr to Sr
  1189. when estimating E[Nr].
  1190. """
  1191. for i, r_ in enumerate(r):
  1192. if len(r) == i + 1 or r[i + 1] != r_ + 1:
  1193. # We are at the end of r, or there is a gap in r
  1194. self._switch_at = r_
  1195. break
  1196. Sr = self.smoothedNr
  1197. smooth_r_star = (r_ + 1) * Sr(r_ + 1) / Sr(r_)
  1198. unsmooth_r_star = (r_ + 1) * nr[i + 1] / nr[i]
  1199. std = math.sqrt(self._variance(r_, nr[i], nr[i + 1]))
  1200. if abs(unsmooth_r_star - smooth_r_star) <= 1.96 * std:
  1201. self._switch_at = r_
  1202. break
  1203. def _variance(self, r, nr, nr_1):
  1204. r = float(r)
  1205. nr = float(nr)
  1206. nr_1 = float(nr_1)
  1207. return (r + 1.0) ** 2 * (nr_1 / nr ** 2) * (1.0 + nr_1 / nr)
  1208. def _renormalize(self, r, nr):
  1209. """
  1210. It is necessary to renormalize all the probability estimates to
  1211. ensure a proper probability distribution results. This can be done
  1212. by keeping the estimate of the probability mass for unseen items as
  1213. N(1)/N and renormalizing all the estimates for previously seen items
  1214. (as Gale and Sampson (1995) propose). (See M&S P.213, 1999)
  1215. """
  1216. prob_cov = 0.0
  1217. for r_, nr_ in zip(r, nr):
  1218. prob_cov += nr_ * self._prob_measure(r_)
  1219. if prob_cov:
  1220. self._renormal = (1 - self._prob_measure(0)) / prob_cov
  1221. def smoothedNr(self, r):
  1222. """
  1223. Return the number of samples with count r.
  1224. :param r: The amount of frequency.
  1225. :type r: int
  1226. :rtype: float
  1227. """
  1228. # Nr = a*r^b (with b < -1 to give the appropriate hyperbolic
  1229. # relationship)
  1230. # Estimate a and b by simple linear regression technique on
  1231. # the logarithmic form of the equation: log Nr = a + b*log(r)
  1232. return math.exp(self._intercept + self._slope * math.log(r))
  1233. def prob(self, sample):
  1234. """
  1235. Return the sample's probability.
  1236. :param sample: sample of the event
  1237. :type sample: str
  1238. :rtype: float
  1239. """
  1240. count = self._freqdist[sample]
  1241. p = self._prob_measure(count)
  1242. if count == 0:
  1243. if self._bins == self._freqdist.B():
  1244. p = 0.0
  1245. else:
  1246. p = p / (self._bins - self._freqdist.B())
  1247. else:
  1248. p = p * self._renormal
  1249. return p
  1250. def _prob_measure(self, count):
  1251. if count == 0 and self._freqdist.N() == 0:
  1252. return 1.0
  1253. elif count == 0 and self._freqdist.N() != 0:
  1254. return self._freqdist.Nr(1) / self._freqdist.N()
  1255. if self._switch_at > count:
  1256. Er_1 = self._freqdist.Nr(count + 1)
  1257. Er = self._freqdist.Nr(count)
  1258. else:
  1259. Er_1 = self.smoothedNr(count + 1)
  1260. Er = self.smoothedNr(count)
  1261. r_star = (count + 1) * Er_1 / Er
  1262. return r_star / self._freqdist.N()
  1263. def check(self):
  1264. prob_sum = 0.0
  1265. for i in range(0, len(self._Nr)):
  1266. prob_sum += self._Nr[i] * self._prob_measure(i) / self._renormal
  1267. print("Probability Sum:", prob_sum)
  1268. # assert prob_sum != 1.0, "probability sum should be one!"
  1269. def discount(self):
  1270. """
  1271. This function returns the total mass of probability transfers from the
  1272. seen samples to the unseen samples.
  1273. """
  1274. return self.smoothedNr(1) / self._freqdist.N()
  1275. def max(self):
  1276. return self._freqdist.max()
  1277. def samples(self):
  1278. return self._freqdist.keys()
  1279. def freqdist(self):
  1280. return self._freqdist
  1281. def __repr__(self):
  1282. """
  1283. Return a string representation of this ``ProbDist``.
  1284. :rtype: str
  1285. """
  1286. return '<SimpleGoodTuringProbDist based on %d samples>' % self._freqdist.N()
  1287. class MutableProbDist(ProbDistI):
  1288. """
  1289. An mutable probdist where the probabilities may be easily modified. This
  1290. simply copies an existing probdist, storing the probability values in a
  1291. mutable dictionary and providing an update method.
  1292. """
  1293. def __init__(self, prob_dist, samples, store_logs=True):
  1294. """
  1295. Creates the mutable probdist based on the given prob_dist and using
  1296. the list of samples given. These values are stored as log
  1297. probabilities if the store_logs flag is set.
  1298. :param prob_dist: the distribution from which to garner the
  1299. probabilities
  1300. :type prob_dist: ProbDist
  1301. :param samples: the complete set of samples
  1302. :type samples: sequence of any
  1303. :param store_logs: whether to store the probabilities as logarithms
  1304. :type store_logs: bool
  1305. """
  1306. self._samples = samples
  1307. self._sample_dict = dict((samples[i], i) for i in range(len(samples)))
  1308. self._data = array.array(str("d"), [0.0]) * len(samples)
  1309. for i in range(len(samples)):
  1310. if store_logs:
  1311. self._data[i] = prob_dist.logprob(samples[i])
  1312. else:
  1313. self._data[i] = prob_dist.prob(samples[i])
  1314. self._logs = store_logs
  1315. def max(self):
  1316. # inherit documentation
  1317. return max((p, v) for (v, p) in self._sample_dict.items())[1]
  1318. def samples(self):
  1319. # inherit documentation
  1320. return self._samples
  1321. def prob(self, sample):
  1322. # inherit documentation
  1323. i = self._sample_dict.get(sample)
  1324. if i is None:
  1325. return 0.0
  1326. return 2 ** (self._data[i]) if self._logs else self._data[i]
  1327. def logprob(self, sample):
  1328. # inherit documentation
  1329. i = self._sample_dict.get(sample)
  1330. if i is None:
  1331. return float('-inf')
  1332. return self._data[i] if self._logs else math.log(self._data[i], 2)
  1333. def update(self, sample, prob, log=True):
  1334. """
  1335. Update the probability for the given sample. This may cause the object
  1336. to stop being the valid probability distribution - the user must
  1337. ensure that they update the sample probabilities such that all samples
  1338. have probabilities between 0 and 1 and that all probabilities sum to
  1339. one.
  1340. :param sample: the sample for which to update the probability
  1341. :type sample: any
  1342. :param prob: the new probability
  1343. :type prob: float
  1344. :param log: is the probability already logged
  1345. :type log: bool
  1346. """
  1347. i = self._sample_dict.get(sample)
  1348. assert i is not None
  1349. if self._logs:
  1350. self._data[i] = prob if log else math.log(prob, 2)
  1351. else:
  1352. self._data[i] = 2 ** (prob) if log else prob
  1353. ##/////////////////////////////////////////////////////
  1354. ## Kneser-Ney Probability Distribution
  1355. ##//////////////////////////////////////////////////////
  1356. # This method for calculating probabilities was introduced in 1995 by Reinhard
  1357. # Kneser and Hermann Ney. It was meant to improve the accuracy of language
  1358. # models that use backing-off to deal with sparse data. The authors propose two
  1359. # ways of doing so: a marginal distribution constraint on the back-off
  1360. # distribution and a leave-one-out distribution. For a start, the first one is
  1361. # implemented as a class below.
  1362. #
  1363. # The idea behind a back-off n-gram model is that we have a series of
  1364. # frequency distributions for our n-grams so that in case we have not seen a
  1365. # given n-gram during training (and as a result have a 0 probability for it) we
  1366. # can 'back off' (hence the name!) and try testing whether we've seen the
  1367. # n-1-gram part of the n-gram in training.
  1368. #
  1369. # The novelty of Kneser and Ney's approach was that they decided to fiddle
  1370. # around with the way this latter, backed off probability was being calculated
  1371. # whereas their peers seemed to focus on the primary probability.
  1372. #
  1373. # The implementation below uses one of the techniques described in their paper
  1374. # titled "Improved backing-off for n-gram language modeling." In the same paper
  1375. # another technique is introduced to attempt to smooth the back-off
  1376. # distribution as well as the primary one. There is also a much-cited
  1377. # modification of this method proposed by Chen and Goodman.
  1378. #
  1379. # In order for the implementation of Kneser-Ney to be more efficient, some
  1380. # changes have been made to the original algorithm. Namely, the calculation of
  1381. # the normalizing function gamma has been significantly simplified and
  1382. # combined slightly differently with beta. None of these changes affect the
  1383. # nature of the algorithm, but instead aim to cut out unnecessary calculations
  1384. # and take advantage of storing and retrieving information in dictionaries
  1385. # where possible.
  1386. @compat.python_2_unicode_compatible
  1387. class KneserNeyProbDist(ProbDistI):
  1388. """
  1389. Kneser-Ney estimate of a probability distribution. This is a version of
  1390. back-off that counts how likely an n-gram is provided the n-1-gram had
  1391. been seen in training. Extends the ProbDistI interface, requires a trigram
  1392. FreqDist instance to train on. Optionally, a different from default discount
  1393. value can be specified. The default discount is set to 0.75.
  1394. """
  1395. def __init__(self, freqdist, bins=None, discount=0.75):
  1396. """
  1397. :param freqdist: The trigram frequency distribution upon which to base
  1398. the estimation
  1399. :type freqdist: FreqDist
  1400. :param bins: Included for compatibility with nltk.tag.hmm
  1401. :type bins: int or float
  1402. :param discount: The discount applied when retrieving counts of
  1403. trigrams
  1404. :type discount: float (preferred, but can be set to int)
  1405. """
  1406. if not bins:
  1407. self._bins = freqdist.B()
  1408. else:
  1409. self._bins = bins
  1410. self._D = discount
  1411. # cache for probability calculation
  1412. self._cache = {}
  1413. # internal bigram and trigram frequency distributions
  1414. self._bigrams = defaultdict(int)
  1415. self._trigrams = freqdist
  1416. # helper dictionaries used to calculate probabilities
  1417. self._wordtypes_after = defaultdict(float)
  1418. self._trigrams_contain = defaultdict(float)
  1419. self._wordtypes_before = defaultdict(float)
  1420. for w0, w1, w2 in freqdist:
  1421. self._bigrams[(w0, w1)] += freqdist[(w0, w1, w2)]
  1422. self._wordtypes_after[(w0, w1)] += 1
  1423. self._trigrams_contain[w1] += 1
  1424. self._wordtypes_before[(w1, w2)] += 1
  1425. def prob(self, trigram):
  1426. # sample must be a triple
  1427. if len(trigram) != 3:
  1428. raise ValueError('Expected an iterable with 3 members.')
  1429. trigram = tuple(trigram)
  1430. w0, w1, w2 = trigram
  1431. if trigram in self._cache:
  1432. return self._cache[trigram]
  1433. else:
  1434. # if the sample trigram was seen during training
  1435. if trigram in self._trigrams:
  1436. prob = (self._trigrams[trigram] - self.discount()) / self._bigrams[
  1437. (w0, w1)
  1438. ]
  1439. # else if the 'rougher' environment was seen during training
  1440. elif (w0, w1) in self._bigrams and (w1, w2) in self._wordtypes_before:
  1441. aftr = self._wordtypes_after[(w0, w1)]
  1442. bfr = self._wordtypes_before[(w1, w2)]
  1443. # the probability left over from alphas
  1444. leftover_prob = (aftr * self.discount()) / self._bigrams[(w0, w1)]
  1445. # the beta (including normalization)
  1446. beta = bfr / (self._trigrams_contain[w1] - aftr)
  1447. prob = leftover_prob * beta
  1448. # else the sample was completely unseen during training
  1449. else:
  1450. prob = 0.0
  1451. self._cache[trigram] = prob
  1452. return prob
  1453. def discount(self):
  1454. """
  1455. Return the value by which counts are discounted. By default set to 0.75.
  1456. :rtype: float
  1457. """
  1458. return self._D
  1459. def set_discount(self, discount):
  1460. """
  1461. Set the value by which counts are discounted to the value of discount.
  1462. :param discount: the new value to discount counts by
  1463. :type discount: float (preferred, but int possible)
  1464. :rtype: None
  1465. """
  1466. self._D = discount
  1467. def samples(self):
  1468. return self._trigrams.keys()
  1469. def max(self):
  1470. return self._trigrams.max()
  1471. def __repr__(self):
  1472. '''
  1473. Return a string representation of this ProbDist
  1474. :rtype: str
  1475. '''
  1476. return '<KneserNeyProbDist based on {0} trigrams'.format(self._trigrams.N())
  1477. ##//////////////////////////////////////////////////////
  1478. ## Probability Distribution Operations
  1479. ##//////////////////////////////////////////////////////
  1480. def log_likelihood(test_pdist, actual_pdist):
  1481. if not isinstance(test_pdist, ProbDistI) or not isinstance(actual_pdist, ProbDistI):
  1482. raise ValueError('expected a ProbDist.')
  1483. # Is this right?
  1484. return sum(
  1485. actual_pdist.prob(s) * math.log(test_pdist.prob(s), 2) for s in actual_pdist
  1486. )
  1487. def entropy(pdist):
  1488. probs = (pdist.prob(s) for s in pdist.samples())
  1489. return -sum(p * math.log(p, 2) for p in probs)
  1490. ##//////////////////////////////////////////////////////
  1491. ## Conditional Distributions
  1492. ##//////////////////////////////////////////////////////
  1493. @compat.python_2_unicode_compatible
  1494. class ConditionalFreqDist(defaultdict):
  1495. """
  1496. A collection of frequency distributions for a single experiment
  1497. run under different conditions. Conditional frequency
  1498. distributions are used to record the number of times each sample
  1499. occurred, given the condition under which the experiment was run.
  1500. For example, a conditional frequency distribution could be used to
  1501. record the frequency of each word (type) in a document, given its
  1502. length. Formally, a conditional frequency distribution can be
  1503. defined as a function that maps from each condition to the
  1504. FreqDist for the experiment under that condition.
  1505. Conditional frequency distributions are typically constructed by
  1506. repeatedly running an experiment under a variety of conditions,
  1507. and incrementing the sample outcome counts for the appropriate
  1508. conditions. For example, the following code will produce a
  1509. conditional frequency distribution that encodes how often each
  1510. word type occurs, given the length of that word type:
  1511. >>> from nltk.probability import ConditionalFreqDist
  1512. >>> from nltk.tokenize import word_tokenize
  1513. >>> sent = "the the the dog dog some other words that we do not care about"
  1514. >>> cfdist = ConditionalFreqDist()
  1515. >>> for word in word_tokenize(sent):
  1516. ... condition = len(word)
  1517. ... cfdist[condition][word] += 1
  1518. An equivalent way to do this is with the initializer:
  1519. >>> cfdist = ConditionalFreqDist((len(word), word) for word in word_tokenize(sent))
  1520. The frequency distribution for each condition is accessed using
  1521. the indexing operator:
  1522. >>> cfdist[3]
  1523. FreqDist({'the': 3, 'dog': 2, 'not': 1})
  1524. >>> cfdist[3].freq('the')
  1525. 0.5
  1526. >>> cfdist[3]['dog']
  1527. 2
  1528. When the indexing operator is used to access the frequency
  1529. distribution for a condition that has not been accessed before,
  1530. ``ConditionalFreqDist`` creates a new empty FreqDist for that
  1531. condition.
  1532. """
  1533. def __init__(self, cond_samples=None):
  1534. """
  1535. Construct a new empty conditional frequency distribution. In
  1536. particular, the count for every sample, under every condition,
  1537. is zero.
  1538. :param cond_samples: The samples to initialize the conditional
  1539. frequency distribution with
  1540. :type cond_samples: Sequence of (condition, sample) tuples
  1541. """
  1542. defaultdict.__init__(self, FreqDist)
  1543. if cond_samples:
  1544. for (cond, sample) in cond_samples:
  1545. self[cond][sample] += 1
  1546. def __reduce__(self):
  1547. kv_pairs = ((cond, self[cond]) for cond in self.conditions())
  1548. return (self.__class__, (), None, None, kv_pairs)
  1549. def conditions(self):
  1550. """
  1551. Return a list of the conditions that have been accessed for
  1552. this ``ConditionalFreqDist``. Use the indexing operator to
  1553. access the frequency distribution for a given condition.
  1554. Note that the frequency distributions for some conditions
  1555. may contain zero sample outcomes.
  1556. :rtype: list
  1557. """
  1558. return list(self.keys())
  1559. def N(self):
  1560. """
  1561. Return the total number of sample outcomes that have been
  1562. recorded by this ``ConditionalFreqDist``.
  1563. :rtype: int
  1564. """
  1565. return sum(fdist.N() for fdist in itervalues(self))
  1566. def plot(self, *args, **kwargs):
  1567. """
  1568. Plot the given samples from the conditional frequency distribution.
  1569. For a cumulative plot, specify cumulative=True.
  1570. (Requires Matplotlib to be installed.)
  1571. :param samples: The samples to plot
  1572. :type samples: list
  1573. :param title: The title for the graph
  1574. :type title: str
  1575. :param conditions: The conditions to plot (default is all)
  1576. :type conditions: list
  1577. """
  1578. try:
  1579. from matplotlib import pylab
  1580. except ImportError:
  1581. raise ValueError(
  1582. 'The plot function requires matplotlib to be installed.'
  1583. 'See http://matplotlib.org/'
  1584. )
  1585. cumulative = _get_kwarg(kwargs, 'cumulative', False)
  1586. percents = _get_kwarg(kwargs, 'percents', False)
  1587. conditions = _get_kwarg(kwargs, 'conditions', sorted(self.conditions()))
  1588. title = _get_kwarg(kwargs, 'title', '')
  1589. samples = _get_kwarg(
  1590. kwargs, 'samples', sorted(set(v for c in conditions for v in self[c]))
  1591. ) # this computation could be wasted
  1592. if "linewidth" not in kwargs:
  1593. kwargs["linewidth"] = 2
  1594. for condition in conditions:
  1595. if cumulative:
  1596. freqs = list(self[condition]._cumulative_frequencies(samples))
  1597. ylabel = "Cumulative Counts"
  1598. legend_loc = 'lower right'
  1599. if percents:
  1600. freqs = [f / freqs[len(freqs) - 1] * 100 for f in freqs]
  1601. ylabel = "Cumulative Percents"
  1602. else:
  1603. freqs = [self[condition][sample] for sample in samples]
  1604. ylabel = "Counts"
  1605. legend_loc = 'upper right'
  1606. # percents = [f * 100 for f in freqs] only in ConditionalProbDist?
  1607. kwargs['label'] = "%s" % condition
  1608. pylab.plot(freqs, *args, **kwargs)
  1609. pylab.legend(loc=legend_loc)
  1610. pylab.grid(True, color="silver")
  1611. pylab.xticks(range(len(samples)), [text_type(s) for s in samples], rotation=90)
  1612. if title:
  1613. pylab.title(title)
  1614. pylab.xlabel("Samples")
  1615. pylab.ylabel(ylabel)
  1616. pylab.show()
  1617. def tabulate(self, *args, **kwargs):
  1618. """
  1619. Tabulate the given samples from the conditional frequency distribution.
  1620. :param samples: The samples to plot
  1621. :type samples: list
  1622. :param conditions: The conditions to plot (default is all)
  1623. :type conditions: list
  1624. :param cumulative: A flag to specify whether the freqs are cumulative (default = False)
  1625. :type title: bool
  1626. """
  1627. cumulative = _get_kwarg(kwargs, 'cumulative', False)
  1628. conditions = _get_kwarg(kwargs, 'conditions', sorted(self.conditions()))
  1629. samples = _get_kwarg(
  1630. kwargs, 'samples', sorted(set(v for c in conditions for v in self[c]))
  1631. ) # this computation could be wasted
  1632. width = max(len("%s" % s) for s in samples)
  1633. freqs = dict()
  1634. for c in conditions:
  1635. if cumulative:
  1636. freqs[c] = list(self[c]._cumulative_frequencies(samples))
  1637. else:
  1638. freqs[c] = [self[c][sample] for sample in samples]
  1639. width = max(width, max(len("%d" % f) for f in freqs[c]))
  1640. condition_size = max(len("%s" % c) for c in conditions)
  1641. print(' ' * condition_size, end=' ')
  1642. for s in samples:
  1643. print("%*s" % (width, s), end=' ')
  1644. print()
  1645. for c in conditions:
  1646. print("%*s" % (condition_size, c), end=' ')
  1647. for f in freqs[c]:
  1648. print("%*d" % (width, f), end=' ')
  1649. print()
  1650. # Mathematical operators
  1651. def __add__(self, other):
  1652. """
  1653. Add counts from two ConditionalFreqDists.
  1654. """
  1655. if not isinstance(other, ConditionalFreqDist):
  1656. return NotImplemented
  1657. result = ConditionalFreqDist()
  1658. for cond in self.conditions():
  1659. newfreqdist = self[cond] + other[cond]
  1660. if newfreqdist:
  1661. result[cond] = newfreqdist
  1662. for cond in other.conditions():
  1663. if cond not in self.conditions():
  1664. for elem, count in other[cond].items():
  1665. if count > 0:
  1666. result[cond][elem] = count
  1667. return result
  1668. def __sub__(self, other):
  1669. """
  1670. Subtract count, but keep only results with positive counts.
  1671. """
  1672. if not isinstance(other, ConditionalFreqDist):
  1673. return NotImplemented
  1674. result = ConditionalFreqDist()
  1675. for cond in self.conditions():
  1676. newfreqdist = self[cond] - other[cond]
  1677. if newfreqdist:
  1678. result[cond] = newfreqdist
  1679. for cond in other.conditions():
  1680. if cond not in self.conditions():
  1681. for elem, count in other[cond].items():
  1682. if count < 0:
  1683. result[cond][elem] = 0 - count
  1684. return result
  1685. def __or__(self, other):
  1686. """
  1687. Union is the maximum of value in either of the input counters.
  1688. """
  1689. if not isinstance(other, ConditionalFreqDist):
  1690. return NotImplemented
  1691. result = ConditionalFreqDist()
  1692. for cond in self.conditions():
  1693. newfreqdist = self[cond] | other[cond]
  1694. if newfreqdist:
  1695. result[cond] = newfreqdist
  1696. for cond in other.conditions():
  1697. if cond not in self.conditions():
  1698. for elem, count in other[cond].items():
  1699. if count > 0:
  1700. result[cond][elem] = count
  1701. return result
  1702. def __and__(self, other):
  1703. """
  1704. Intersection is the minimum of corresponding counts.
  1705. """
  1706. if not isinstance(other, ConditionalFreqDist):
  1707. return NotImplemented
  1708. result = ConditionalFreqDist()
  1709. for cond in self.conditions():
  1710. newfreqdist = self[cond] & other[cond]
  1711. if newfreqdist:
  1712. result[cond] = newfreqdist
  1713. return result
  1714. # @total_ordering doesn't work here, since the class inherits from a builtin class
  1715. def __le__(self, other):
  1716. if not isinstance(other, ConditionalFreqDist):
  1717. raise_unorderable_types("<=", self, other)
  1718. return set(self.conditions()).issubset(other.conditions()) and all(
  1719. self[c] <= other[c] for c in self.conditions()
  1720. )
  1721. def __lt__(self, other):
  1722. if not isinstance(other, ConditionalFreqDist):
  1723. raise_unorderable_types("<", self, other)
  1724. return self <= other and self != other
  1725. def __ge__(self, other):
  1726. if not isinstance(other, ConditionalFreqDist):
  1727. raise_unorderable_types(">=", self, other)
  1728. return other <= self
  1729. def __gt__(self, other):
  1730. if not isinstance(other, ConditionalFreqDist):
  1731. raise_unorderable_types(">", self, other)
  1732. return other < self
  1733. def __repr__(self):
  1734. """
  1735. Return a string representation of this ``ConditionalFreqDist``.
  1736. :rtype: str
  1737. """
  1738. return '<ConditionalFreqDist with %d conditions>' % len(self)
  1739. @compat.python_2_unicode_compatible
  1740. @add_metaclass(ABCMeta)
  1741. class ConditionalProbDistI(dict):
  1742. """
  1743. A collection of probability distributions for a single experiment
  1744. run under different conditions. Conditional probability
  1745. distributions are used to estimate the likelihood of each sample,
  1746. given the condition under which the experiment was run. For
  1747. example, a conditional probability distribution could be used to
  1748. estimate the probability of each word type in a document, given
  1749. the length of the word type. Formally, a conditional probability
  1750. distribution can be defined as a function that maps from each
  1751. condition to the ``ProbDist`` for the experiment under that
  1752. condition.
  1753. """
  1754. @abstractmethod
  1755. def __init__(self):
  1756. """
  1757. Classes inheriting from ConditionalProbDistI should implement __init__.
  1758. """
  1759. def conditions(self):
  1760. """
  1761. Return a list of the conditions that are represented by
  1762. this ``ConditionalProbDist``. Use the indexing operator to
  1763. access the probability distribution for a given condition.
  1764. :rtype: list
  1765. """
  1766. return list(self.keys())
  1767. def __repr__(self):
  1768. """
  1769. Return a string representation of this ``ConditionalProbDist``.
  1770. :rtype: str
  1771. """
  1772. return '<%s with %d conditions>' % (type(self).__name__, len(self))
  1773. class ConditionalProbDist(ConditionalProbDistI):
  1774. """
  1775. A conditional probability distribution modeling the experiments
  1776. that were used to generate a conditional frequency distribution.
  1777. A ConditionalProbDist is constructed from a
  1778. ``ConditionalFreqDist`` and a ``ProbDist`` factory:
  1779. - The ``ConditionalFreqDist`` specifies the frequency
  1780. distribution for each condition.
  1781. - The ``ProbDist`` factory is a function that takes a
  1782. condition's frequency distribution, and returns its
  1783. probability distribution. A ``ProbDist`` class's name (such as
  1784. ``MLEProbDist`` or ``HeldoutProbDist``) can be used to specify
  1785. that class's constructor.
  1786. The first argument to the ``ProbDist`` factory is the frequency
  1787. distribution that it should model; and the remaining arguments are
  1788. specified by the ``factory_args`` parameter to the
  1789. ``ConditionalProbDist`` constructor. For example, the following
  1790. code constructs a ``ConditionalProbDist``, where the probability
  1791. distribution for each condition is an ``ELEProbDist`` with 10 bins:
  1792. >>> from nltk.corpus import brown
  1793. >>> from nltk.probability import ConditionalFreqDist
  1794. >>> from nltk.probability import ConditionalProbDist, ELEProbDist
  1795. >>> cfdist = ConditionalFreqDist(brown.tagged_words()[:5000])
  1796. >>> cpdist = ConditionalProbDist(cfdist, ELEProbDist, 10)
  1797. >>> cpdist['passed'].max()
  1798. 'VBD'
  1799. >>> cpdist['passed'].prob('VBD')
  1800. 0.423...
  1801. """
  1802. def __init__(self, cfdist, probdist_factory, *factory_args, **factory_kw_args):
  1803. """
  1804. Construct a new conditional probability distribution, based on
  1805. the given conditional frequency distribution and ``ProbDist``
  1806. factory.
  1807. :type cfdist: ConditionalFreqDist
  1808. :param cfdist: The ``ConditionalFreqDist`` specifying the
  1809. frequency distribution for each condition.
  1810. :type probdist_factory: class or function
  1811. :param probdist_factory: The function or class that maps
  1812. a condition's frequency distribution to its probability
  1813. distribution. The function is called with the frequency
  1814. distribution as its first argument,
  1815. ``factory_args`` as its remaining arguments, and
  1816. ``factory_kw_args`` as keyword arguments.
  1817. :type factory_args: (any)
  1818. :param factory_args: Extra arguments for ``probdist_factory``.
  1819. These arguments are usually used to specify extra
  1820. properties for the probability distributions of individual
  1821. conditions, such as the number of bins they contain.
  1822. :type factory_kw_args: (any)
  1823. :param factory_kw_args: Extra keyword arguments for ``probdist_factory``.
  1824. """
  1825. self._probdist_factory = probdist_factory
  1826. self._factory_args = factory_args
  1827. self._factory_kw_args = factory_kw_args
  1828. for condition in cfdist:
  1829. self[condition] = probdist_factory(
  1830. cfdist[condition], *factory_args, **factory_kw_args
  1831. )
  1832. def __missing__(self, key):
  1833. self[key] = self._probdist_factory(
  1834. FreqDist(), *self._factory_args, **self._factory_kw_args
  1835. )
  1836. return self[key]
  1837. class DictionaryConditionalProbDist(ConditionalProbDistI):
  1838. """
  1839. An alternative ConditionalProbDist that simply wraps a dictionary of
  1840. ProbDists rather than creating these from FreqDists.
  1841. """
  1842. def __init__(self, probdist_dict):
  1843. """
  1844. :param probdist_dict: a dictionary containing the probdists indexed
  1845. by the conditions
  1846. :type probdist_dict: dict any -> probdist
  1847. """
  1848. self.update(probdist_dict)
  1849. def __missing__(self, key):
  1850. self[key] = DictionaryProbDist()
  1851. return self[key]
  1852. ##//////////////////////////////////////////////////////
  1853. ## Adding in log-space.
  1854. ##//////////////////////////////////////////////////////
  1855. # If the difference is bigger than this, then just take the bigger one:
  1856. _ADD_LOGS_MAX_DIFF = math.log(1e-30, 2)
  1857. def add_logs(logx, logy):
  1858. """
  1859. Given two numbers ``logx`` = *log(x)* and ``logy`` = *log(y)*, return
  1860. *log(x+y)*. Conceptually, this is the same as returning
  1861. ``log(2**(logx)+2**(logy))``, but the actual implementation
  1862. avoids overflow errors that could result from direct computation.
  1863. """
  1864. if logx < logy + _ADD_LOGS_MAX_DIFF:
  1865. return logy
  1866. if logy < logx + _ADD_LOGS_MAX_DIFF:
  1867. return logx
  1868. base = min(logx, logy)
  1869. return base + math.log(2 ** (logx - base) + 2 ** (logy - base), 2)
  1870. def sum_logs(logs):
  1871. return reduce(add_logs, logs[1:], logs[0]) if len(logs) != 0 else _NINF
  1872. ##//////////////////////////////////////////////////////
  1873. ## Probabilistic Mix-in
  1874. ##//////////////////////////////////////////////////////
  1875. class ProbabilisticMixIn(object):
  1876. """
  1877. A mix-in class to associate probabilities with other classes
  1878. (trees, rules, etc.). To use the ``ProbabilisticMixIn`` class,
  1879. define a new class that derives from an existing class and from
  1880. ProbabilisticMixIn. You will need to define a new constructor for
  1881. the new class, which explicitly calls the constructors of both its
  1882. parent classes. For example:
  1883. >>> from nltk.probability import ProbabilisticMixIn
  1884. >>> class A:
  1885. ... def __init__(self, x, y): self.data = (x,y)
  1886. ...
  1887. >>> class ProbabilisticA(A, ProbabilisticMixIn):
  1888. ... def __init__(self, x, y, **prob_kwarg):
  1889. ... A.__init__(self, x, y)
  1890. ... ProbabilisticMixIn.__init__(self, **prob_kwarg)
  1891. See the documentation for the ProbabilisticMixIn
  1892. ``constructor<__init__>`` for information about the arguments it
  1893. expects.
  1894. You should generally also redefine the string representation
  1895. methods, the comparison methods, and the hashing method.
  1896. """
  1897. def __init__(self, **kwargs):
  1898. """
  1899. Initialize this object's probability. This initializer should
  1900. be called by subclass constructors. ``prob`` should generally be
  1901. the first argument for those constructors.
  1902. :param prob: The probability associated with the object.
  1903. :type prob: float
  1904. :param logprob: The log of the probability associated with
  1905. the object.
  1906. :type logprob: float
  1907. """
  1908. if 'prob' in kwargs:
  1909. if 'logprob' in kwargs:
  1910. raise TypeError('Must specify either prob or logprob ' '(not both)')
  1911. else:
  1912. ProbabilisticMixIn.set_prob(self, kwargs['prob'])
  1913. elif 'logprob' in kwargs:
  1914. ProbabilisticMixIn.set_logprob(self, kwargs['logprob'])
  1915. else:
  1916. self.__prob = self.__logprob = None
  1917. def set_prob(self, prob):
  1918. """
  1919. Set the probability associated with this object to ``prob``.
  1920. :param prob: The new probability
  1921. :type prob: float
  1922. """
  1923. self.__prob = prob
  1924. self.__logprob = None
  1925. def set_logprob(self, logprob):
  1926. """
  1927. Set the log probability associated with this object to
  1928. ``logprob``. I.e., set the probability associated with this
  1929. object to ``2**(logprob)``.
  1930. :param logprob: The new log probability
  1931. :type logprob: float
  1932. """
  1933. self.__logprob = logprob
  1934. self.__prob = None
  1935. def prob(self):
  1936. """
  1937. Return the probability associated with this object.
  1938. :rtype: float
  1939. """
  1940. if self.__prob is None:
  1941. if self.__logprob is None:
  1942. return None
  1943. self.__prob = 2 ** (self.__logprob)
  1944. return self.__prob
  1945. def logprob(self):
  1946. """
  1947. Return ``log(p)``, where ``p`` is the probability associated
  1948. with this object.
  1949. :rtype: float
  1950. """
  1951. if self.__logprob is None:
  1952. if self.__prob is None:
  1953. return None
  1954. self.__logprob = math.log(self.__prob, 2)
  1955. return self.__logprob
  1956. class ImmutableProbabilisticMixIn(ProbabilisticMixIn):
  1957. def set_prob(self, prob):
  1958. raise ValueError('%s is immutable' % self.__class__.__name__)
  1959. def set_logprob(self, prob):
  1960. raise ValueError('%s is immutable' % self.__class__.__name__)
  1961. ## Helper function for processing keyword arguments
  1962. def _get_kwarg(kwargs, key, default):
  1963. if key in kwargs:
  1964. arg = kwargs[key]
  1965. del kwargs[key]
  1966. else:
  1967. arg = default
  1968. return arg
  1969. ##//////////////////////////////////////////////////////
  1970. ## Demonstration
  1971. ##//////////////////////////////////////////////////////
  1972. def _create_rand_fdist(numsamples, numoutcomes):
  1973. """
  1974. Create a new frequency distribution, with random samples. The
  1975. samples are numbers from 1 to ``numsamples``, and are generated by
  1976. summing two numbers, each of which has a uniform distribution.
  1977. """
  1978. fdist = FreqDist()
  1979. for x in range(numoutcomes):
  1980. y = random.randint(1, (1 + numsamples) // 2) + random.randint(
  1981. 0, numsamples // 2
  1982. )
  1983. fdist[y] += 1
  1984. return fdist
  1985. def _create_sum_pdist(numsamples):
  1986. """
  1987. Return the true probability distribution for the experiment
  1988. ``_create_rand_fdist(numsamples, x)``.
  1989. """
  1990. fdist = FreqDist()
  1991. for x in range(1, (1 + numsamples) // 2 + 1):
  1992. for y in range(0, numsamples // 2 + 1):
  1993. fdist[x + y] += 1
  1994. return MLEProbDist(fdist)
  1995. def demo(numsamples=6, numoutcomes=500):
  1996. """
  1997. A demonstration of frequency distributions and probability
  1998. distributions. This demonstration creates three frequency
  1999. distributions with, and uses them to sample a random process with
  2000. ``numsamples`` samples. Each frequency distribution is sampled
  2001. ``numoutcomes`` times. These three frequency distributions are
  2002. then used to build six probability distributions. Finally, the
  2003. probability estimates of these distributions are compared to the
  2004. actual probability of each sample.
  2005. :type numsamples: int
  2006. :param numsamples: The number of samples to use in each demo
  2007. frequency distributions.
  2008. :type numoutcomes: int
  2009. :param numoutcomes: The total number of outcomes for each
  2010. demo frequency distribution. These outcomes are divided into
  2011. ``numsamples`` bins.
  2012. :rtype: None
  2013. """
  2014. # Randomly sample a stochastic process three times.
  2015. fdist1 = _create_rand_fdist(numsamples, numoutcomes)
  2016. fdist2 = _create_rand_fdist(numsamples, numoutcomes)
  2017. fdist3 = _create_rand_fdist(numsamples, numoutcomes)
  2018. # Use our samples to create probability distributions.
  2019. pdists = [
  2020. MLEProbDist(fdist1),
  2021. LidstoneProbDist(fdist1, 0.5, numsamples),
  2022. HeldoutProbDist(fdist1, fdist2, numsamples),
  2023. HeldoutProbDist(fdist2, fdist1, numsamples),
  2024. CrossValidationProbDist([fdist1, fdist2, fdist3], numsamples),
  2025. SimpleGoodTuringProbDist(fdist1),
  2026. SimpleGoodTuringProbDist(fdist1, 7),
  2027. _create_sum_pdist(numsamples),
  2028. ]
  2029. # Find the probability of each sample.
  2030. vals = []
  2031. for n in range(1, numsamples + 1):
  2032. vals.append(tuple([n, fdist1.freq(n)] + [pdist.prob(n) for pdist in pdists]))
  2033. # Print the results in a formatted table.
  2034. print(
  2035. (
  2036. '%d samples (1-%d); %d outcomes were sampled for each FreqDist'
  2037. % (numsamples, numsamples, numoutcomes)
  2038. )
  2039. )
  2040. print('=' * 9 * (len(pdists) + 2))
  2041. FORMATSTR = ' FreqDist ' + '%8s ' * (len(pdists) - 1) + '| Actual'
  2042. print(FORMATSTR % tuple(repr(pdist)[1:9] for pdist in pdists[:-1]))
  2043. print('-' * 9 * (len(pdists) + 2))
  2044. FORMATSTR = '%3d %8.6f ' + '%8.6f ' * (len(pdists) - 1) + '| %8.6f'
  2045. for val in vals:
  2046. print(FORMATSTR % val)
  2047. # Print the totals for each column (should all be 1.0)
  2048. zvals = list(zip(*vals))
  2049. sums = [sum(val) for val in zvals[1:]]
  2050. print('-' * 9 * (len(pdists) + 2))
  2051. FORMATSTR = 'Total ' + '%8.6f ' * (len(pdists)) + '| %8.6f'
  2052. print(FORMATSTR % tuple(sums))
  2053. print('=' * 9 * (len(pdists) + 2))
  2054. # Display the distributions themselves, if they're short enough.
  2055. if len("%s" % fdist1) < 70:
  2056. print(' fdist1: %s' % fdist1)
  2057. print(' fdist2: %s' % fdist2)
  2058. print(' fdist3: %s' % fdist3)
  2059. print()
  2060. print('Generating:')
  2061. for pdist in pdists:
  2062. fdist = FreqDist(pdist.generate() for i in range(5000))
  2063. print('%20s %s' % (pdist.__class__.__name__[:20], ("%s" % fdist)[:55]))
  2064. print()
  2065. def gt_demo():
  2066. from nltk import corpus
  2067. emma_words = corpus.gutenberg.words('austen-emma.txt')
  2068. fd = FreqDist(emma_words)
  2069. sgt = SimpleGoodTuringProbDist(fd)
  2070. print('%18s %8s %14s' % ("word", "freqency", "SimpleGoodTuring"))
  2071. fd_keys_sorted = (
  2072. key for key, value in sorted(fd.items(), key=lambda item: item[1], reverse=True)
  2073. )
  2074. for key in fd_keys_sorted:
  2075. print('%18s %8d %14e' % (key, fd[key], sgt.prob(key)))
  2076. if __name__ == '__main__':
  2077. demo(6, 10)
  2078. demo(5, 5000)
  2079. gt_demo()
  2080. __all__ = [
  2081. 'ConditionalFreqDist',
  2082. 'ConditionalProbDist',
  2083. 'ConditionalProbDistI',
  2084. 'CrossValidationProbDist',
  2085. 'DictionaryConditionalProbDist',
  2086. 'DictionaryProbDist',
  2087. 'ELEProbDist',
  2088. 'FreqDist',
  2089. 'SimpleGoodTuringProbDist',
  2090. 'HeldoutProbDist',
  2091. 'ImmutableProbabilisticMixIn',
  2092. 'LaplaceProbDist',
  2093. 'LidstoneProbDist',
  2094. 'MLEProbDist',
  2095. 'MutableProbDist',
  2096. 'KneserNeyProbDist',
  2097. 'ProbDistI',
  2098. 'ProbabilisticMixIn',
  2099. 'UniformProbDist',
  2100. 'WittenBellProbDist',
  2101. 'add_logs',
  2102. 'log_likelihood',
  2103. 'sum_logs',
  2104. 'entropy',
  2105. ]