JL i`dZddlZddlZddlZddlZddlmZmZddlm Z m Z ddl m Z ddl mZedZGdd e ZGd d e ZGd deZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGdd eZGd!d"eZGd#d$eZGd%d&eZd'Z d(Z!Gd)d*e Z"Gd+d,e#e Z$Gd-d.e$Z%Gd/d0e$Z&ejNd1d2Z(d3Z)d4Z*Gd5d6Z+Gd7d8e+Z,d9Z-d:Z.d;Z/dDd=Z0d>Z1e2d?k(re0d>> from nltk.tokenize import word_tokenize >>> from nltk.probability import FreqDist >>> sent = 'This is an example sentence' >>> fdist = FreqDist() >>> for word in word_tokenize(sent): ... fdist[word.lower()] += 1 An equivalent way to do this is with the initializer: >>> fdist = FreqDist(word.lower() for word in word_tokenize(sent)) c>tj||d|_y)ab Construct a new frequency distribution. If ``samples`` is given, then the frequency distribution will be initialized with the count of each object in ``samples``; otherwise, it will be initialized to be empty. In particular, ``FreqDist()`` returns an empty frequency distribution; and ``FreqDist(samples)`` first creates an empty frequency distribution, and then calls ``update`` with the list ``samples``. :param samples: The samples to initialize the frequency distribution with. :type samples: Sequence N)r__init___Nselfsampless V/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/probability.pyr zFreqDist.__init__Vs w'cn|jt|j|_|jS)z Return the total number of sample outcomes that have been recorded by this FreqDist. For the number of unique sample values (or bins) with counts greater than zero, use ``FreqDist.B()``. :rtype: int )r sumvaluesrs rNz FreqDist.Nks( 77?$++-(DGwwrc4d|_t| ||y)zO Override ``Counter.__setitem__()`` to invalidate the cached N N)r super __setitem__rkeyval __class__s rrzFreqDist.__setitem__ys C%rc2d|_t| |y)zO Override ``Counter.__delitem__()`` to invalidate the cached N N)r r __delitem__)rrrs rr zFreqDist.__delitem__s C rc2d|_t||i|y)zJ Override ``Counter.update()`` to invalidate the cached N N)r rupdate)rargskwargsrs rr"zFreqDist.updates ''rc4d|_t| ||y)zN Override ``Counter.setdefault()`` to invalidate the cached N N)r r setdefaultrs rr&zFreqDist.setdefaults 3$rct|S)a  Return the total number of sample values (or "bins") that have counts greater than zero. For the total number of sample outcomes recorded, use ``FreqDist.N()``. (FreqDist.B() is the same as len(FreqDist).) :rtype: int lenrs rBz FreqDist.Bs4yrc>|Dcgc] }||dk(s |c}Scc}w)ze Return a list of all samples that occur once (hapax legomena) :rtype: list )ritems rhapaxeszFreqDist.hapaxess" "&9dq999s c*|j||SN)r_Nr)rrbinss rNrz FreqDist.Nrsyyq!!rctt}|jD]}||xxdz cc<|||jz nd|d<|S)a Return the dictionary mapping r to Nr, the number of samples with frequency r, where Nr > 0. :type bins: int :param bins: The number of possible sample outcomes. ``bins`` is used to calculate Nr(0). In particular, Nr(0) is ``bins-self.B()``. If ``bins`` is not specified, it defaults to ``self.B()`` (so Nr(0) will be 0). :rtype: int r,r)rintrr*)rr4_r_Nrcounts rr2z FreqDist.r_NrsRC [[] E %LA L '+&64$&&(?Aa rc#6Kd}|D]}|||z }|yw)a0 Return the cumulative frequencies of the specified samples. If no samples are specified, all counts are returned, starting with the largest. :param samples: the samples whose frequencies should be returned. :type samples: any :rtype: list(float) Nr-)rrcfsamples r_cumulative_frequenciesz FreqDist._cumulative_frequenciess/ F $v, BH sc>|j}|dk(ry|||z S)a0 Return the frequency of a given sample. The frequency of a sample is defined as the count of that sample divided by the total number of sample outcomes that have been recorded by this FreqDist. The count of a sample is defined as the number of times that sample outcome was recorded by this FreqDist. Frequencies are always real numbers in the range [0, 1]. :param sample: the sample whose frequency should be returned. :type sample: any :rtype: float rr)rr=ns rfreqz FreqDist.freqs( FFH 6F|arcbt|dk(r td|jdddS)a Return the sample with the greatest number of outcomes in this frequency distribution. If two or more samples have the same number of outcomes, return one of them; which sample is returned is undefined. If no outcomes have occurred in this frequency distribution, return None. :return: The sample with the maximum number of outcomes in this frequency distribution. :rtype: any or None rz?A FreqDist must have at least one sample before max is defined.r,)r) ValueError most_commonrs rmaxz FreqDist.maxs< t9>Q "1%a((rF)title cumulativepercentsshowcZ ddlm}t |dk(r t |g}|j |D cgc]\} } |  } } } |rt |j| } d} n| Dcgc]}|| } }d} |r)| Dcgc]}||jz dz} }| dz } n| dz } |j}|jd d d |vrd |d <|r|j||j| fi||jtt | |j| Dcgc] }t!|c}d|j#d|j%| |r|j'|S#t$r}td|d}~wwxYwcc} } wcc}wcc}wcc}w)a Plot samples from the frequency distribution displaying the most frequent sample first. If an integer parameter is supplied, stop after this many samples have been plotted. For a cumulative plot, specify cumulative=True. Additional ``**kwargs`` are passed to matplotlib's plot function. (Requires Matplotlib to be installed.) :param title: The title for the graph. :type title: str :param cumulative: Whether the plot is cumulative. (default = False) :type cumulative: bool :param percents: Whether the plot uses percents instead of counts. (default = False) :type percents: bool :param show: Whether to show the plot, or only return the ax. :type show: bool rNQThe plot function requires matplotlib to be installed.See https://matplotlib.org/ Cumulative rGdPercentsCountsTsilvercolor linewidthZrotationSamples)matplotlib.pyplotpyplot ImportErrorrDr)rElistr>rgcagrid set_titleplot set_xticksrangeset_xticklabelsstr set_xlabel set_ylabelrK)rrHrIrJrKr#r$plter._rfreqsylabelr=faxss rrbz FreqDist.plots(  + t9>I;D'7t'7'7'>?GD!4?? 55g>?E"F078fT&\8E8F 167AQ\C'7E7 j F h F WWY H% f $"#F;   LL    eCL)* G4qCF4rB i  f  HHJ Q .  @ 985s.E; F& F<F#*F(; F FFc \t|dk(r t|g}t|d|j|Dcgc]\}}| c}}}t|dd}|rt|j |}n|Dcgc]}|| }}t d|D} t | t d|D} t t|D]} td| || fzd tt t|D]} td | || fzd ty cc}}wcc}w) a Tabulate the given samples from the frequency distribution (cumulative), displaying the most frequent sample first. If an integer parameter is supplied, stop after this many samples have been plotted. :param samples: The samples to plot (default is all samples) :type samples: list :param cumulative: A flag to specify whether the freqs are cumulative (default = False) :type title: bool rrrIFc34K|]}t|ywr1r(.0rps r z$FreqDist.tabulate..Ps1AC1#K1sc38K|]}td|zywz%dNr(rtrns rruz$FreqDist.tabulate..Qs<s4!8}<%*s end%*dN)r) _get_kwargrEr^r>rFrdprint) rr#r$r.rkrrIrlr=widthis rtabulatezFreqDist.tabulate7s% t9>I;D I4DD4D4Dd4KLqL   e< 55g>?E078fT&\8E8111E3>> FreqDist('abbb') + FreqDist('bcc') FreqDist({'b': 4, 'c': 2, 'a': 1}) )rr__add__rotherrs rrzFreqDist.__add__d~~egoe455rc@|jt| |S)z Subtract count, but keep only results with positive counts. >>> FreqDist('abbbc') - FreqDist('bccd') FreqDist({'b': 2, 'a': 1}) )rr__sub__rs rrzFreqDist.__sub__nrrc@|jt| |S)z Union is the maximum of value in either of the input counters. >>> FreqDist('abbb') | FreqDist('bcc') FreqDist({'b': 3, 'c': 2, 'a': 1}) )rr__or__rs rrzFreqDist.__or__xs~~egnU344rc@|jt| |S)z Intersection is the minimum of corresponding counts. >>> FreqDist('abbb') & FreqDist('bcc') FreqDist({'b': 1}) )rr__and__rs rrzFreqDist.__and__rrctts tdtj xrt fdDS)a8 Returns True if this frequency distribution is a subset of the other and for no key the value exceeds the value of the same key from the other frequency distribution. The <= operator forms partial order and satisfying the axioms reflexivity, antisymmetry and transitivity. >>> FreqDist('a') <= FreqDist('a') True >>> a = FreqDist('abc') >>> b = FreqDist('aabc') >>> (a <= b, b <= a) (True, False) >>> FreqDist('a') <= FreqDist('abcd') True >>> FreqDist('abc') <= FreqDist('xyz') False >>> FreqDist('xyz') <= FreqDist('abc') False >>> c = FreqDist('a') >>> d = FreqDist('aa') >>> e = FreqDist('aaa') >>> c <= d and d <= e and c <= e True <=c34K|]}||kywr1r-rtrrrs rruz"FreqDist.__le__..s#1 (+DIs #1 ) isinstancer rsetissubsetallrrs``r__le__zFreqDist.__le__sK6%* #D$ 64y!!%( S1 /31 .  rctts tdtj xrt fdDS)N>=c34K|]}||k\ywr1r-rs rruz"FreqDist.__ge__..s#3 (+DIs #3 r)rr rr issupersetrrs``r__ge__zFreqDist.__ge__sI%* #D$ 64y##E* s3 /43 0  rc||kxr||k( Sr1r-rs rzFreqDist.!Dtu}3Drc||k\xr||k( Sr1r-rs rrzFreqDist.rrc"|jS)Z Return a string representation of this FreqDist. :rtype: string )pformatrs r__repr__zFreqDist.__repr__s ||~rc>t|j||y)z Print a string representation of this FreqDist to 'stream' :param maxlen: The maximum number of items to print :type maxlen: int :param stream: The stream to print to. stdout by default )maxlen)fileN)rr)rrstreams rpprintzFreqDist.pprints dll&l)7rc|j|Dcgc]}dj|}}t||kDr|jddjdj |Scc}w)z Return a string representation of this FreqDist. :param maxlen: The maximum number of items to display :type maxlen: int :rtype: string z {!r}: {!r}z...zFreqDist({{{0}}})z, )rEformatr)appendjoin)rrr.itemss rrzFreqDist.pformatsh9=8H8H8PQ$$$d+QQ t9v  LL "))$))E*:;;RsA+c>dt||jfzS)rz*)r)rrs r__str__zFreqDist.__str__s SSSrc#bK|j|jD] \}}| yw)zh Return an iterator which yields tokens ordered by frequency. :rtype: iterator N)rEr*)rtokenrks r__iter__zFreqDist.__iter__s1 ((2 HE1K s-/r1) N)r)"__name__ __module__ __qualname____doc__r rrr r"r&r*r/r5r2r>rBrFrbrrrrrrrr__lt____gt__rrrrr __classcell__rs@rr r 9s8* &!(% :"* " ()&%%e>@!F$6656 B EF DF8 <Trr cheZdZdZdZ edZedZdZedZ edZ dZ d Z y ) ProbDistIa A probability distribution for the outcomes of an experiment. A probability distribution specifies how likely it is that an experiment will have any given outcome. For example, a probability distribution could be used to predict the probability that a token in a document will have a given type. Formally, a probability distribution can be defined as a function mapping from samples to nonnegative real numbers, such that the sum of every number in the function's range is 1.0. A ``ProbDist`` is often used to model the probability distribution of the experiment used to generate a frequency distribution. Tcy)zN Classes inheriting from ProbDistI should implement __init__. Nr-rs rr zProbDistI.__init__rcy)a Return the probability for a given sample. Probabilities are always real numbers in the range [0, 1]. :param sample: The sample whose probability should be returned. :type sample: any :rtype: float Nr-rr=s rprobzProbDistI.probrrcf|j|}|dk7rtj|dStS)z Return the base 2 logarithm of the probability for a given sample. :param sample: The sample whose probability should be returned. :type sample: any :rtype: float rrV)rmathlog_NINF)rr=ps rlogprobzProbDistI.logprobs- IIf !"atxx1~2U2rcy)z Return the sample with the greatest probability. If two or more samples have the same probability, return one of them; which sample is returned is undefined. :rtype: any Nr-rs rrFz ProbDistI.maxrrcy)z Return a list of all samples that have nonzero probabilities. Use ``prob`` to find the probability of each sample. :rtype: list Nr-rs rrzProbDistI.samples(rrcy)zi Return the ratio by which counts are discounted on average: c*/c :rtype: float r;r-rs rdiscountzProbDistI.discount2s rcNtj}|}|jD]}||j|z}|dks|cS|dkrS|jrt j d|d||z dtj t|jS)z Return a randomly selected sample from this probability distribution. The probability of returning each sample ``samp`` is equal to ``self.prob(samp)``. rg-C6?zProbability distribution z sums to z.; generate() is returning an arbitrary sample.)randomrr SUM_TO_ONEwarningswarnchoicer^)rrp_initr=s rgeneratezProbDistI.generate<s MMOlln F 6" "AAv   v:M ?? MM8)r)rrs rrzUniformProbDist.__repr__vs2S5IIIrN) rrrrr rrFrrr-rrrrTs! .$> Jrrc>eZdZdZdZedZdZdZdZ dZ y) RandomProbDistz Generates a random probability distribution whereby each sample will be between 0 and 1 with equal probability (uniform random distribution. Also called a continuous uniform distribution). ct|dk(r td|j||_t |jj |_y)Nrz9A probability distribution must have at least one sample.)r)rDunirand_probsr^keysrrs rr zRandomProbDist.__init__sI w<1 P ll7+ T[[--/0 rcdt|}tt|Dcgc]}tj}}t |}t |D] \}}||z ||<t |}|dk7r|dxx|dz zcc<t |Dcic] \}}||| c}}Scc}wcc}}w)a The key function that creates a randomized initial distribution that still sums to 1. Set as a dictionary of prob values so that it can still be passed to MutableProbDist and called with identical syntax to UniformProbDist r,)rrdr)rr enumerate)clsrrrandrowtotalxrps rrzRandomProbDist.unirandsg,,1#g,,?@q6==?@@G g& #DAqUGAJ #G  A: BK519 $K*3G*<=$!Q71: ==A>s B'B,ct|ds2td|jjDd|_|jS)N_maxc3*K|] \}}||f ywr1r-rtvrs rruz%RandomProbDist.max..sEv1QFEr,)hasattrrFrrrrs rrFzRandomProbDist.maxs:tV$E1B1B1DEEaHDIyyrc:|jj|dSr)rgetrs rrzRandomProbDist.probs{{vq))rc|jSr1rrs rrzRandomProbDist.samplesrrc2dt|jzS)Nz')r)rrs rrzRandomProbDist.__repr__s83t{{;KKKrN) rrrrr classmethodrrFrrrr-rrrrzs5 1>>* *Lrrc6eZdZdZd dZdZdZdZdZdZ y) DictionaryProbDistz A probability distribution whose probabilities are directly specified by a given dictionary. The given dictionary maps samples to probabilities. Nc||jni|_||_|rOt|dk(r t d|rt t |jj}|tkr9tjdt|z d}|D]}||j|<y|jjD]\}}|j|xx|zcc<yt|jj}|dk(r%dt|z }|D]}||j|<yd|z }|jjD]\}}|j|xx|zcc<yy)a Construct a new probability distribution from the given dictionary, which maps values to probabilities (or to log probabilities, if ``log`` is true). If ``normalize`` is true, then the probability values are scaled by a constant factor such that they sum to 1. If called without arguments, the resulting probability distribution assigns zero probability to all values. NrzOA DictionaryProbDist must have at least one sample before it can be normalized.rrV) r _prob_dict_logr)rDsum_logsr^rrrrrr) r prob_dictr normalize value_sumlogprr norm_factors rr zDictionaryProbDist.__init__sg/8.C)..*  9~" 5$T$//*@*@*B%CD %88C#i.$8!c)n,A&/-.*/#& /K $ 5 5 7:1*k9*:/ rc|jr"||jvrd|j|zSdS|jj|dS)NrVr)rrrrs rrzDictionaryProbDist.probsE 995;t5N101 UTU U??&&vq1 1rc|jr |jj|tS||jvrtS|j|dk(rtSt j |j|dS)NrrV)rrrrrrrs rrzDictionaryProbDist.logprobsa 99??&&vu5 5T__, (A- xx 7;;rct|ds2td|jjDd|_|jS)Nrc3*K|] \}}||f ywr1r-rs rruz)DictionaryProbDist.max..sIv1QFIrr,)rrFrrrrs rrFzDictionaryProbDist.maxs:tV$I1F1F1HII!LDIyyrc6|jjSr1)rrrs rrzDictionaryProbDist.sampless##%%rc2dt|jzS)Nz)r)rrs rrzDictionaryProbDist.__repr__s+c$//.BBBr)NFF) rrrrr rrrFrrr-rrrrs' (:T2 < &Crrc6eZdZdZd dZdZdZdZdZdZ y) MLEProbDista% The maximum likelihood estimate for the probability distribution of the experiment used to generate a frequency distribution. The "maximum likelihood estimate" approximates the probability of each sample as the frequency of that sample in the frequency distribution. Nc||_y)a) Use the maximum likelihood estimate to create a probability distribution for the experiment used to generate ``freqdist``. :type freqdist: FreqDist :param freqdist: The frequency distribution that the probability estimates should be based on. N _freqdistrfreqdistr4s rr zMLEProbDist.__init__s "rc|jSz Return the frequency distribution that this probability distribution is based on. :rtype: FreqDist rrs rrzMLEProbDist.freqdist~~rc8|jj|Sr1)rrBrs rrzMLEProbDist.probs~~""6**rc6|jjSr1rrFrs rrFzMLEProbDist.max~~!!##rc6|jjSr1rrrs rrzMLEProbDist.samples~~""$$rc<d|jjzS)\ :rtype: str :return: A string representation of this ``ProbDist``. z!rrrs rrzMLEProbDist.__repr__"s 3T^^5E5E5GGGrr1) rrrrr rrrFrrr-rrrrs& "+$%Hrrc@eZdZdZdZd dZdZdZdZdZ d Z d Z y) LidstoneProbDista8 The Lidstone estimate for the probability distribution of the experiment used to generate a frequency distribution. The "Lidstone estimate" is parameterized by a real number *gamma*, which typically ranges from 0 to 1. The Lidstone estimate approximates the probability of a sample with count *c* from an experiment with *N* outcomes and *B* bins as ``c+gamma)/(N+B*gamma)``. This is equivalent to adding *gamma* to the count for each bin, and taking the maximum likelihood estimate of the resulting frequency distribution. FNcF|dk(s|=|jdk(r*|jjdd}td|zdz|W||j krD|jjdd}td|zd|zzdzd |j zz||_t ||_|j j|_||j }||_ |j||zz|_ |jd k(rd|_d |_ yy) a Use the Lidstone estimate to create a probability distribution for the experiment used to generate ``freqdist``. :type freqdist: FreqDist :param freqdist: The frequency distribution that the probability estimates should be based on. :type gamma: float :param gamma: A real number used to parameterize the estimate. The Lidstone estimate is equivalent to adding *gamma* to the count for each bin, and taking the maximum likelihood estimate of the resulting frequency distribution. :type bins: int :param bins: The number of sample values that can be generated by the experiment that is described by the probability distribution. This value must be correctly set for the probabilities of the sample values to sum to one. If ``bins`` is not specified, it defaults to ``freqdist.B()``. rNizA %s probability distribution zmust have at least one bin.z) The number of bins in a %s distribution z&(%d) must be greater than or equal to z(the number of bins in the FreqDist used zto create it (%d).r;r,) rrrrDr*rfloat_gammar _bins_divisor)rrgammar4names rr zLidstoneProbDist.__init__9s,* AI4>**3B/D047:WW   4(**,#6>>**3B/Dr&rs rrzLidstoneProbDist.__repr__s 8$..:J:J:LLLrr1) rrrrrr rrrFrrrr-rrr(r(*s3 J0d1$ %#Mrr(ceZdZdZddZdZy)LaplaceProbDista The Laplace estimate for the probability distribution of the experiment used to generate a frequency distribution. The "Laplace estimate" approximates the probability of a sample with count *c* from an experiment with *N* outcomes and *B* bins as *(c+1)/(N+B)*. This is equivalent to adding one to the count for each bin, and taking the maximum likelihood estimate of the resulting frequency distribution. Nc4tj||d|y)a Use the Laplace estimate to create a probability distribution for the experiment used to generate ``freqdist``. :type freqdist: FreqDist :param freqdist: The frequency distribution that the probability estimates should be based on. :type bins: int :param bins: The number of sample values that can be generated by the experiment that is described by the probability distribution. This value must be correctly set for the probabilities of the sample values to sum to one. If ``bins`` is not specified, it defaults to ``freqdist.B()``. r,Nr(r rs rr zLaplaceProbDist.__init__s !!$!T:rc<d|jjzS)r%z%r&rs rrzLaplaceProbDist.__repr__s 79I9I9KKKrr1rrrrr rr-rrr;r;s;"Lrr;ceZdZdZddZdZy) ELEProbDista The expected likelihood estimate for the probability distribution of the experiment used to generate a frequency distribution. The "expected likelihood estimate" approximates the probability of a sample with count *c* from an experiment with *N* outcomes and *B* bins as *(c+0.5)/(N+B/2)*. This is equivalent to adding 0.5 to the count for each bin, and taking the maximum likelihood estimate of the resulting frequency distribution. Nc4tj||d|y)a Use the expected likelihood estimate to create a probability distribution for the experiment used to generate ``freqdist``. :type freqdist: FreqDist :param freqdist: The frequency distribution that the probability estimates should be based on. :type bins: int :param bins: The number of sample values that can be generated by the experiment that is described by the probability distribution. This value must be correctly set for the probabilities of the sample values to sum to one. If ``bins`` is not specified, it defaults to ``freqdist.B()``. ?Nr=rs rr zELEProbDist.__init__s !!$#tr&rs rrzELEProbDist.__repr__s 3T^^5E5E5GGGrr1r?r-rrrArAs="HrrAcReZdZdZdZddZdZdZdZdZ d Z d Z d Z d Z d Zy)HeldoutProbDistag The heldout estimate for the probability distribution of the experiment used to generate two frequency distributions. These two frequency distributions are called the "heldout frequency distribution" and the "base frequency distribution." The "heldout estimate" uses uses the "heldout frequency distribution" to predict the probability of each sample, given its frequency in the "base frequency distribution". In particular, the heldout estimate approximates the probability for a sample that occurs *r* times in the base distribution as the average frequency in the heldout distribution of all samples that occur *r* times in the base distribution. This average frequency is *Tr[r]/(Nr[r].N)*, where: - *Tr[r]* is the total count in the heldout distribution for all samples that occur *r* times in the base distribution. - *Nr[r]* is the number of samples that occur *r* times in the base distribution. - *N* is the number of outcomes recorded by the heldout frequency distribution. In order to increase the efficiency of the ``prob`` member function, *Tr[r]/(Nr[r].N)* is precomputed for each value of *r* when the ``HeldoutProbDist`` is created. :type _estimate: list(float) :ivar _estimate: A list mapping from *r*, the number of times that a sample occurs in the base distribution, to the probability estimate for that sample. ``_estimate[r]`` is calculated by finding the average frequency in the heldout distribution of all samples that occur *r* times in the base distribution. In particular, ``_estimate[r]`` = *Tr[r]/(Nr[r].N)*. :type _max_r: int :ivar _max_r: The maximum number of times that any sample occurs in the base distribution. ``_max_r`` is used to decide how large ``_estimate`` must be. FNc<||_||_||j|_|j }|j |}t |jdzDcgc]}|| }}|j}|j||||_ ycc}w)a Use the heldout estimate to create a probability distribution for the experiment used to generate ``base_fdist`` and ``heldout_fdist``. :type base_fdist: FreqDist :param base_fdist: The base frequency distribution. :type heldout_fdist: FreqDist :param heldout_fdist: The heldout frequency distribution. :type bins: int :param bins: The number of sample values that can be generated by the experiment that is described by the probability distribution. This value must be correctly set for the probabilities of the sample values to sum to one. If ``bins`` is not specified, it defaults to ``freqdist.B()``. r,N) _base_fdist_heldout_fdistrF_max_r _calculate_Trr2rdr_calculate_estimate _estimate) r base_fdist heldout_fdistr4Trr2r3r5rs rr zHeldoutProbDist.__init__s$&+!!12    !t$$T[[1_5 6!d1g 6 6 OO 11"b!< 7s" Bcdg|jdzz}|jD]+}|j|}||xx|j|z cc<-|S)z Return the list *Tr*, where *Tr[r]* is the total count in ``heldout_fdist`` for all samples that occur *r* times in ``base_fdist``. :rtype: list(float) r;r,)rJrIrH)rrPr=r3s rrKzHeldoutProbDist._calculate_Tr%s]UdkkAo &)) 1F  (A qET((0 0E 1 rcg}t|jdzD]9}||dk(r|jd|j|||||zz ;|S)a~ Return the list *estimate*, where *estimate[r]* is the probability estimate for any sample that occurs *r* times in the base frequency distribution. In particular, *estimate[r]* is *Tr[r]/(N[r].N)*. In the special case that *N[r]=0*, *estimate[r]* will never be used; so we define *estimate[r]=None* for those cases. :rtype: list(float) :type Tr: list(float) :param Tr: the list *Tr*, where *Tr[r]* is the total count in the heldout distribution for all samples that occur *r* times in base distribution. :type Nr: list(float) :param Nr: The list *Nr*, where *Nr[r]* is the number of samples that occur *r* times in the base distribution. :type N: int :param N: The total number of outcomes recorded by the heldout frequency distribution. r,rN)rdrJr)rrPr5restimater3s rrLz#HeldoutProbDist._calculate_estimate3s`(t{{Q' 5A!uz%1A 34  5 rc|jS)z Return the base frequency distribution that this probability distribution is based on. :rtype: FreqDist )rHrs rrNzHeldoutProbDist.base_fdistOsrc|jS)z Return the heldout frequency distribution that this probability distribution is based on. :rtype: FreqDist )rIrs rrOzHeldoutProbDist.heldout_fdistXs"""rc6|jjSr1)rHrrs rrzHeldoutProbDist.samplesas$$&&rc>|j|}|j|Sr1)rHrM)rr=r3s rrzHeldoutProbDist.probds!   V $~~a  rc6|jjSr1)rHrFrs rrFzHeldoutProbDist.maxis##%%rctr1NotImplementedErrorrs rrzHeldoutProbDist.discounto !##rctd}||jj|jjfzS)r%z6)rHrrI)rrps rrzHeldoutProbDist.__repr__rs8 ED$$&&($*=*=*?*?*ABBBrr1)rrrrrr rKrLrNrOrrrFrrr-rrrFrFsC'RJ =D 8 #'! & $CrrFc8eZdZdZdZdZdZdZdZdZ dZ y ) CrossValidationProbDistaA The cross-validation estimate for the probability distribution of the experiment used to generate a set of frequency distribution. The "cross-validation estimate" for the probability of a sample is found by averaging the held-out estimates for the sample in each pair of frequency distributions. Fc||_g|_|D]6}|D]/}||ust|||}|jj|18y)a Use the cross-validation estimate to create a probability distribution for the experiment used to generate ``freqdists``. :type freqdists: list(FreqDist) :param freqdists: A list of the frequency distributions generated by the experiment. :type bins: int :param bins: The number of sample values that can be generated by the experiment that is described by the probability distribution. This value must be correctly set for the probabilities of the sample values to sum to one. If ``bins`` is not specified, it defaults to ``freqdist.B()``. N) _freqdists_heldout_probdistsrFr)r freqdistsr4fdist1fdist2probdists rr z CrossValidationProbDist.__init__s] $#% =F# ='.vvtDH++228< = =rc|jS)z Return the list of frequency distributions that this ``ProbDist`` is based on. :rtype: list(FreqDist) )rars rrcz!CrossValidationProbDist.freqdistss rcNttd|jDgS)Nc32K|]}t|ywr1)r^)rtfds rruz2CrossValidationProbDist.samples..s;RR;s)rrrars rrzCrossValidationProbDist.sampless3;4??;R@AArcd}|jD]}||j|z }|t|jz S)Nr;)rbrr))rr=rheldout_probdists rrzCrossValidationProbDist.probsK $ 7 7 2  $))&1 1D 2c$11222rctr1rZrs rrz CrossValidationProbDist.discountr\rc2dt|jzS)r9z!)r)rars rrz CrossValidationProbDist.__repr__s 3S5IIIrN) rrrrrr rcrrrrr-rrr_r_{s.J=6B3$Jrr_c<eZdZdZd dZdZdZdZdZdZ d Z y) WittenBellProbDista The Witten-Bell estimate of a probability distribution. This distribution allocates uniform probability mass to as yet unseen events by using the number of events that have only been seen once. The probability mass reserved for unseen events is equal to *T / (N + T)* where *T* is the number of observed event types and *N* is the total number of observed events. This equates to the maximum likelihood estimate of a new type event occurring. The remaining probability mass is discounted such that all probability estimates sum to one, yielding: - *p = T / Z (N + T)*, if count = 0 - *p = c / (N + T)*, otherwise Nc|+||jk\sJd|jz||j}||_|jj|_||jjz |_|jj |_|j dk(rd|jz |_y|j|j|j |jzzz |_y)a) Creates a distribution of Witten-Bell probability estimates. This distribution allocates uniform probability mass to as yet unseen events by using the number of events that have only been seen once. The probability mass reserved for unseen events is equal to *T / (N + T)* where *T* is the number of observed event types and *N* is the total number of observed events. This equates to the maximum likelihood estimate of a new type event occurring. The remaining probability mass is discounted such that all probability estimates sum to one, yielding: - *p = T / Z (N + T)*, if count = 0 - *p = c / (N + T)*, otherwise The parameters *T* and *N* are taken from the ``freqdist`` parameter (the ``B()`` and ``N()`` values). The normalizing factor *Z* is calculated using these values along with the ``bins`` parameter. :param freqdist: The frequency counts upon which to base the estimation. :type freqdist: FreqDist :param bins: The number of possible event types. This must be at least as large as the number of bins in the ``freqdist``. If None, then it's assumed to be equal to that of the ``freqdist`` :type bins: int Nz4bins parameter must not be less than %d=freqdist.B()rr)r*r_T_Zrr _P0rs rr zWittenBellProbDist.__init__s6|txzz|3 BXZZ\ Q 3 <::"?@DHrcz|j|}|dk7r||j|jzz S|jSr)rr rrrtr2s rrzWittenBellProbDist.probs7 NN6 "*+q&qDGGdgg%&>dhh>rc6|jjSr1rrs rrFzWittenBellProbDist.maxr rc6|jjSr1r"rs rrzWittenBellProbDist.samplesr#rc|jSr1rrs rrzWittenBellProbDist.freqdist ~~rctr1rZrs rrzWittenBellProbDist.discount r\rc<d|jjzS)r9z(r&rs rrzWittenBellProbDist.__repr__ s :DNN 0 )rzipsortedr)rnonzeros rr8zSimpleGoodTuringProbDist._r_Nrs4%%'r6MF7==?+,,rc|r|syg}tt|D]T}|dkDr||dz nd}|t|dz k(r d||z|z n||dz}d||z||z z }|j|V|Dcgc]}tj|}}|Dcgc]}tj|} }dx} } t |t|z } t | t| z } t || D]\}}| || z || z zz } | || z dzz } | dk7r| | z nd|_|jdk\rtjd| |j| zz |_ ycc}wcc}w) z Use simple linear regression to tune parameters self._slope and self._intercept in the log-log space based on count and Nr(count) (Work in log space to avoid floating point underflow.) Nrr,rVg@r;rzSimpleGoodTuring did not find a proper best fit line for smoothing probabilities of occurrences. The probability estimates are likely to be unreliable.) rdr)rrrrr_sloperr _intercept)rr3rzrjrkzr_log_rlog_zrxy_covx_varx_meany_meanrys rrz&SimpleGoodTuringProbDist.find_best_fits  s1v AE!a%qA !SVaZAaD1 Qq1uXA1+Q'C IIcN   '((!((')*!$((1+**Uc%j(Vs6{*v& 'DAq q6za&j1 1F a&jQ& &E '). fun ;;"  MM  !4;;#77#)*s 7E#E(c t|D]\}}t||dzk(s||dz|dzk7r ||_y|j}|dz||dzz||z }|dz||dzz||z }t j |j |||||dz}t||z d|zks||_yy)zl Calculate the r frontier where we must switch from Nr to Sr when estimating E[Nr]. r,g\(\?N)rr) _switch_at smoothedNrrsqrt _varianceabs) rr3rrr_Sr smooth_r_starunsmooth_r_starstds rrz SimpleGoodTuringProbDist._switchs q\ EAr1vQ!AE(b1f"4"$B!Vr"q&z1BrF:M!AvAE2RU:O))DNN2r!ubQi@AC?]23tczA"$ rcxt|}t|}t|}|dzdz||dzz zd||z zzS)NrrV)r*)rr3rnr_1s rrz"SimpleGoodTuringProbDist._variancesE !H 2YT{CA~A.#r /BBrcd}t||D]\}}|||j|zz }|rd|jdz |z |_yy)ay It is necessary to renormalize all the probability estimates to ensure a proper probability distribution results. This can be done by keeping the estimate of the probability mass for unseen items as N(1)/N and renormalizing all the estimates for previously seen items (as Gale and Sampson (1995) propose). (See M&S P.213, 1999) r;r,rN)r _prob_measure _renormal)rr3rprob_covrnr_s rrz%SimpleGoodTuringProbDist._renormalizes`1bz 5GB d0044 4H 5 $"4"4Q"778CDN rctj|j|jtj|zzS)z Return the number of samples with count r. :param r: The amount of frequency. :type r: int :rtype: float )rexprrr)rr3s rrz#SimpleGoodTuringProbDist.smoothedNrs-xx$++ *CCDDrc|j|}|j|}|dk(rW|j|jjk(rd}|S||j|jjz z }|S||jz}|S)z Return the sample's probability. :param sample: sample of the event :type sample: str :rtype: float rr;)rrr,r*r)rr=r9rs rrzSimpleGoodTuringProbDist.probsv&   u % A:zzT^^--// dnn&6&6&889DNN"Arc$|dk(r|jjdk(ry|dk(rS|jjdk7r6|jjd|jjz S|j|kDr:|jj|dz}|jj|}n%|j |dz}|j |}|dz|z|z }||jjz S)Nrrr,)rrr5rr)rr9Er_1Err_stars rrz&SimpleGoodTuringProbDist._prob_measures A:$..**,1 aZDNN,,.!3>>$$Q'$..*:*:*<< < ??U ">>$$UQY/D""5)B??519-D'B!)t#b(((***rcd}tdt|jD]3}||j||j|z|jz z }5t d|y)Nr;rzProbability Sum:)rdr)_Nrrrr)rprob_sumrs rcheckzSimpleGoodTuringProbDist.checks]q#dhh-( MA  d&8&8&;;dnnL LH M  (+rcZ|jd|jjz S)z This function returns the total mass of probability transfers from the seen samples to the unseen samples. r,)rrrrs rrz!SimpleGoodTuringProbDist.discounts% q!DNN$4$4$666rc6|jjSr1rrs rrFzSimpleGoodTuringProbDist.maxr rc6|jjSr1r"rs rrz SimpleGoodTuringProbDist.samples r#rc|jSr1rrs rrz!SimpleGoodTuringProbDist.freqdist#ryrc<d|jjzS)r9z.r&rs rrz!SimpleGoodTuringProbDist.__repr__&s @$..BRBRBTTTrr1)rrrrrr rr8rrrrrrrrrrFrrrr-rrr}r}Psc&J!, -'8R(C DE &+ ,7$%Urr}c8eZdZdZd dZdZdZdZdZd dZ y) MutableProbDistz An mutable probdist where the probabilities may be easily modified. This simply copies an existing probdist, storing the probability values in a mutable dictionary and providing an update method. c||_tt|Dcic]}||| c}|_t jddgt|z|_tt|D]G}|r"|j |||j |<'|j|||j |<I||_ycc}w)a Creates the mutable probdist based on the given prob_dist and using the list of samples given. These values are stored as log probabilities if the store_logs flag is set. :param prob_dist: the distribution from which to garner the probabilities :type prob_dist: ProbDist :param samples: the complete set of samples :type samples: sequence of any :param store_logs: whether to store the probabilities as logarithms :type store_logs: bool dr;N) rrdr) _sample_dictarray_datarr_logs)r prob_distr store_logsrs rr zMutableProbDist.__init__6s  49#g,4GHqWQZ]H[[se,s7|; s7|$ ;A ) 1 1'!* = 1 )wqz : 1  ;   Is Cc\td|jjDdS)Nc3*K|] \}}||f ywr1r-rs rruz&MutableProbDist.max..PsBfq!Aq6Brr,)rFrrrs rrFzMutableProbDist.maxNs'B(9(9(?(?(ABB1EErc|jSr1rrs rrzMutableProbDist.samplesRs }}rc|jj|}|y|jrd|j|zS|j|S)Nr;rV)rrrrrr=rs rrzMutableProbDist.probVsF    ! !& ) 9'+zzqTZZ]#Dtzz!}Drc|jj|}| tdS|jr|j|St j |j|dS)Nz-infrV)rrr*rrrrrs rrzMutableProbDist.logprob]sS    ! !& ) 9= $ tzz!}JA0JJrc|jj|}|J|jr(|r|ntj|d|j |<y|rd|zn||j |<y)a< Update the probability for the given sample. This may cause the object to stop being the valid probability distribution - the user must ensure that they update the sample probabilities such that all samples have probabilities between 0 and 1 and that all probabilities sum to one. :param sample: the sample for which to update the probability :type sample: any :param prob: the new probability :type prob: float :param log: is the probability already logged :type log: bool NrV)rrrrrr)rr=rrrs rr"zMutableProbDist.updateds\    ! !& )}} ::$'DTXXdA->DJJqM+.A$KDDJJqMrN)T) rrrrr rFrrrr"r-rrrr/s(  0FEK9rrc<eZdZdZd dZdZdZdZdZdZ d Z y) KneserNeyProbDista~ Kneser-Ney estimate of a probability distribution. This is a version of back-off that counts how likely an n-gram is provided the n-1-gram had been seen in training. Extends the ProbDistI interface, requires a trigram FreqDist instance to train on. Optionally, a different from default discount value can be specified. The default discount is set to 0.75. Nc|s|j|_n||_||_i|_t t |_||_t t|_ t t|_ t t|_ |D]n\}}}|j ||fxx||||fz cc<|j||fxxdz cc<|j|xxdz cc<|j||fxxdz cc<py)a :param freqdist: The trigram frequency distribution upon which to base the estimation :type freqdist: FreqDist :param bins: Included for compatibility with nltk.tag.hmm :type bins: int or float :param discount: The discount applied when retrieving counts of trigrams :type discount: float (preferred, but can be set to int) r,N) r*r,_D_cacherr7_bigrams _trigramsr*_wordtypes_after_trigrams_contain_wordtypes_before)rrr4rw0w1w2s rr zKneserNeyProbDist.__init__s!DJDJ $C( !!,E 2!,U!3!,U!3" 2JBB MM2r( #xR '= = #  ! !2r( +q 0 +  " "2 &! + &  " "B8 , 1 ,  2rc<t|dk7r tdt|}|\}}}||jvr|j|S||jvr3|j||j z |j ||fz }n||f|j vrr||f|jvrb|j||f}|j||f}||j z|j ||fz }||j||z z } || z}nd}||j|<|S)Nz$Expected an iterable with 3 members.r;) r)rDtuplerrrrrrr) rtrigramrrrraftrbfr leftover_probbetas rrzKneserNeyProbDist.probs7 w<1 CD D. B dkk !;;w' '$..(w/$--/AT]]HF bT]]*Bx4;Q;Q/Q,,b"X6,,b"X6"& !74=="b;R R d44R84?@$t+#'DKK Krc|jS)zq Return the value by which counts are discounted. By default set to 0.75. :rtype: float rrs rrzKneserNeyProbDist.discounts wwrc||_y)z Set the value by which counts are discounted to the value of discount. :param discount: the new value to discount counts by :type discount: float (preferred, but int possible) :rtype: None Nr)rrs r set_discountzKneserNeyProbDist.set_discounts rc6|jjSr1)rrrs rrzKneserNeyProbDist.samplesr#rc6|jjSr1)rrFrs rrFzKneserNeyProbDist.maxr rc>d|jjdS)zV Return a string representation of this ProbDist :rtype: str z.>.@-AKKr)Ng?) rrrrr rrrrrFrr-rrrrs-!2F"H%$Lrrcttrtts tdtfdDS)Nzexpected a ProbDist.c3K|];}j|tjj|dz=ywrVN)rrr)rtrp actual_pdist test_pdists rruz!log_likelihood..s:CD !txx (:A>>sAA)rrrDr)rrs``rlog_likelihoodrs< j) ,J|Y4W/00 HT rc\fdjD}td|D S)Nc3@K|]}j|ywr1)r)rtrppdists rruzentropy.. s 4qUZZ] 4sc3NK|]}|tj|dzywr)rr)rtrs rruzentropy..!s2qDHHQN"2s#%)rr)rprobss` rentropyrs' 4EMMO 4E 2E2 2 22rceZdZdZddZdZdZdZddddddd d Zd Z d Z d Z dZ dZ dZdZdZdZdZeZdZy)ConditionalFreqDista A collection of frequency distributions for a single experiment run under different conditions. Conditional frequency distributions are used to record the number of times each sample occurred, given the condition under which the experiment was run. For example, a conditional frequency distribution could be used to record the frequency of each word (type) in a document, given its length. Formally, a conditional frequency distribution can be defined as a function that maps from each condition to the FreqDist for the experiment under that condition. Conditional frequency distributions are typically constructed by repeatedly running an experiment under a variety of conditions, and incrementing the sample outcome counts for the appropriate conditions. For example, the following code will produce a conditional frequency distribution that encodes how often each word type occurs, given the length of that word type: >>> from nltk.probability import ConditionalFreqDist >>> from nltk.tokenize import word_tokenize >>> sent = "the the the dog dog some other words that we do not care about" >>> cfdist = ConditionalFreqDist() >>> for word in word_tokenize(sent): ... condition = len(word) ... cfdist[condition][word] += 1 An equivalent way to do this is with the initializer: >>> cfdist = ConditionalFreqDist((len(word), word) for word in word_tokenize(sent)) The frequency distribution for each condition is accessed using the indexing operator: >>> cfdist[3] FreqDist({'the': 3, 'dog': 2, 'not': 1}) >>> cfdist[3].freq('the') 0.5 >>> cfdist[3]['dog'] 2 When the indexing operator is used to access the frequency distribution for a condition that has not been accessed before, ``ConditionalFreqDist`` creates a new empty FreqDist for that condition. Ncrtj|t|r|D]\}}|||xxdz cc<yy)aZ Construct a new empty conditional frequency distribution. In particular, the count for every sample, under every condition, is zero. :param cond_samples: The samples to initialize the conditional frequency distribution with :type cond_samples: Sequence of (condition, sample) tuples r,N)rr r )r cond_samplescondr=s rr zConditionalFreqDist.__init__YsC T8,  , ( fT 6"a'" ( rcXfdjD}jddd|fS)Nc3,K|] }||f ywr1r-)rtrrs rruz1ConditionalFreqDist.__reduce__..jsE4T4:&Esr-) conditionsr)rkv_pairss` r __reduce__zConditionalFreqDist.__reduce__is)E4??3DED$99rc4t|jS)aT Return a list of the conditions that have been accessed for this ``ConditionalFreqDist``. Use the indexing operator to access the frequency distribution for a given condition. Note that the frequency distributions for some conditions may contain zero sample outcomes. :rtype: list r^rrs rrzConditionalFreqDist.conditionsmsDIIK  rcBtd|jDS)z Return the total number of sample outcomes that have been recorded by this ``ConditionalFreqDist``. :rtype: int c3<K|]}|jywr1r@)rtfdists rruz(ConditionalFreqDist.N..s857798s)rrrs rrzConditionalFreqDist.Nys8$++-888rrGF)rrHrIrJrrKc> ddlm} |s|j }n|D cgc] } | |vs|  }} |s%t |D chc]} || D]} | c} } }d|vrd|d<| j } |rbg}|D]p}|rt||j|}n|Dcgc] }||| }}|r&|Dcgc]}|||jz dz}}|j|r|rd}d}nd }d }|r|d z }n|d z }d}|D]%}|||d <|dz }| j|g|i|'| j|| jdd| jtt!|| j#|Dcgc] }t%|c}d|r| j'|| j)d| j+||r| j-| S#t$r} td| d} ~ wwxYwcc} wcc} } wcc}wcc}wcc}w)aK Plot the given samples from the conditional frequency distribution. For a cumulative plot, specify cumulative=True. Additional ``*args`` and ``**kwargs`` are passed to matplotlib's plot function. (Requires Matplotlib to be installed.) :param samples: The samples to plot :type samples: list :param title: The title for the graph :type title: str :param cumulative: Whether the plot is cumulative. (default = False) :type cumulative: bool :param percents: Whether the plot uses percents instead of counts. (default = False) :type percents: bool :param conditions: The conditions to plot (default is all) :type conditions: list :param show: Whether to show the plot, or only return the ax. :type show: bool rNrMrUrVrOrNz lower rightrGz upper rightrPrQlabelr,)locTrRrSrWrXrZ)r[r\r]rDrrr_r^r>rrrblegendr`rcrdr)rerfrargrhrK)rrrHrIrJrrKr#r$rirjr3rrorl conditionrBr=rnrm legend_locrrps rrbzConditionalFreqDist.plotsD<  +*J%/=19!=J=EAT!WEaEaEFG f $"#F;  WWY E' # Y G G PQDBIJDOF3JDJCGHaAY 1 1 33c9HDH T" #&* * *$("A /",Q-wQ.t.v. / II*I % GGDG ) MM%G - .   81A82  F U# MM) $ MM& !  HHJ u .  >EKI0 9s8G( HHH H4 HH( H1 G==Hc t|dd}t|dt|j}t|dt|Dchc]}||vs||D]}|c}}}td|D}t } |D]]}|r!t ||j || |<n|D cgc] } |||  c} | |<t|td| |D}_td|D} td| zd |D]} td || fzd t|D]:}td | |fzd | |D]} td || fzd t<y cc}}wcc} w) a~ Tabulate the given samples from the conditional frequency distribution. :param samples: The samples to plot :type samples: list :param conditions: The conditions to plot (default is all) :type conditions: list :param cumulative: A flag to specify whether the freqs are cumulative (default = False) :type title: bool rIFrrc38K|]}td|zyw%sNr(rss rruz/ConditionalFreqDist.tabulate..s3aCqM3ryc38K|]}td|zywrwr(rxs rruz/ConditionalFreqDist.tabulate..s"CQ3tax="Cryc38K|]}td|zywr r()rtr3s rruz/ConditionalFreqDist.tabulate..s?qS]?ryr{r|rzr~N)rrrrFdictr^r>r)rr#r$rIrr3rrrrlr=condition_sizerprns rrzConditionalFreqDist.tabulates  e<  fT__=N6OP    zH!Q$YQH1AHAH I  3733 EAQ ? ? HIa:ABDGFOBas"C%("CCDE  E?J?? cN", /A %5!*$# . /  A %>1--3 71X 3euaj(c2 3 G  #ICs E* E*/E0ct|tstS|j}|j D]}||xx||z cc<|S)z; Add counts from two ConditionalFreqDists. rrNotImplementedrrrrresultrs rrzConditionalFreqDist.__add__O%!45! !$$& (D 4LE$K 'L ( rct|tstS|j}|j D]}||xx||zcc<||r||=|S)zM Subtract count, but keep only results with positive counts. rrs rrzConditionalFreqDist.__sub__s_%!45! !$$& !D 4LE$K 'L$<4L ! rct|tstS|j}|j D]}||xx||zcc<|S)zP Union is the maximum of value in either of the input counters. rrs rrzConditionalFreqDist.__or__ rrct|tstSt}|jD]}||||z}|s|||<|S)zF Intersection is the minimum of corresponding counts. )rrrr)rrrr newfreqdists rrzConditionalFreqDist.__and__+sX%!45! !$&OO% +Dt*uT{2K*t  + rctts tdtj j j xr#t fdj DS)Nrc34K|]}||kywr1r-)rtr3rrs rruz-ConditionalFreqDist.__le__..<s%K $%DGuQx K r)rrrrrrrrs``rrzConditionalFreqDist.__le__9se%!45 #D$ 64??$%..u/?/?/AB sK )-):K H  rcTt|ts td||||kxr||k7S)N<rrrrs rrzConditionalFreqDist.__lt__@s,%!45 #Cu 5u}..rcFt|ts td||||kS)Nrrrs rrzConditionalFreqDist.__ge__Es#%!45 #D$ 6}rcFt|ts td||||kS)N>rrs rrzConditionalFreqDist.__gt__Js#%!45 #Cu 5t|rcddlm}||S)Nr)deepcopy)rr")rr"s rr"zConditionalFreqDist.deepcopyOs!~rcdt|zS)zf Return a string representation of this ``ConditionalFreqDist``. :rtype: str z(r(rs rrzConditionalFreqDist.__repr__Vs :CIEErr1)rrrrr rrrrbrrrrrrrrrr"rrr-rrrr)sw-^( : !9 Zx&T     /    DFrrc,eZdZdZedZdZdZy)ConditionalProbDistIao A collection of probability distributions for a single experiment run under different conditions. Conditional probability distributions are used to estimate the likelihood of each sample, given the condition under which the experiment was run. For example, a conditional probability distribution could be used to estimate the probability of each word type in a document, given the length of the word type. Formally, a conditional probability distribution can be defined as a function that maps from each condition to the ``ProbDist`` for the experiment under that condition. cy)zY Classes inheriting from ConditionalProbDistI should implement __init__. Nr-rs rr zConditionalProbDistI.__init__mrrc4t|jS)z Return a list of the conditions that are represented by this ``ConditionalProbDist``. Use the indexing operator to access the probability distribution for a given condition. :rtype: list rrs rrzConditionalProbDistI.conditionsssDIIK  rcHdt|jt|fzS)zf Return a string representation of this ``ConditionalProbDist``. :rtype: str z<%s with %d conditions>)typerr)rs rrzConditionalProbDistI.__repr__}s" )DJ,?,?T+KKKrN)rrrrrr rrr-rrr%r%_s&   !Lrr%ceZdZdZdZdZy)ConditionalProbDista A conditional probability distribution modeling the experiments that were used to generate a conditional frequency distribution. A ConditionalProbDist is constructed from a ``ConditionalFreqDist`` and a ``ProbDist`` factory: - The ``ConditionalFreqDist`` specifies the frequency distribution for each condition. - The ``ProbDist`` factory is a function that takes a condition's frequency distribution, and returns its probability distribution. A ``ProbDist`` class's name (such as ``MLEProbDist`` or ``HeldoutProbDist``) can be used to specify that class's constructor. The first argument to the ``ProbDist`` factory is the frequency distribution that it should model; and the remaining arguments are specified by the ``factory_args`` parameter to the ``ConditionalProbDist`` constructor. For example, the following code constructs a ``ConditionalProbDist``, where the probability distribution for each condition is an ``ELEProbDist`` with 10 bins: >>> from nltk.corpus import brown >>> from nltk.probability import ConditionalFreqDist >>> from nltk.probability import ConditionalProbDist, ELEProbDist >>> cfdist = ConditionalFreqDist(brown.tagged_words()[:5000]) >>> cpdist = ConditionalProbDist(cfdist, ELEProbDist, 10) >>> cpdist['passed'].max() 'VBD' >>> cpdist['passed'].prob('VBD') #doctest: +ELLIPSIS 0.423... c`||_||_||_|D]}|||g|i|||<y)a Construct a new conditional probability distribution, based on the given conditional frequency distribution and ``ProbDist`` factory. :type cfdist: ConditionalFreqDist :param cfdist: The ``ConditionalFreqDist`` specifying the frequency distribution for each condition. :type probdist_factory: class or function :param probdist_factory: The function or class that maps a condition's frequency distribution to its probability distribution. The function is called with the frequency distribution as its first argument, ``factory_args`` as its remaining arguments, and ``factory_kw_args`` as keyword arguments. :type factory_args: (any) :param factory_args: Extra arguments for ``probdist_factory``. These arguments are usually used to specify extra properties for the probability distributions of individual conditions, such as the number of bins they contain. :type factory_kw_args: (any) :param factory_kw_args: Extra keyword arguments for ``probdist_factory``. N)_probdist_factory _factory_args_factory_kw_args)rcfdistprobdist_factory factory_argsfactory_kw_argsrs rr zConditionalProbDist.__init__sQ0"2) / I.y!$04CDO rcv|jtg|ji|j||<||Sr1)r-r r.r/rrs r __missing__zConditionalProbDist.__missing__sE*D** J ++ /3/D/D S CyrNrrrrr r6r-rrr+r+sBBrr+ceZdZdZdZdZy)DictionaryConditionalProbDistz An alternative ConditionalProbDist that simply wraps a dictionary of ProbDists rather than creating these from FreqDists. c&|j|y)z :param probdist_dict: a dictionary containing the probdists indexed by the conditions :type probdist_dict: dict any -> probdist N)r")r probdist_dicts rr z&DictionaryConditionalProbDist.__init__s M"rc&t||<||Sr1)rr5s rr6z)DictionaryConditionalProbDist.__missing__s&(S CyrNr7r-rrr9r9s #rr9gKH9rVc||tzkr|S||tzkr|St||}|tjd||z zd||z zzdzS)a Given two numbers ``logx`` = *log(x)* and ``logy`` = *log(y)*, return *log(x+y)*. Conceptually, this is the same as returning ``log(2**(logx)+2**(logy))``, but the actual implementation avoids overflow errors that could result from direct computation. rV)_ADD_LOGS_MAX_DIFFminrr)logxlogybases radd_logsrCsb d'''  d''' tT?D $((1-dTk0BBAF FFrcXt|dk7rtt|dd|dStS)Nrr,)r)rrCr)logss rrrs*25d)q.6(DHd1g .KeKrc.eZdZdZdZdZdZdZdZy)ProbabilisticMixIna A mix-in class to associate probabilities with other classes (trees, rules, etc.). To use the ``ProbabilisticMixIn`` class, define a new class that derives from an existing class and from ProbabilisticMixIn. You will need to define a new constructor for the new class, which explicitly calls the constructors of both its parent classes. For example: >>> from nltk.probability import ProbabilisticMixIn >>> class A: ... def __init__(self, x, y): self.data = (x,y) ... >>> class ProbabilisticA(A, ProbabilisticMixIn): ... def __init__(self, x, y, **prob_kwarg): ... A.__init__(self, x, y) ... ProbabilisticMixIn.__init__(self, **prob_kwarg) See the documentation for the ProbabilisticMixIn ``constructor<__init__>`` for information about the arguments it expects. You should generally also redefine the string representation methods, the comparison methods, and the hashing method. c d|vr)d|vr tdtj||dyd|vrtj||dydx|_|_y)a Initialize this object's probability. This initializer should be called by subclass constructors. ``prob`` should generally be the first argument for those constructors. :param prob: The probability associated with the object. :type prob: float :param logprob: The log of the probability associated with the object. :type logprob: float rrz.Must specify either prob or logprob (not both)N) TypeErrorrGset_prob set_logprob_ProbabilisticMixIn__prob_ProbabilisticMixIn__logprob)rr$s rr zProbabilisticMixIn.__init__ s_ V F" STT"++D&.A &  * *4 1B C+/ /DK$.rc ||_d|_y)z Set the probability associated with this object to ``prob``. :param prob: The new probability :type prob: float NrLrMrrs rrJzProbabilisticMixIn.set_prob3 s rc ||_d|_y)z Set the log probability associated with this object to ``logprob``. I.e., set the probability associated with this object to ``2**(logprob)``. :param logprob: The new log probability :type logprob: float N)rMrL)rrs rrKzProbabilisticMixIn.set_logprob= s! rct|j!|jyd|jz|_|jS)z\ Return the probability associated with this object. :rtype: float NrVrOrs rrzProbabilisticMixIn.probI s5 ;; ~~%/DK{{rc|j2|jytj|jd|_|jS)z Return ``log(p)``, where ``p`` is the probability associated with this object. :rtype: float NrV)rMrLrrrs rrzProbabilisticMixIn.logprobU s; >> !{{"!XXdkk15DN~~rN) rrrrr rJrKrrr-rrrGrG s 20,   rrGceZdZdZdZy)ImmutableProbabilisticMixIncFtd|jjzNz%s is immutablerDrrrPs rrJz$ImmutableProbabilisticMixIn.set_probd *T^^-D-DDEErcFtd|jjzrWrXrPs rrKz'ImmutableProbabilisticMixIn.set_logprobg rYrN)rrrrJrKr-rrrUrUc sFFrrUc&||vr ||}||=|S|}|Sr1r-)r$rdefaultargs rrrn s, f}Sk 3K J Jrct}t|D]E}tjdd|zdztjd|dzz}||xxdz cc<G|S)z Create a new frequency distribution, with random samples. The samples are numbers from 1 to ``numsamples``, and are generated by summing two numbers, each of which has a uniform distribution. r,rVr)r rdrrandint) numsamples numoutcomesrrrs r_create_rand_fdistrb| sg JE ;  NN1q:~!3 4v~~ zQ8   aA   Lrct}tdd|zdzdzD])}td|dzdzD]}|||zxxdz cc<+t|S)zp Return the true probability distribution for the experiment ``_create_rand_fdist(numsamples, x)``. r,rVr)r rdr)r`rrrs r_create_sum_pdistrd sm JE 1q:~!+a/ 0q*/A-. A !a%LA L  u rc t||}t||}t||}t|t|d|t|||t|||t |||g|t |t |dt |g}g}td|dzD]M}|jt||j|g|Dcgc]}|j|c}zOtd|||fztdt|dzzddt|dz zzd z} t| td |d d Dztd t|dzzddt|dz zzdz} |D]} t| | ztt|} | dd D cgc] } t!| } } td t|dzzddt|zzdz} t| t| ztdt|dzztd|zdkr*td|ztd|ztd|zttd|D]Wt#fdtdD} tdj%j&j(d dd| zd dYty cc}wcc} w)aK A demonstration of frequency distributions and probability distributions. This demonstration creates three frequency distributions with, and uses them to sample a random process with ``numsamples`` samples. Each frequency distribution is sampled ``numoutcomes`` times. These three frequency distributions are then used to build six probability distributions. Finally, the probability estimates of these distributions are compared to the actual probability of each sample. :type numsamples: int :param numsamples: The number of samples to use in each demo frequency distributions. :type numoutcomes: int :param numoutcomes: The total number of outcomes for each demo frequency distribution. These outcomes are divided into ``numsamples`` bins. :rtype: None rCr,z=%d samples (1-%d); %d outcomes were sampled for each FreqDistz =========rVz FreqDist z%8s z | Actualc38K|]}t|ddyw)r, N)repr)rtrs rruzdemo.. sFDK!,FryNrz ---------z %3d %8.6f z%8.6f z| %8.6fzTotal r Fz fdist1: %sz fdist2: %sz fdist3: %sz Generating:c3>K|]}jywr1)r)rtrrs rruzdemo.. s?a)?sz {:>20} {}7)rbrr(rFr_r}rdrdrrrBrrr)r^rrr rrr)r`rardrefdist3pdistsvalsrAr FORMATSTRrzvalssumsrs ` rdemorv s, K 8F  K 8F  K 8F Fj1 3 3 8*E ( +*% F D 1j1n %V E1fkk!n-F0S5A0SSTUV G z; / 0 'S[1_ %&!Fc&kAo$>>LI )eF&"+FF FG 'S[1_ %&S[1_!== II i#o d E %ab *CH *D * 'S[1_ %&8s6{33i?I )eDk !" 'S[1_ %& 4&=B nv%& nv%& nv%& G -V?5;?? k  !9!9#2!>sPR@STUV GE1T" +s =K%Kc Fddlm}|jjd}t |}t |}t djddddt|jd d D}|D]%}t d ||||j|fz'y) Nr)corpuszausten-emma.txtz{:>18} {:>8} {:>14}word frequencySimpleGoodTuringc3&K|] \}}| ywr1r-)rtrvalues rruzgt_demo.. sUsc |dS)Nr,r-)r.s rrzgt_demo.. s $q'rT)rreversez%18s %8d %14e) nltkrx gutenbergwordsr r}rrrrr)rx emma_wordsrjsgtfd_keys_sortedrs rgt_demor s!!''(9:J * B "2 &C ' ' =O PQ$RXXZ5ISWXN@ #r#w !>>?@r__main__rrm)rr+r%r_r9rrAr r}rFrUr;r(rrrrrGrrprCrrr)rei)4rrrrrabcrr collectionsrr functoolsrnltk.internalsrr*rr rrrrrr(r;rArFr_rpr}rrrrrr r%r+r9rr>rCrrGrUrrbrdrvrr__all__r-rrrs2 ',2 hlwlh d3'd3N#Ji#JL1LY1LhKCKC\+H)+H\aMyaMH!L&!LH"H""HJaCiaCHCJiCJLQOQO^\Uy\U~I9iI9`oL oLn3sF+sFl $L47$LNG.GT$80TXXeQ' GL]]@F"4F  K \ @ zBKDM I r