ó
    ´OÂf¯î  ã                   óÜ  • S r  SSKrSSKrSSKrSSKJr  SSKJr  SSK	J
r
JrJr  SSKJrJrJr  SSKJrJrJr  SSKJr  SS	KJr  SS
KJr  Sr " S S\5      r\r " S S5      r " S S\5      r " S S\5      r  " S S\ 5      r! " S S\ 5      r" " S S\5      r# S(S jr$S r%S r& S(S jr'S r(S r) S)S  jr* " S! S"\5      r+S# r,S*S$ jr-S% r.S& r/\0S':X  a  \/" 5         gg! \ a     Nâf = f)+aä  
A classifier model based on maximum entropy modeling framework.  This
framework considers all of the probability distributions that are
empirically consistent with the training data; and chooses the
distribution with the highest entropy.  A probability distribution is
"empirically consistent" with a set of training data if its estimated
frequency with which a class and a feature vector value co-occur is
equal to the actual frequency in the data.

Terminology: 'feature'
======================
The term *feature* is usually used to refer to some property of an
unlabeled token.  For example, when performing word sense
disambiguation, we might define a ``'prevword'`` feature whose value is
the word preceding the target word.  However, in the context of
maxent modeling, the term *feature* is typically used to refer to a
property of a "labeled" token.  In order to prevent confusion, we
will introduce two distinct terms to disambiguate these two different
concepts:

  - An "input-feature" is a property of an unlabeled token.
  - A "joint-feature" is a property of a labeled token.

In the rest of the ``nltk.classify`` module, the term "features" is
used to refer to what we will call "input-features" in this module.

In literature that describes and discusses maximum entropy models,
input-features are typically called "contexts", and joint-features
are simply referred to as "features".

Converting Input-Features to Joint-Features
-------------------------------------------
In maximum entropy models, joint-features are required to have numeric
values.  Typically, each input-feature ``input_feat`` is mapped to a
set of joint-features of the form:

|   joint_feat(token, label) = { 1 if input_feat(token) == feat_val
|                              {      and label == some_label
|                              {
|                              { 0 otherwise

For all values of ``feat_val`` and ``some_label``.  This mapping is
performed by classes that implement the ``MaxentFeatureEncodingI``
interface.
é    N)Údefaultdict)ÚClassifierI)Ú
call_megamÚparse_megam_weightsÚwrite_megam_file)Ú	call_tadmÚparse_tadm_weightsÚwrite_tadm_file)ÚCutoffCheckerÚaccuracyÚlog_likelihood)Úgzip_open_unicode)ÚDictionaryProbDist)ÚOrderedDictz
epytext enc                   óŠ   • \ rS rSrSrSS jrS rS rS rS r	S r
SS	 jrSS
 jrSS jrS r/ SQr\     SS j5       rSrg)ÚMaxentClassifieréN   aº  
A maximum entropy classifier (also known as a "conditional
exponential classifier").  This classifier is parameterized by a
set of "weights", which are used to combine the joint-features
that are generated from a featureset by an "encoding".  In
particular, the encoding maps each ``(featureset, label)`` pair to
a vector.  The probability of each label is then computed using
the following equation::

                            dotprod(weights, encode(fs,label))
  prob(fs|label) = ---------------------------------------------------
                   sum(dotprod(weights, encode(fs,l)) for l in labels)

Where ``dotprod`` is the dot product::

  dotprod(a,b) = sum(x*y for (x,y) in zip(a,b))
c                 óf   • Xl         X l        X0l        UR                  5       [	        U5      :X  d   eg)a  
Construct a new maxent classifier model.  Typically, new
classifier models are created using the ``train()`` method.

:type encoding: MaxentFeatureEncodingI
:param encoding: An encoding that is used to convert the
    featuresets that are given to the ``classify`` method into
    joint-feature vectors, which are used by the maxent
    classifier model.

:type weights: list of float
:param weights:  The feature weight vector for this classifier.

:type logarithmic: bool
:param logarithmic: If false, then use non-logarithmic weights.
N)Ú	_encodingÚ_weightsÚ_logarithmicÚlengthÚlen)ÚselfÚencodingÚweightsÚlogarithmics       Ú6/usr/lib/python3/dist-packages/nltk/classify/maxent.pyÚ__init__ÚMaxentClassifier.__init__a   s-   € ð" "ŒØŒØ'Ôà�‰Ó ¤C¨£LÓ0Ð0Ñ0ó    c                 ó6   • U R                   R                  5       $ ©N)r   Úlabels©r   s    r   r$   ÚMaxentClassifier.labelsx   s   € Ø�~‰~×$Ñ$Ó&Ð&r!   c                 ób   • Xl         U R                  R                  5       [        U5      :X  d   eg)zˆ
Set the feature weight vector for this classifier.
:param new_weights: The new feature weight vector.
:type new_weights: list of float
N)r   r   r   r   )r   Únew_weightss     r   Úset_weightsÚMaxentClassifier.set_weights{   s)   € ð $ŒØ�~‰~×$Ñ$Ó&¬#¨kÓ*:Ó:Ð:Ñ:r!   c                 ó   • U R                   $ )zO
:return: The feature weight vector for this classifier.
:rtype: list of float
)r   r%   s    r   r   ÚMaxentClassifier.weights„   s   € ð
 �}‰}Ðr!   c                 ó@   • U R                  U5      R                  5       $ r#   )Úprob_classifyÚmax)r   Ú
featuresets     r   ÚclassifyÚMaxentClassifier.classify‹   s   € Ø×!Ñ! *Ó-×1Ñ1Ó3Ð3r!   c                 ó`  • 0 nU R                   R                  5        H{  nU R                   R                  X5      nU R                  (       a'  SnU H  u  pgXPR                  U   U-  -  nM     XRU'   MV  SnU H  u  pgX€R                  U   U-  -  nM     X‚U'   M}     [        X R                  SS9$ )Ng        ç      ð?T)ÚlogÚ	normalize)r   r$   Úencoder   r   r   )	r   r0   Ú	prob_dictÚlabelÚfeature_vectorÚtotalÚf_idÚf_valÚprods	            r   r.   ÚMaxentClassifier.prob_classifyŽ   s°   € Øˆ	Ø—^‘^×*Ñ*Ö,ˆEØ!Ÿ^™^×2Ñ2°:ÓEˆNà× × Ø�Û#1‘K�DØŸ]™]¨4Ñ0°5Ñ8Ñ8’Eñ $2à#(˜%Ó ð �Û#1‘K�DØŸM™M¨$Ñ/°5Ñ8Ñ8’Dñ $2à#'˜%Ó ñ -ô  " )×1BÑ1BÈdÑSÐSr!   c           	      óz  ^ ^^• SnS[        US-
  5      -   S-   nT R                  U5      m[        TR                  5       TR                  SS9nUSU n[        SR                  U5      S	R                  S
 U 5       5      -   5        [        SSUS-
  S[        U5      -  -   -  -   5        [        [        5      m[        U5       Hæ  u  pgT R                  R                  X5      nUR                  U 4S jSS9  U H¬  u  pšT R                  (       a  T R                   U	   U
-  nOT R                   U	   U
-  nT R                  R#                  U	5      nUR%                  S5      S   nUSU
-  -  n[        U5      S:”  a  USS S-   n[        XLUS-  S-  U4-  5        TU==   U-  ss'   M®     Mè     [        SSUS-
  S[        U5      -  -   -  -   5        [        SR                  U5      S	R                  U4S jU 5       5      -   5        [        SR                  U5      S	R                  U4S jU 5       5      -   5        g)z«
Print a table showing the effect of each of the features in
the given feature set, and how they combine to determine the
probabilities of each label for that featureset.
é2   z  %-é   zs%s%8.3fT©ÚkeyÚreverseNz	  FeatureÚ c              3   ó8   #   • U  H  nS SU-  SS -  v •  M     g7f)z%8sú%sNé   © )Ú.0Úls     r   Ú	<genexpr>Ú+MaxentClassifier.explain.<locals>.<genexpr>°   s   é € Ð?º°1�e  q¡¨"¨1˜~Ö.ºùs   ‚z  Ú-é   c                 ó:   >• [        TR                  U S      5      $ )Nr   ©Úabsr   )Úfid__r   s    €r   Ú<lambda>Ú*MaxentClassifier.explain.<locals>.<lambda>·   s   ø€ ¤# d§m¡m°E¸!±HÑ&=Ô">r!   ú and label is r   z (%s)é/   é,   z...Ú é   z  TOTAL:c              3   ó4   >#   • U  H  nS TU   -  v •  M     g7f©z%8.3fNrJ   )rK   rL   Úsumss     €r   rM   rN   Ç   s   øé € Ð3VÊvÈ!°G¸dÀ1¹gÖ4EÊvùs   ƒz  PROBS:c              3   óL   >#   • U  H  nS TR                  U5      -  v •  M     g7fr]   )Úprob)rK   rL   Úpdists     €r   rM   rN   Ë   s   øé € Ð>²v°!�g §
¡
¨1£Ö-²vùs   ƒ!$)Ústrr.   ÚsortedÚsamplesr`   ÚprintÚljustÚjoinr   r   ÚintÚ	enumerater   r7   Úsortr   r   ÚdescribeÚsplit)r   r0   ÚcolumnsÚdescr_widthÚTEMPLATEr$   Úir9   r:   r<   r=   ÚscoreÚdescrra   r^   s   `            @@r   ÚexplainÚMaxentClassifier.explain¢   s$  ú€ ð ˆØœC ¨a¡Ó0Ñ0°:Ñ=ˆà×"Ñ" :Ó.ˆÜ˜Ÿ™›¨U¯Z©ZÀÑFˆØ˜˜Ð!ˆÜØ×Ñ˜kÓ*Ø�g‰gÑ?¹Ó?Ó?ñ@ô	
ô 	ˆd�S˜K¨!™O¨a´#°f³+©oÑ=Ñ>Ñ>Ô?Üœ3ÓˆÜ! &Ö)‰HˆAØ!Ÿ^™^×2Ñ2°:ÓEˆNØ×ÑÜ>Èð  ñ ó  .‘�Ø×$×$Ø ŸM™M¨$Ñ/°%Ñ7‘Eà ŸM™M¨$Ñ/°5Ñ8�EØŸ™×/Ñ/°Ó5�ØŸ™Ð$4Ó5°aÑ8�Ø˜ 5™Ñ(�Ü�u“: “?Ø! # 2˜J¨Ñ.�EÜ�h¨¨Q©°©°eÐ!<Ñ<Ô=Ø�U“˜uÑ$•ó  .ñ *ô" 	ˆd�S˜K¨!™O¨a´#°f³+©oÑ=Ñ>Ñ>Ô?ÜØ×Ñ˜[Ó)¨B¯G©GÔ3VÉvÓ3VÓ,VÑVô	
ô 	Ø×Ñ˜[Ó)Ø�g‰gÔ>±vÓ>Ó>ñ?õ	
r!   c           	      óÔ   ^ • [        T S5      (       a  T R                  SU $ [        [        [	        [        T R                  5      5      5      U 4S jSS9T l        T R                  SU $ )zG
Generates the ranked list of informative features from most to least.
Ú_most_informative_featuresNc                 ó4   >• [        TR                  U    5      $ r#   rR   )Úfidr   s    €r   rU   Ú<MaxentClassifier.most_informative_features.<locals>.<lambda>×   s   ø€ ¤ D§M¡M°#Ñ$6Ô 7r!   TrC   )Úhasattrrv   rc   ÚlistÚranger   r   )r   Úns   ` r   Úmost_informative_featuresÚ*MaxentClassifier.most_informative_featuresÎ   sd   ø€ ô �4Ð5×6Ñ6Ø×2Ñ2°2°AÐ6Ð6ä.4Ü”Uœ3˜tŸ}™}Ó-Ó.Ó/Ü7Øñ/ˆDÔ+ð
 ×2Ñ2°2°AÐ6Ð6r!   c                 ór  • U R                  S5      nUS:X  a'  U Vs/ s H  o@R                  U   S:”  d  M  UPM     nnO,US:X  a&  U Vs/ s H  o@R                  U   S:  d  M  UPM     nnUSU  H:  n[        U R                  U   S SU R                  R	                  U5       35        M<     gs  snf s  snf )zƒ
:param show: all, neg, or pos (for negative-only or positive-only)
:type show: str
:param n: The no. of top features
:type n: int
NÚposr   Únegz8.3frZ   )r~   r   re   r   rk   )r   r}   ÚshowÚfidsrx   s        r   Úshow_most_informative_featuresÚ/MaxentClassifier.show_most_informative_featuresÜ   s°   € ð ×-Ñ-¨dÓ3ˆØ�5‹=Ù#'ÓB¢4˜C¯=©=¸Ñ+=ÀÑ+A—C¡4ˆDÐBˆDØ�U‹]Ù#'ÓB¢4˜C¯=©=¸Ñ+=ÀÑ+A—C¡4ˆDÐBØ˜˜“8ˆCÜ�T—]‘] 3Ñ'¨Ð-¨Q¨t¯~©~×/FÑ/FÀsÓ/KÐ.LÐMÖNò ùò CùâBs   œB/¶B/Á	B4Á#B4c                 ó‚   • S[        U R                  R                  5       5      U R                  R                  5       4-  $ )Nz:<ConditionalExponentialClassifier: %d labels, %d features>)r   r   r$   r   r%   s    r   Ú__repr__ÚMaxentClassifier.__repr__ì   s:   € ØKÜ�—‘×%Ñ%Ó'Ó(Ø�N‰N×!Ñ!Ó#ðO
ñ 
ð 	
r!   )ÚGISÚIISÚMEGAMÚTADMNc                 óT  • Uc  SnU H  nUS;  d  M  [        SU-  5      e   UR                  5       nUS:X  a  [        XXE40 UD6$ US:X  a  [        XXE40 UD6$ US:X  a  [	        XXEU40 UD6$ US:X  a)  Un	X9S'   XIS'   XYS	'   XiS
'   [
        R                  " U40 U	D6$ [        SU-  5      e)aV  
Train a new maxent classifier based on the given corpus of
training samples.  This classifier will have its weights
chosen to maximize entropy while remaining empirically
consistent with the training corpus.

:rtype: MaxentClassifier
:return: The new maxent classifier

:type train_toks: list
:param train_toks: Training data, represented as a list of
    pairs, the first member of which is a featureset,
    and the second of which is a classification label.

:type algorithm: str
:param algorithm: A case-insensitive string, specifying which
    algorithm should be used to train the classifier.  The
    following algorithms are currently available.

    - Iterative Scaling Methods: Generalized Iterative Scaling (``'GIS'``),
      Improved Iterative Scaling (``'IIS'``)
    - External Libraries (requiring megam):
      LM-BFGS algorithm, with training performed by Megam (``'megam'``)

    The default algorithm is ``'IIS'``.

:type trace: int
:param trace: The level of diagnostic tracing output to produce.
    Higher values produce more verbose output.
:type encoding: MaxentFeatureEncodingI
:param encoding: A feature encoding, used to convert featuresets
    into feature vectors.  If none is specified, then a
    ``BinaryMaxentFeatureEncoding`` will be built based on the
    features that are attested in the training corpus.
:type labels: list(str)
:param labels: The set of possible labels.  If none is given, then
    the set of all labels attested in the training data will be
    used instead.
:param gaussian_prior_sigma: The sigma value for a gaussian
    prior on model weights.  Currently, this is supported by
    ``megam``. For other algorithms, its value is ignored.
:param cutoffs: Arguments specifying various conditions under
    which the training should be halted.  (Some of the cutoff
    conditions are not supported by some algorithms.)

    - ``max_iter=v``: Terminate after ``v`` iterations.
    - ``min_ll=v``: Terminate after the negative average
      log-likelihood drops under ``v``.
    - ``min_lldelta=v``: Terminate if a single iteration improves
      log likelihood by less than ``v``.
Úiis)	Úmax_iterÚmin_llÚmin_lldeltaÚmax_accÚmin_accdeltaÚcount_cutoffÚnormÚexplicitÚ	bernoullizUnexpected keyword arg %rÚgisÚmegamÚtadmÚtracer   r$   Úgaussian_prior_sigmazUnknown algorithm %s)Ú	TypeErrorÚlowerÚ train_maxent_classifier_with_iisÚ train_maxent_classifier_with_gisÚ"train_maxent_classifier_with_megamÚTadmMaxentClassifierÚtrainÚ
ValueError)
ÚclsÚ
train_toksÚ	algorithmrœ   r   r$   r�   ÚcutoffsrD   Úkwargss
             r   r¤   ÚMaxentClassifier.trainö   s  € ð| ÑØˆIÛˆCØð 
õ 
ô  Ð ;¸cÑ AÓBÐBñ ð —O‘OÓ%ˆ	Ø˜ÓÜ3Ø 8ñØ7>ñð ð ˜%ÓÜ3Ø 8ñØ7>ñð ð ˜'Ó!Ü5Ø 8Ð5IñØMTñð ð ˜&Ó ØˆFØ#�7‰OØ!)�:ÑØ%�8ÑØ-AÐ)Ñ*Ü'×-Ò-¨jÑC¸FÑCÐCäÐ3°iÑ?Ó@Ð@r!   )r   r   rv   r   )T)é   )é
   )r­   Úall)Né   NNr   )Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   r$   r)   r   r1   r.   rs   r~   r…   rˆ   Ú
ALGORITHMSÚclassmethodr¤   Ú__static_attributes__rJ   r!   r   r   r   N   sj   † ñô$1ò.'ò;òò4òTô(*
ôX7ôOò 
ò 1€Jàð ØØØØóaAó óaAr!   r   c                   ó6   • \ rS rSrSrS rS rS rS rS r	Sr
g	)
ÚMaxentFeatureEncodingIid  ap  
A mapping that converts a set of input-feature values to a vector
of joint-feature values, given a label.  This conversion is
necessary to translate featuresets into a format that can be used
by maximum entropy models.

The set of joint-features used by a given encoding is fixed, and
each index in the generated joint-feature vectors corresponds to a
single joint-feature.  The length of the generated joint-feature
vectors is therefore constant (for a given encoding).

Because the joint-feature vectors generated by
``MaxentFeatureEncodingI`` are typically very sparse, they are
represented as a list of ``(index, value)`` tuples, specifying the
value of each non-zero joint-feature.

Feature encodings are generally created using the ``train()``
method, which generates an appropriate encoding based on the
input-feature values and labels that are present in a given
corpus.
c                 ó   • [        5       e)a  
Given a (featureset, label) pair, return the corresponding
vector of joint-feature values.  This vector is represented as
a list of ``(index, value)`` tuples, specifying the value of
each non-zero joint-feature.

:type featureset: dict
:rtype: list(tuple(int, int))
©ÚNotImplementedError©r   r0   r9   s      r   r7   ÚMaxentFeatureEncodingI.encode{  ó   € ô "Ó#Ð#r!   c                 ó   • [        5       e)zr
:return: The size of the fixed-length joint-feature vectors
    that are generated by this encoding.
:rtype: int
r»   r%   s    r   r   ÚMaxentFeatureEncodingI.length‡  ó   € ô "Ó#Ð#r!   c                 ó   • [        5       e)z¶
:return: A list of the "known labels" -- i.e., all labels
    ``l`` such that ``self.encode(fs,l)`` can be a nonzero
    joint-feature vector for some value of ``fs``.
:rtype: list
r»   r%   s    r   r$   ÚMaxentFeatureEncodingI.labels�  s   € ô "Ó#Ð#r!   c                 ó   • [        5       e)z†
:return: A string describing the value of the joint-feature
    whose index in the generated feature vectors is ``fid``.
:rtype: str
r»   ©r   rx   s     r   rk   ÚMaxentFeatureEncodingI.describe˜  rÂ   r!   c                 ó   • [        5       e)a7  
Construct and return new feature encoding, based on a given
training corpus ``train_toks``.

:type train_toks: list(tuple(dict, str))
:param train_toks: Training data, represented as a list of
    pairs, the first member of which is a feature dictionary,
    and the second of which is a classification label.
r»   )r¦   r§   s     r   r¤   ÚMaxentFeatureEncodingI.train   r¿   r!   rJ   N)r°   r±   r²   r³   r´   r7   r   r$   rk   r¤   r·   rJ   r!   r   r¹   r¹   d  s    † ñò,
$ò$ò$ò$õ
$r!   r¹   c                   ó6   • \ rS rSrSrS rS rS rS rS r	Sr
g	)
Ú#FunctionBackedMaxentFeatureEncodingi­  z
A feature encoding that calls a user-supplied function to map a
given featureset/label pair to a sparse joint-feature vector.
c                 ó(   • X l         Xl        X0l        g)aß  
Construct a new feature encoding based on the given function.

:type func: (callable)
:param func: A function that takes two arguments, a featureset
     and a label, and returns the sparse joint feature vector
     that encodes them::

         func(featureset, label) -> feature_vector

     This sparse joint feature vector (``feature_vector``) is a
     list of ``(index,value)`` tuples.

:type length: int
:param length: The size of the fixed-length joint-feature
    vectors that are generated by this encoding.

:type labels: list
:param labels: A list of the "known labels" for this
    encoding -- i.e., all labels ``l`` such that
    ``self.encode(fs,l)`` can be a nonzero joint-feature vector
    for some value of ``fs``.
N)Ú_lengthÚ_funcÚ_labels)r   Úfuncr   r$   s       r   r   Ú,FunctionBackedMaxentFeatureEncoding.__init__³  s   € ð0 ŒØŒ
Ø�r!   c                 ó$   • U R                  X5      $ r#   )rÎ   r½   s      r   r7   Ú*FunctionBackedMaxentFeatureEncoding.encodeÏ  s   € Ø�z‰z˜*Ó,Ð,r!   c                 ó   • U R                   $ r#   ©rÍ   r%   s    r   r   Ú*FunctionBackedMaxentFeatureEncoding.lengthÒ  ó   € Ø�|‰|Ðr!   c                 ó   • U R                   $ r#   ©rÏ   r%   s    r   r$   Ú*FunctionBackedMaxentFeatureEncoding.labelsÕ  r×   r!   c                 ó   • g)Nzno description availablerJ   rÆ   s     r   rk   Ú,FunctionBackedMaxentFeatureEncoding.describeØ  s   € Ø)r!   )rÎ   rÏ   rÍ   N)r°   r±   r²   r³   r´   r   r7   r   r$   rk   r·   rJ   r!   r   rË   rË   ­  s    † ñò
ò8-òòõ*r!   rË   c                   óN   • \ rS rSrSrSS jrS rS rS rS r	\
SS	 j5       rS
rg)ÚBinaryMaxentFeatureEncodingiÜ  a„  
A feature encoding that generates vectors containing a binary
joint-features of the form:

|  joint_feat(fs, l) = { 1 if (fs[fname] == fval) and (l == label)
|                      {
|                      { 0 otherwise

Where ``fname`` is the name of an input-feature, ``fval`` is a value
for that input-feature, and ``label`` is a label.

Typically, these features are constructed based on a training
corpus, using the ``train()`` method.  This method will create one
feature for each combination of ``fname``, ``fval``, and ``label``
that occurs at least once in the training corpus.

The ``unseen_features`` parameter can be used to add "unseen-value
features", which are used whenever an input feature has a value
that was not encountered in the training corpus.  These features
have the form:

|  joint_feat(fs, l) = { 1 if is_unseen(fname, fs[fname])
|                      {      and l == label
|                      {
|                      { 0 otherwise

Where ``is_unseen(fname, fval)`` is true if the encoding does not
contain any joint features that are true when ``fs[fname]==fval``.

The ``alwayson_features`` parameter can be used to add "always-on
features", which have the form::

|  joint_feat(fs, l) = { 1 if (l == label)
|                      {
|                      { 0 otherwise

These always-on features allow the maxent model to directly model
the prior probabilities of each label.
c                 óÄ  • [        UR                  5       5      [        [        [        U5      5      5      :w  a  [	        S5      e[        U5      U l         X l         [        U5      U l         SU l	         SU l
         U(       aZ  [        U5       VVs0 s H  u  pVXeU R                  -   _M     snnU l	        U =R                  [        U R                  5      -  sl        U(       ai  U VVVs1 s H  u  pxogiM	     n	nnn[        U	5       VVs0 s H  u  pWXuU R                  -   _M     snnU l
        U =R                  [        U	5      -  sl        ggs  snnf s  snnnf s  snnf )a[  
:param labels: A list of the "known labels" for this encoding.

:param mapping: A dictionary mapping from ``(fname,fval,label)``
    tuples to corresponding joint-feature indexes.  These
    indexes must be the set of integers from 0...len(mapping).
    If ``mapping[fname,fval,label]=id``, then
    ``self.encode(..., fname:fval, ..., label)[id]`` is 1;
    otherwise, it is 0.

:param unseen_features: If true, then include unseen value
   features in the generated joint-feature vectors.

:param alwayson_features: If true, then include always-on
   features in the generated joint-feature vectors.
úHMapping values must be exactly the set of integers from 0...len(mapping)N©ÚsetÚvaluesr|   r   r¥   r{   rÏ   Ú_mappingrÍ   Ú	_alwaysonÚ_unseenri   ©
r   r$   ÚmappingÚunseen_featuresÚalwayson_featuresrp   r9   ÚfnameÚfvalÚfnamess
             r   r   Ú$BinaryMaxentFeatureEncoding.__init__  ó*  € ô" ˆw�~‰~ÓÓ ¤C¬¬c°'«lÓ(;Ó$<Ó<Üð8óð ô
 ˜F“|ˆŒØ(àŒØ9ä˜7“|ˆŒØ<àˆŒØ,àˆŒØ,æä:CÀFÔ:KôÚ:K©J¨Q�˜4Ÿ<™<Ñ'Ò'Ñ:KòˆDŒNð �LŠLœC §¡Ó/Ñ/�LæÙ8?Õ@ºÑ 4 ¨e’e¹ˆFÒ@ÜFOÐPVÔFWÔXÒFW¹
¸˜E t§|¡|Ñ#3Ò3ÑFWÒXˆDŒLØ�LŠLœC ›KÑ'ŽLð ùóùô AùÛXó   ÂEÃ+EÄEc                 ó   • / nUR                  5        H§  u  pEXEU4U R                  ;   a$  UR                  U R                  XEU4   S45        M;  U R                  (       d  MN  U R                   H  nXEU4U R                  ;   d  M    Mt     X@R                  ;   d  M‡  UR                  U R                  U   S45        M©     U R
                  (       a/  X R
                  ;   a   UR                  U R
                  U   S45        U$ ©Nr[   )Úitemsrä   Úappendræ   rÏ   rå   ©r   r0   r9   r   rë   rì   Úlabel2s          r   r7   Ú"BinaryMaxentFeatureEncoding.encode6  sÒ   € àˆð &×+Ñ+Ö-‰KˆEà˜UÐ# t§}¡}Ó4Ø—‘ §¡¨u¸EÐ/AÑ!BÀAÐ FÖGð ——‘à"Ÿlœl�FØ VÐ,°·±Õ=Úñ +ð
 §¡Õ,Ø Ÿ™¨¯©°eÑ)<¸aÐ(@ÖAñ .ð" �>�>˜e§~¡~Ó5Ø�O‰O˜TŸ^™^¨EÑ2°AÐ6Ô7àˆr!   c                 ó  • [        U[        5      (       d  [        S5      e U R                    U[        U R                  5      :  a  U R                  U   u  pEnU SU< SU< 3$ U R                  (       aM  XR                  R                  5       ;   a0  U R                  R                  5        H  u  pgX:X  d  M  SU-  s  $    g U R                  (       aM  XR                  R                  5       ;   a0  U R                  R                  5        H  u  pGX:X  d  M  SU-  s  $    g [        S5      e! [         aS    S/[        U R                  5      -  U l        U R                  R                  5        H  u  p#X R                  U'   M      GNZf = f©Nzdescribe() expected an intéÿÿÿÿz==rW   zlabel is %rz%s is unseenzBad feature id©Ú
isinstancerh   rž   Ú_inv_mappingÚAttributeErrorr   rä   ró   rå   rã   ræ   r¥   ©r   r<   Úinforp   rë   rì   r9   Úf_id2s           r   rk   Ú$BinaryMaxentFeatureEncoding.describeQ  óL  € ä˜$¤×$Ñ$ÜÐ8Ó9Ð9ð	,Ø×Òð ”#�d—m‘mÓ$Ó$Ø#'×#4Ñ#4°TÑ#:Ñ ˆU˜%Ø�W˜B˜t™h n°U±IÐ>Ð>Ø�^�^ ¯©×(=Ñ(=Ó(?Ó ?Ø $§¡× 4Ñ 4Ö 6‘�Ø•=Ø(¨5Ñ0Ò0ò !7ð �\�\˜d§l¡l×&9Ñ&9Ó&;Ó;Ø $§¡× 2Ñ 2Ö 4‘�Ø•=Ø)¨EÑ1Ò1ò !5ô Ð-Ó.Ð.øô# ó 	,Ø!# ¤s¨4¯=©=Ó'9Ñ 9ˆDÔØŸ=™=×.Ñ.Ö0‘�Ø'+×!Ñ! !Ó$ô 1ð	,úó   ¢D, Ä,AF	ÆF	c                 ó   • U R                   $ r#   rÙ   r%   s    r   r$   Ú"BinaryMaxentFeatureEncoding.labelsj  ó   € à�|‰|Ðr!   c                 ó   • U R                   $ r#   rÕ   r%   s    r   r   Ú"BinaryMaxentFeatureEncoding.lengthn  r  r!   Nc                 óX  • 0 n[        5       n[        [        5      nU H|  u  p‰U(       a  X“;  a  [        SU	-  5      eUR	                  U	5        UR                  5        H8  u  p«XzU4==   S-  ss'   XzU4   U:¼  d  M  X«U	4U;  d  M)  [        U5      XZX¹4'   M:     M~     Uc  UnU " X540 UD6$ )a  
Construct and return new feature encoding, based on a given
training corpus ``train_toks``.  See the class description
``BinaryMaxentFeatureEncoding`` for a description of the
joint-features that will be included in this encoding.

:type train_toks: list(tuple(dict, str))
:param train_toks: Training data, represented as a list of
    pairs, the first member of which is a feature dictionary,
    and the second of which is a classification label.

:type count_cutoff: int
:param count_cutoff: A cutoff value that is used to discard
    rare joint-features.  If a joint-feature's value is 1
    fewer than ``count_cutoff`` times in the training corpus,
    then that joint-feature is not included in the generated
    encoding.

:type labels: list
:param labels: A list of labels that should be used by the
    classifier.  If not specified, then the set of labels
    attested in ``train_toks`` will be used.

:param options: Extra parameters for the constructor, such as
    ``unseen_features`` and ``alwayson_features``.
úUnexpected label %sr[   )râ   r   rh   r¥   Úaddró   r   ©r¦   r§   r•   r$   Úoptionsrè   Úseen_labelsÚcountÚtokr9   rë   rì   s               r   r¤   Ú!BinaryMaxentFeatureEncoding.trainr  s¼   € ð8 ˆÜ“eˆÜœCÓ ˆã$‰JˆCÞ˜%Ó-Ü Ð!6¸Ñ!>Ó?Ð?Ø�O‰O˜EÔ"ð  #Ÿy™yž{‘�ð ˜T�kÓ" aÑ'Ó"Ø ˜Ñ%¨Õ5Ø UÐ+°7Õ:Ü69¸'³l˜ tÐ 2Ó3ó  +ñ %ð ‰>Ø ˆFÙ�6Ñ. gÑ.Ð.r!   ©rå   rý   rÏ   rÍ   rä   ræ   ©FF©r   N©r°   r±   r²   r³   r´   r   r7   rk   r$   r   r¶   r¤   r·   rJ   r!   r   rÞ   rÞ   Ü  s6   † ñ&ôP/(òbò6/ò2òð ó0/ó ó0/r!   rÞ   c                   óF   • \ rS rSrSr S
S jr\S 5       rS rS r	S r
S	rg)ÚGISEncodingi¦  aó  
A binary feature encoding which adds one new joint-feature to the
joint-features defined by ``BinaryMaxentFeatureEncoding``: a
correction feature, whose value is chosen to ensure that the
sparse vector always sums to a constant non-negative number.  This
new feature is used to ensure two preconditions for the GIS
training algorithm:

  - At least one feature vector index must be nonzero for every
    token.
  - The feature vector must sum to a constant non-negative number
    for every token.
Nc           
      óœ   • [         R                  XX#U5        Uc%  [        U VVVs1 s H  u  pgo†iM	     snnn5      S-   nXPl        gs  snnnf )zá
:param C: The correction constant.  The value of the correction
    feature is based on this value.  In particular, its value is
    ``C - sum([v for (f,v) in encoding])``.
:seealso: ``BinaryMaxentFeatureEncoding.__init__``
Nr[   )rÞ   r   r   Ú_C)	r   r$   rè   ré   rê   ÚCrë   rì   r9   s	            r   r   ÚGISEncoding.__init__µ  sO   € ô 	$×,Ñ,Ø˜'Ð4Eô	
ð ‰9Ü±wÕ?²wÑ3 ¨U’U±wÓ?Ó@À1ÑDˆAØ�ùô @s   ¦Ac                 ó   • U R                   $ )zGThe non-negative constant that all encoded feature vectors
will sum to.©r  r%   s    r   r  ÚGISEncoding.CÅ  s   € ð �w‰wˆr!   c                 óò   • [         R                  XU5      n[         R                  U 5      n[        S U 5       5      nXPR                  :¼  a  [        S5      eUR                  X@R                  U-
  45        U$ )Nc              3   ó*   #   • U  H	  u  pUv •  M     g 7fr#   rJ   )rK   ÚfÚvs      r   rM   Ú%GISEncoding.encode.<locals>.<genexpr>Ñ  s   é € Ð-¢H™&˜1•A¢Hùó   ‚z&Correction feature is not high enough!)rÞ   r7   r   Úsumr  r¥   rô   )r   r0   r9   r   Úbase_lengthr;   s         r   r7   ÚGISEncoding.encodeË  sj   € ä.×5Ñ5°dÈÓNˆÜ1×8Ñ8¸Ó>ˆô Ñ-¡HÓ-Ó-ˆØ—G‘GÓÜÐEÓFÐFØ�‰˜§g¡g°¡oÐ6Ô7ð ˆr!   c                 ó2   • [         R                  U 5      S-   $ rò   )rÞ   r   r%   s    r   r   ÚGISEncoding.lengthÙ  s   € Ü*×1Ñ1°$Ó7¸!Ñ;Ð;r!   c                 ó|   • U[         R                  U 5      :X  a  SU R                  -  $ [         R                  X5      $ )NzCorrection feature (%s))rÞ   r   r  rk   )r   r<   s     r   rk   ÚGISEncoding.describeÜ  s6   € ØÔ.×5Ñ5°dÓ;Ó;Ø,¨t¯w©wÑ6Ð6ä.×7Ñ7¸ÓCÐCr!   r  )FFN)r°   r±   r²   r³   r´   r   Úpropertyr  r7   r   rk   r·   rJ   r!   r   r  r  ¦  s7   † ñð RVôð  ñó ðò
ò<õDr!   r  c                   óJ   • \ rS rSrS
S jrS rS rS rS r\	SS j5       r
S	rg)ÚTadmEventMaxentFeatureEncodingiã  c                 ó„   • [        U5      U l        [        5       U l        [        R	                  XU R                  X45        g r#   )r   rä   Ú_label_mappingrÞ   r   )r   r$   rè   ré   rê   s        r   r   Ú'TadmEventMaxentFeatureEncoding.__init__ä  s1   € Ü# GÓ,ˆŒÜ)›mˆÔÜ#×,Ñ,Ø˜$Ÿ-™-¨õ	
r!   c                 óª  • / nUR                  5        H¼  u  pEXB4U R                  ;  a#  [        U R                  5      U R                  XB4'   XPR                  ;  aF  [	        U[
        5      (       d#  [        U R                  5      U R                  U'   OXPR                  U'   UR                  U R                  XB4   U R                  U   45        M¾     U$ r#   )ró   rä   r   r1  rü   rh   rô   )r   r0   r9   r   ÚfeatureÚvalues         r   r7   Ú%TadmEventMaxentFeatureEncoding.encodeë  s¹   € ØˆØ(×.Ñ.Ö0‰NˆGØÐ t§}¡}Ó4Ü25°d·m±mÓ2D�—‘˜wÐ.Ñ/Ø×/Ñ/Ó/Ü! %¬×-Ñ-Ü14°T×5HÑ5HÓ1I�D×'Ñ'¨Ò.à16×'Ñ'¨Ñ.Ø�O‰OØ—‘ Ð/Ñ0°$×2EÑ2EÀeÑ2LÐMöñ 1ð ˆr!   c                 ó   • U R                   $ r#   rÙ   r%   s    r   r$   Ú%TadmEventMaxentFeatureEncoding.labelsú  r×   r!   c                 ó`   • U R                    H  u  p#U R                   X#4   U:X  d  M  X#4s  $    g r#   )rä   )r   rx   r4  r9   s       r   rk   Ú'TadmEventMaxentFeatureEncoding.describeý  s/   € Ø"Ÿmœm‰NˆGØ�}‰}˜gÐ-Ñ.°#Õ5ØÐ'Ò'ò ,r!   c                 ó,   • [        U R                  5      $ r#   )r   rä   r%   s    r   r   Ú%TadmEventMaxentFeatureEncoding.length  s   € Ü�4—=‘=Ó!Ð!r!   Nc                 ó   • [        5       nU(       d  / n[        U5      nU H  u  pgXs;  d  M  UR                  U5        M     U H/  u  pgU H$  nU H  nX‡4U;  d  M  [        U5      XXU4'   M     M&     M1     U " X540 UD6$ r#   )r   r{   rô   r   )	r¦   r§   r•   r$   r  rè   r0   r9   r4  s	            r   r¤   Ú$TadmEventMaxentFeatureEncoding.train  s�   € ä“-ˆÞØˆFô ˜*Ó%ˆ
ã!+ÑˆJØÕ"Ø—‘˜eÖ$ñ ",ó ",ÑˆJÛ�Û)�GØÐ'¨wÕ6Ü47¸³L˜¨%Ð 0Ó1ó  *ó  ñ ",ñ �6Ñ. gÑ.Ð.r!   )r1  rä   r  r  )r°   r±   r²   r³   r   r7   r$   rk   r   r¶   r¤   r·   rJ   r!   r   r/  r/  ã  s/   † ô
òòò(ò
"ð ó/ó ó/r!   r/  c                   óN   • \ rS rSrSrSS jrS rS rS rS r	\
SS	 j5       rS
rg)ÚTypedMaxentFeatureEncodingi  aº  
A feature encoding that generates vectors containing integer,
float and binary joint-features of the form:

Binary (for string and boolean features):

|  joint_feat(fs, l) = { 1 if (fs[fname] == fval) and (l == label)
|                      {
|                      { 0 otherwise

Value (for integer and float features):

|  joint_feat(fs, l) = { fval if     (fs[fname] == type(fval))
|                      {         and (l == label)
|                      {
|                      { not encoded otherwise

Where ``fname`` is the name of an input-feature, ``fval`` is a value
for that input-feature, and ``label`` is a label.

Typically, these features are constructed based on a training
corpus, using the ``train()`` method.

For string and boolean features [type(fval) not in (int, float)]
this method will create one feature for each combination of
``fname``, ``fval``, and ``label`` that occurs at least once in the
training corpus.

For integer and float features [type(fval) in (int, float)] this
method will create one feature for each combination of ``fname``
and ``label`` that occurs at least once in the training corpus.

For binary features the ``unseen_features`` parameter can be used
to add "unseen-value features", which are used whenever an input
feature has a value that was not encountered in the training
corpus.  These features have the form:

|  joint_feat(fs, l) = { 1 if is_unseen(fname, fs[fname])
|                      {      and l == label
|                      {
|                      { 0 otherwise

Where ``is_unseen(fname, fval)`` is true if the encoding does not
contain any joint features that are true when ``fs[fname]==fval``.

The ``alwayson_features`` parameter can be used to add "always-on
features", which have the form:

|  joint_feat(fs, l) = { 1 if (l == label)
|                      {
|                      { 0 otherwise

These always-on features allow the maxent model to directly model
the prior probabilities of each label.
c                 óÄ  • [        UR                  5       5      [        [        [        U5      5      5      :w  a  [	        S5      e[        U5      U l         X l         [        U5      U l         SU l	         SU l
         U(       aZ  [        U5       VVs0 s H  u  pVXeU R                  -   _M     snnU l	        U =R                  [        U R                  5      -  sl        U(       ai  U VVVs1 s H  u  pxogiM	     n	nnn[        U	5       VVs0 s H  u  pWXuU R                  -   _M     snnU l
        U =R                  [        U	5      -  sl        ggs  snnf s  snnnf s  snnf )a]  
:param labels: A list of the "known labels" for this encoding.

:param mapping: A dictionary mapping from ``(fname,fval,label)``
    tuples to corresponding joint-feature indexes.  These
    indexes must be the set of integers from 0...len(mapping).
    If ``mapping[fname,fval,label]=id``, then
    ``self.encode({..., fname:fval, ...``, label)[id]} is 1;
    otherwise, it is 0.

:param unseen_features: If true, then include unseen value
   features in the generated joint-feature vectors.

:param alwayson_features: If true, then include always-on
   features in the generated joint-feature vectors.
rà   Nrá   rç   s
             r   r   Ú#TypedMaxentFeatureEncoding.__init__T  rï   rð   c                 óÒ  • / nUR                  5        GH  u  pE[        U[        [        45      (       aL  U[	        U5      U4U R
                  ;   a.  UR                  U R
                  U[	        U5      U4   U45        Mk  Mm  XEU4U R
                  ;   a$  UR                  U R
                  XEU4   S45        M£  U R                  (       d  M¶  U R                   H  nXEU4U R
                  ;   d  M    MÜ     X@R                  ;   d  Mï  UR                  U R                  U   S45        GM     U R                  (       a/  X R                  ;   a   UR                  U R                  U   S45        U$ rò   )
ró   rü   rh   ÚfloatÚtyperä   rô   ræ   rÏ   rå   rõ   s          r   r7   Ú!TypedMaxentFeatureEncoding.encode…  s&  € àˆð &×+Ñ+×-‰KˆEÜ˜$¤¤e ×-Ñ-àœ4 ›: uÐ-°·±Ó>Ø—O‘O T§]¡]°5¼$¸t»*ÀeÐ3KÑ%LÈdÐ$SÖTñ ?ð  Ð'¨4¯=©=Ó8Ø—O‘O T§]¡]°5ÀÐ3EÑ%FÈÐ$JÖKð —\—\‘\à"&§,¤,˜Ø!¨Ð0°D·M±MÕAÚ!ñ #/ð
 !§L¡LÕ0Ø$ŸO™O¨T¯\©\¸%Ñ-@À!Ð,D×Eñ' .ð, �>�>˜e§~¡~Ó5Ø�O‰O˜TŸ^™^¨EÑ2°AÐ6Ô7àˆr!   c                 ó  • [        U[        5      (       d  [        S5      e U R                    U[        U R                  5      :  a  U R                  U   u  pEnU SU< SU< 3$ U R                  (       aM  XR                  R                  5       ;   a0  U R                  R                  5        H  u  pgX:X  d  M  SU-  s  $    g U R                  (       aM  XR                  R                  5       ;   a0  U R                  R                  5        H  u  pGX:X  d  M  SU-  s  $    g [        S5      e! [         aS    S/[        U R                  5      -  U l        U R                  R                  5        H  u  p#X R                  U'   M      GNZf = frù   rû   rÿ   s           r   rk   Ú#TypedMaxentFeatureEncoding.describe¥  r  r  c                 ó   • U R                   $ r#   rÙ   r%   s    r   r$   Ú!TypedMaxentFeatureEncoding.labels¾  r  r!   c                 ó   • U R                   $ r#   rÕ   r%   s    r   r   Ú!TypedMaxentFeatureEncoding.lengthÂ  r  r!   Nc                 ó   • 0 n[        5       n[        [        5      nU H   u  p‰U(       a  X“;  a  [        SU	-  5      eUR	                  U	5        UR                  5        H\  u  p«[        U5      [        [        4;   a  [        U5      nXzU4==   S-  ss'   XzU4   U:¼  d  MC  X«U	4U;  d  MM  [        U5      XZX¹4'   M^     M¢     Uc  UnU " X540 UD6$ )aq  
Construct and return new feature encoding, based on a given
training corpus ``train_toks``.  See the class description
``TypedMaxentFeatureEncoding`` for a description of the
joint-features that will be included in this encoding.

Note: recognized feature values types are (int, float), over
types are interpreted as regular binary features.

:type train_toks: list(tuple(dict, str))
:param train_toks: Training data, represented as a list of
    pairs, the first member of which is a feature dictionary,
    and the second of which is a classification label.

:type count_cutoff: int
:param count_cutoff: A cutoff value that is used to discard
    rare joint-features.  If a joint-feature's value is 1
    fewer than ``count_cutoff`` times in the training corpus,
    then that joint-feature is not included in the generated
    encoding.

:type labels: list
:param labels: A list of labels that should be used by the
    classifier.  If not specified, then the set of labels
    attested in ``train_toks`` will be used.

:param options: Extra parameters for the constructor, such as
    ``unseen_features`` and ``alwayson_features``.
r  r[   )	râ   r   rh   r¥   r  ró   rE  rD  r   r  s               r   r¤   Ú TypedMaxentFeatureEncoding.trainÆ  sÕ   € ð> ˆÜ“eˆÜœCÓ ˆã$‰JˆCÞ˜%Ó-Ü Ð!6¸Ñ!>Ó?Ð?Ø�O‰O˜EÔ"ð  #Ÿy™yž{‘�Ü˜“:¤#¤u Ó-Ü ›:�Dð ˜T�kÓ" aÑ'Ó"Ø ˜Ñ%¨Õ5Ø UÐ+°7Õ:Ü69¸'³l˜ tÐ 2Ó3ó  +ñ %ð" ‰>Ø ˆFÙ�6Ñ. gÑ.Ð.r!   r  r  r  r  rJ   r!   r   r@  r@    s7   † ñ6ôp/(òbò@/ò2òð ó5/ó ó5/r!   r@  c                 ó¦  • UR                  SS5        [        U5      nUc  [        R                  XS9n[	        US5      (       d  [        S5      eSUR                  -  n[        X5      n[        [        R                  " US:H  5      S   5      n[        R                  " [        U5      S5      n	U H  n
[        R                  Xš'   M     [        X)5      n[        R                  " U5      nAUS:”  a  [!        S	US   -  5        US
:”  a   [!        5         [!        S5        [!        S5          US
:”  aX  UR"                  =(       d    [%        X°5      nUR&                  =(       d    [)        X°5      nUR*                  n[!        SXýU4-  5        [-        X°U5      nU H  n
UU
==   S-  ss'   M     [        R                  " U5      nAUR/                  5       n	XœU-
  U-  -  n	UR1                  U	5        UR3                  X°5      (       a  OMÛ  US
:”  a)  [%        X°5      n[)        X°5      n[!        SUS SUS 35        U$ ! [4         a    [!        S5         NH  e = f)aj  
Train a new ``ConditionalExponentialClassifier``, using the given
training samples, using the Generalized Iterative Scaling
algorithm.  This ``ConditionalExponentialClassifier`` will encode
the model that maximizes entropy from all the models that are
empirically consistent with ``train_toks``.

:see: ``train_maxent_classifier()`` for parameter descriptions.
r�   éd   ©r$   r  zJThe GIS algorithm requires an encoding that defines C (e.g., GISEncoding).r4   r   Údú  ==> Training (%d iterations)rB   ú-      Iteration    Log Likelihood    Accuracyú-      ---------------------------------------ú     %9d    %14.5f    %9.3fr[   ú*      Training stopped: keyboard interruptú         Final    ú14.5fú    ú9.3f)Ú
setdefaultr   r  r¤   rz   rž   r  Úcalculate_empirical_fcountrâ   ÚnumpyÚnonzeroÚzerosr   ÚNINFÚ ConditionalExponentialClassifierÚlog2re   Úllr   Úaccr   ÚiterÚcalculate_estimated_fcountr   r)   ÚcheckÚKeyboardInterrupt)r§   rœ   r   r$   r©   ÚcutoffcheckerÚCinvÚempirical_fcountÚ
unattestedr   rx   Ú
classifierÚlog_empirical_fcountrd  re  ÚiternumÚestimated_fcountÚlog_estimated_fcounts                     r   r¡   r¡     sZ  € ð ×Ñ�z 3Ô'Ü! 'Ó*€Mð ÑÜ×$Ñ$ ZÐ$Ð?ˆä�8˜S×!Ñ!Üð-ó
ð 	
ð �—‘Ñ€Dô 2°*ÓGÐô ”U—]’]Ð#3°qÑ#8Ó9¸!Ñ<Ó=€Jô �kŠkœ#Ð.Ó/°Ó5€GÛˆÜ—z‘zˆ‹ñ ä1°(ÓD€Jô !Ÿ:š:Ð&6Ó7ÐØàˆqƒyÜÐ.°¸Ñ1DÑDÔEØˆqƒyÜŒÜÐ=Ô>ÜÐ=Ô>ð ØØ�q‹yØ"×%Ñ%×O¬¸
Ó)O�Ø#×'Ñ'×K¬8°JÓ+K�Ø'×,Ñ,�ÜÐ3°wÀCÐ6HÑHÔIô  :Ø¨ó Ðó
 "�Ø  Ó%¨Ñ*Õ%ñ "ä#(§:¢:Ð.>Ó#?Ð Ø ð !×(Ñ(Ó*ˆGØÐ/CÑCÀtÑKÑKˆGØ×"Ñ" 7Ô+ð ×"Ñ" :×:Ñ:Øñ5 ðB ˆqƒyÜ˜JÓ3ˆÜ�zÓ.ˆÜÐ" 2 e *¨D°°T°
Ð;Ô<ð Ðøô ó <ÜÐ:Ö;ðØús   Ä*CH7 ÈH7 È7IÉIc                 ó²   • [         R                  " UR                  5       S5      nU  H+  u  p4UR                  X45       H  u  pVX%==   U-  ss'   M     M-     U$ ©NrR  )r^  r`  r   r7   )r§   r   Úfcountr  r9   ÚindexÚvals          r   r]  r]  f  sM   € Ü�[Š[˜Ÿ™Ó*¨CÓ0€Fã ‰
ˆØ"Ÿ/™/¨#Ö5‰JˆEØ‹M˜SÑ �Mó 6ñ !ð €Mr!   c                 ó(  • [         R                  " UR                  5       S5      nU Hf  u  pEU R                  U5      nUR	                  5        H<  nUR                  U5      nUR                  XE5       H  u  p‰X8==   Xy-  -  ss'   M     M>     Mh     U$ rt  )r^  r`  r   r.   rd   r`   r7   )
rn  r§   r   ru  r  r9   ra   r`   rx   rì   s
             r   rg  rg  p  s}   € Ü�[Š[˜Ÿ™Ó*¨CÓ0€Fã ‰
ˆØ×(Ñ(¨Ó-ˆØ—]‘]–_ˆEØ—:‘:˜eÓ$ˆDØ%Ÿ_™_¨SÖ8‘	�Ø“˜t™{Ñ*•ó 9ó %ñ !ð €Mr!   c           
      óŒ  • UR                  SS5        [        U5      nUc  [        R                  XS9n[	        X5      [        U 5      -  n[        X5      n[        R                  " [        XwR                  S9S5      n[        R                  " U[        U5      S45      n	[        [        R                  " US:H  5      S   5      n
[        R                  " [        U5      S5      nU
 H  n[        R                  X¼'   M     [!        X+5      nUS:”  a  [#        SUS   -  5        US	:”  a   [#        5         [#        S
5        [#        S5          US	:”  aX  UR$                  =(       d    ['        XÐ5      nUR(                  =(       d    [+        XÐ5      nUR,                  n[#        SUXï4-  5        [/        U UU
UUUU	U5      nUR1                  5       nUU-  nUR3                  U5        UR5                  XÐ5      (       a  OM¯  US	:”  a)  ['        XÐ5      n[+        XÐ5      n[#        SUS SUS 35        U$ ! [6         a    [#        S5         NH  e = f)af  
Train a new ``ConditionalExponentialClassifier``, using the given
training samples, using the Improved Iterative Scaling algorithm.
This ``ConditionalExponentialClassifier`` will encode the model
that maximizes entropy from all the models that are empirically
consistent with ``train_toks``.

:see: ``train_maxent_classifier()`` for parameter descriptions.
r�   rP  rQ  )rD   rR  r[   r   rS  rB   rT  rU  rV  rW  rX  rY  rZ  r[  )r\  r   rÞ   r¤   r]  r   Úcalculate_nfmapr^  Úarrayrc   Ú__getitem__Úreshaperâ   r_  r`  ra  rb  re   rd  r   re  r   rf  Úcalculate_deltasr   r)   rh  ri  )r§   rœ   r   r$   r©   rj  Úempirical_ffreqÚnfmapÚnfarrayÚnftransposerm  r   rx   rn  rd  re  rp  Údeltass                     r   r    r    ‚  s6  € ð ×Ñ�z 3Ô'Ü! 'Ó*€Mð ÑÜ.×4Ñ4°ZÐ4ÐOˆô 1°ÓFÌÈZËÑX€Oô ˜JÓ1€EÜ�kŠkœ& ×,=Ñ,=Ñ>ÀÓD€GÜ—-’- ¬#¨g«,¸Ð):Ó;€Kô ”U—]’] ?°aÑ#7Ó8¸Ñ;Ó<€Jô �kŠkœ#˜oÓ.°Ó4€GÛˆÜ—z‘zˆ‹ñ ä1°(ÓD€JàˆqƒyÜÐ.°¸Ñ1DÑDÔEØˆqƒyÜŒÜÐ=Ô>ÜÐ=Ô>ð ØØ�q‹yØ"×%Ñ%×O¬¸
Ó)O�Ø#×'Ñ'×K¬8°JÓ+K�Ø'×,Ñ,�ÜÐ3°wÀÐ6HÑHÔIô &ØØØØØØØØó	ˆFð !×(Ñ(Ó*ˆGØ�vÑˆGØ×"Ñ" 7Ô+ð ×"Ñ" :×:Ñ:Øñ5 ðB ˆqƒyÜ˜JÓ3ˆÜ�zÓ.ˆÜÐ" 2 e *¨D°°T°
Ð;Ô<ð Ðøô ó <ÜÐ:Ö;ðØús   Å	B-H* Ç7H* È*IÉIc                 ó  • [        5       nU  HL  u  p4UR                  5        H3  nUR                  [        S UR	                  X55       5       5      5        M5     MN     [        U5       VVs0 s H  u  pgXv_M	     snn$ s  snnf )a·  
Construct a map that can be used to compress ``nf`` (which is
typically sparse).

*nf(feature_vector)* is the sum of the feature values for
*feature_vector*.

This represents the number of features that are active for a
given labeled text.  This method finds all values of *nf(t)*
that are attested for at least one token in the given list of
training tokens; and constructs a dictionary mapping these
attested values to a continuous range *0...N*.  For example,
if the only values of *nf()* that were attested were 3, 5, and
7, then ``_nfmap`` might return the dictionary ``{3:0, 5:1, 7:2}``.

:return: A map that can be used to compress ``nf`` to a dense
    vector.
:rtype: dict(int -> int)
c              3   ó*   #   • U  H	  u  pUv •  M     g 7fr#   rJ   ©rK   Úidrw  s      r   rM   Ú"calculate_nfmap.<locals>.<genexpr>ö  s   é € ÐKÒ/J¡) 2�#Ò/Jùr%  )râ   r$   r  r&  r7   ri   )r§   r   Únfsetr  Ú_r9   rp   Únfs           r   rz  rz  Þ  sm   € ô* ‹E€EÛ‰ˆØ—_‘_Ö&ˆEØ�I‰I”cÑK¨x¯©¸sÔ/JÓKÓKÖLó 'ñ ô "+¨5Ô!1Ô2Ò!1‘g�qˆBŠEÑ!1Ò2Ð2ùÓ2s   Á+A=c           	      ó|  • SnSn	[         R                  " UR                  5       S5      n
[         R                  " [	        U5      UR                  5       4S5      nU  H  u  pÍUR                  U5      nUR                  5        HU  nUR                  XÍ5      n[        S U 5       5      nU H)  u  nnX´U   U4==   UR                  U5      U-  -  ss'   M+     MW     M�     U[	        U 5      -  n[        U	5       HÀ  n[         R                  " XZ5      nSU-  nUU-  n[         R                  " UU-  SS9n[         R                  " UU-  SS9nU H  nUU==   S-  ss'   M     X£U-
  U* -  -  n
[         R                  " [        UU-
  5      5      [         R                  " [        U
5      5      -  nUU:  d  M¾  U
s  $    U
$ )	aW	  
Calculate the update values for the classifier weights for
this iteration of IIS.  These update weights are the value of
``delta`` that solves the equation::

  ffreq_empirical[i]
         =
  SUM[fs,l] (classifier.prob_classify(fs).prob(l) *
             feature_vector(fs,l)[i] *
             exp(delta[i] * nf(feature_vector(fs,l))))

Where:
    - *(fs,l)* is a (featureset, label) tuple from ``train_toks``
    - *feature_vector(fs,l)* = ``encoding.encode(fs,l)``
    - *nf(vector)* = ``sum([val for (id,val) in vector])``

This method uses Newton's method to solve this equation for
*delta[i]*.  In particular, it starts with a guess of
``delta[i]`` = 1; and iteratively updates ``delta`` with:

| delta[i] -= (ffreq_empirical[i] - sum1[i])/(-sum2[i])

until convergence, where *sum1* and *sum2* are defined as:

|    sum1[i](delta) = SUM[fs,l] f[i](fs,l,delta)
|    sum2[i](delta) = SUM[fs,l] (f[i](fs,l,delta).nf(feature_vector(fs,l)))
|    f[i](fs,l,delta) = (classifier.prob_classify(fs).prob(l) .
|                        feature_vector(fs,l)[i] .
|                        exp(delta[i] . nf(feature_vector(fs,l))))

Note that *sum1* and *sum2* depend on ``delta``; so they need
to be re-computed each iteration.

The variables ``nfmap``, ``nfarray``, and ``nftranspose`` are
used to generate a dense encoding for *nf(ltext)*.  This
allows ``_deltas`` to calculate *sum1* and *sum2* using
matrices, which yields a significant performance improvement.

:param train_toks: The set of training tokens.
:type train_toks: list(tuple(dict, str))
:param classifier: The current classifier.
:type classifier: ClassifierI
:param ffreq_empirical: An array containing the empirical
    frequency for each feature.  The *i*\ th element of this
    array is the empirical frequency for feature *i*.
:type ffreq_empirical: sequence of float
:param unattested: An array that is 1 for features that are
    not attested in the training data; and 0 for features that
    are attested.  In other words, ``unattested[i]==0`` iff
    ``ffreq_empirical[i]==0``.
:type unattested: sequence of int
:param nfmap: A map that can be used to compress ``nf`` to a dense
    vector.
:type nfmap: dict(int -> int)
:param nfarray: An array that can be used to uncompress ``nf``
    from a dense vector.
:type nfarray: array(float)
:param nftranspose: The transpose of ``nfarray``
:type nftranspose: array(float)
gê-�™—q=i,  rR  c              3   ó*   #   • U  H	  u  pUv •  M     g 7fr#   rJ   r†  s      r   rM   Ú#calculate_deltas.<locals>.<genexpr>T  s   é € Ð9ª.™Y˜b•Sª.ùr%  rB   r   )Úaxisr[   )r^  Úonesr   r`  r   r.   r$   r7   r&  r`   r|   ÚouterrS   )r§   rn  rm  Úffreq_empiricalr€  r�  r‚  r   ÚNEWTON_CONVERGEÚ
MAX_NEWTONrƒ  ÚAr  r9   Údistr:   r‹  r‡  rw  ÚrangenumÚnf_deltaÚexp_nf_deltaÚnf_exp_nf_deltaÚsum1Úsum2rx   Ún_errors                              r   r~  r~  ú  s   € ðR €OØ€Jä�ZŠZ˜Ÿ™Ó)¨3Ó/€Fô
 	�Š”S˜“Z §¡Ó!2Ð3°SÓ9€Aã ‰
ˆØ×'Ñ'¨Ó,ˆà—_‘_Ö&ˆEà%Ÿ_™_¨SÓ8ˆNäÑ9©.Ó9Ó9ˆBã)‘��CØ˜‘)˜R�-Ó  D§I¡I¨eÓ$4°sÑ$:Ñ:Õ ó *ó 'ñ !ð ŒˆZ‹Ñ€Aô ˜*Ö%ˆÜ—;’;˜wÓ/ˆØ˜(‘{ˆØ%¨Ñ4ˆÜ�yŠy˜¨Ñ)°Ñ2ˆÜ�yŠy˜¨1Ñ,°1Ñ5ˆó ˆCØ�‹I˜‰N�Iñ ð 	 TÑ)¨d¨UÑ2Ñ2ˆô —)’)œC °$Ñ 6Ó7Ó8¼5¿9º9ÄSÈÃ[Ó;QÑQˆØ�_Õ$ØŠMñ# &ð& €Mr!   c           	      ó  • SnSnSU;   a  US   nSU;   a  US   nUc(  UR                  SS5      n[        R                  XUSS9nOUb  [        S5      e [        R
                  " S	S
9u  pš[        U
S5       n[        XX¶US9  SSS5        [        R                  " U	5        / nU/ SQ-  nU(       a  US/-  nU(       d  US/-  nU(       a	  SUS-  -  nOSnUSSU-  S/-  nUS:  a  US/-  nSU;   a  USSUS   -  /-  nSU;   a  USS[        US   5      -  /-  n[        US5      (       a  US/-  nUSU
/-  n[        U5      n [        R                  " U
5        [!        XòR#                  5       U5      nU[$        R&                  " [$        R(                  5      -  n[+        UU5      $ ! , (       d  f       GN-= f! [        [        4 a  n[        SU-  5      UeSnAff = f! [         a  n[        S U
 S!U 35         SnAN¦SnAff = f)"a{  
Train a new ``ConditionalExponentialClassifier``, using the given
training samples, using the external ``megam`` library.  This
``ConditionalExponentialClassifier`` will encode the model that
maximizes entropy from all the models that are empirically
consistent with ``train_toks``.

:see: ``train_maxent_classifier()`` for parameter descriptions.
:see: ``nltk.classify.megam``
Tr—   r˜   Nr•   r   )r$   rê   z$Specify encoding or labels, not bothznltk-©ÚprefixÚw)r—   r˜   z,Error while creating megam training file: %s)z-nobiasz-repeatÚ10z	-explicitz-fvalsr4   rB   z-lambdaz%.2fz-tuner¯   z-quietr�   z-maxirH   Úll_deltaz-dppÚcostz-multilabelÚ
multiclasszWarning: unable to delete z: )ÚgetrÞ   r¤   r¥   ÚtempfileÚmkstempÚopenr   ÚosÚcloseÚOSErrorrS   rz   r   Úremovere   r   r   r^  rc  Úer   )r§   rœ   r   r$   r�   rª   r—   r˜   r•   ÚfdÚtrainfile_nameÚ	trainfiler®  r  Úinv_varianceÚstdoutr   s                    r   r¢   r¢   �  sc  € ð €HØ€IØ�VÓØ˜*Ñ%ˆØ�fÓØ˜;Ñ'ˆ	ð Ñð —z‘z .°!Ó4ˆÜ.×4Ñ4Ø¨VÀtð 5ð 
‰ð 
Ñ	ÜÐ?Ó@Ð@ðTÜ%×-Ò-°WÑ=ÑˆÜ�. #Ô&¨)ÜØ iÈiò÷ 'ô 	�Š�Œð
 €GØÒ+Ñ+€GÞØ�K�=Ñ ˆÞØ�H�:ÑˆÞð Ð1°1Ñ4Ñ4‰àˆØ�	˜6 LÑ0°'Ð:Ñ:€GØˆqƒyØ�H�:ÑˆØ�VÓØ�G˜T F¨:Ñ$6Ñ6Ð7Ñ7ˆØ�VÓð 	�F˜D¤3 v¨jÑ'9Ó#:Ñ:Ð;Ñ;ˆÜˆx˜× Ñ Ø�M�?Ñ"ˆØ�˜nÐ-Ñ-€GÜ˜Ó €FðBÜ
�	Š	�.Ô!ô
 " &¯/©/Ó*;¸XÓF€Gð Œu�zŠzœ%Ÿ'™'Ó"Ñ"€Gô ˜H gÓ.Ð.÷c 'Ö&ûô
 ”ZÐ ó TÜÐGÈ!ÑKÓLÐRSÐSûðTûôD ó BÜÐ*¨>Ð*:¸"¸Q¸CÐ@×AÑAûðBúsH   Á"F; Á7F)ÂF; ÅG" Æ)
F8Æ3F; Æ;GÇGÇGÇ"
HÇ,HÈHc                   ó$   • \ rS rSr\S 5       rSrg)r£   iÝ  c                 óâ  • UR                  SS5      nUR                  SS5      nUR                  SS 5      nUR                  SS 5      nUR                  SS5      nUR                  S	S5      nUR                  S
5      n	UR                  S5      n
U(       d  [        R                  XUS9n[        R                  " SSS9u  p¼[        R                  " SS9u  pÞ[        US5      n[        XU5        UR                  5         / nUR                  S/5        UR                  SU/5        U(       a  UR                  SSUS-  -  /5        U	(       a  UR                  SSU	-  /5        U
(       a  UR                  SS[        U
5      -  /5        UR                  SU/5        UR                  SU/5        US:  a  UR                  S/5        OUR                  S/5        [        U5        [        U5       n[        U5      nS S S 5        [        R                  " U5        [        R                  " U5        W[        R                   " [        R"                  5      -  nU " UU5      $ ! , (       d  f       Nj= f)Nr¨   Útao_lmvmrœ   r¯   r   r$   r�   r   r•   r�   r’   rQ  znltk-tadm-events-z.gz)r   Úsuffixznltk-tadm-weights-rŸ  r¡  z-monitorz-methodz-l2z%.6frB   z-max_itz%dz-fatolz
-events_inz-params_outz2>&1z-summary)r¦  r/  r¤   r§  r¨  r   r
   r«  ÚextendrS   r   r©  r	   rª  r­  r^  rc  r®  )r¦   r§   rª   r¨   rœ   r   r$   Úsigmar•   r�   r£  Útrainfile_fdr°  Úweightfile_fdÚweightfile_namer±  r  Ú
weightfiler   s                      r   r¤   ÚTadmMaxentClassifier.trainÞ  s  € à—J‘J˜{¨JÓ7ˆ	Ø—
‘
˜7 AÓ&ˆØ—:‘:˜j¨$Ó/ˆØ—‘˜H dÓ+ˆØ—
‘
Ð1°1Ó5ˆØ—z‘z .°!Ó4ˆØ—:‘:˜jÓ)ˆØ—:‘:˜mÓ,ˆö Ü5×;Ñ;Ø°ð <ð ˆHô (0×'7Ò'7Ø&¨uñ(
Ñ$ˆô *2×)9Ò)9ÐAUÑ)VÑ&ˆä% n°cÓ:ˆ	Ü˜
¨iÔ8Ø�‰ÔàˆØ�‰˜
�|Ô$Ø�‰˜	 9Ð-Ô.ÞØ�N‰N˜E 6¨E°1©HÑ#4Ð5Ô6ÞØ�N‰N˜I t¨h¡Ð7Ô8ÞØ�N‰N˜H f¬s°8«}Ñ&<Ð=Ô>Ø�‰˜ nÐ5Ô6Ø�‰˜ Ð7Ô8Ø�1‹9Ø�N‰N˜F˜8Õ$à�N‰N˜J˜<Ô(ä�'Ôä�/Ô" jÜ(¨Ó4ˆG÷ #ô 	�	Š	�.Ô!Ü
�	Š	�/Ô"ð 	”5—:’:œeŸg™gÓ&Ñ&ˆñ �8˜WÓ%Ð%÷ #Õ"ús   Ç0I É 
I.rJ   N)r°   r±   r²   r³   r¶   r¤   r·   rJ   r!   r   r£   r£   Ý  s   † Øñ5&ó ó5&r!   r£   c                 óR  • SS K nSSKJn  U" 5       n[        U  S35       nUR                  " [        [        UR                  UR                  U5      5      5      5      nS S S 5        [        U  S35       nUR                  U5      nS S S 5        [        U  S35       nUR                  U5      nS S S 5        [        U  S35       nUR                  U5      nS S S 5        WWWW4$ ! , (       d  f       NŒ= f! , (       d  f       Nu= f! , (       d  f       N^= f! , (       d  f       NG= f)Nr   )ÚMaxentDecoderú/weights.txtú/mapping.tabú/labels.txtú/alwayson.tab)r^  Únltk.tabdatarÀ  r©  r{  r{   ÚmapÚfloat64Útxt2listÚtupkey2dictÚ
tab2ivdict)	Útab_dirr^  rÀ  Úmdecr"  ÚwgtÚmpgÚlabÚaons	            r   Úload_maxent_paramsrÑ    sõ   € Ûå*á‹?€Dä	��	˜Ð&Ô	'¨1Ø�kŠkœ$œs 5§=¡=°$·-±-ÀÓ2BÓCÓDÓEˆ÷ 
(ô 
��	˜Ð&Ô	'¨1Ø×Ñ˜qÓ!ˆ÷ 
(ô 
��	˜Ð%Ô	&¨!Ø�m‰m˜AÓˆ÷ 
'ô 
��	˜Ð'Ô	(¨AØ�o‰o˜aÓ ˆ÷ 
)ð ��S˜#ÐÐ÷ 
(Õ	'ú÷ 
(Õ	'ú÷ 
'Õ	&ú÷ 
)Õ	(ús/    ?C%Á5C6ÂDÃDÃ%
C3Ã6
DÄ
DÄ
D&c           
      ó  • SSK Jn  SSKJn  SSKJn  U" 5       nU" U5      (       d  U" U5        [        SU 35        [        U S3S5       n	U	R                  UR                  [        [        U R                  5       5      5       5        S S S 5        [        U S3S5       n	U	R                  UR                  U5       5        S S S 5        [        U S	3S5       n	U	R                  UR                  U5       5        S S S 5        [        U S
3S5       n	U	R                  UR                  U5       5        S S S 5        g ! , (       d  f       Nº= f! , (       d  f       N’= f! , (       d  f       Nj= f! , (       d  f       g = f)Nr   )Úmkdir)Úisdir)ÚMaxentEncoderzSaving Maxent parameters in rÁ  r¡  rÂ  rÃ  rÄ  )rª  rÓ  Úos.pathrÔ  rÅ  rÕ  re   r©  ÚwriteÚlist2txtrÆ  ÚreprÚtolistÚtupdict2tabÚ
ivdict2tab)
rÍ  rÎ  rÏ  rÐ  rË  rÓ  rÔ  rÕ  Úmencr"  s
             r   Úsave_maxent_paramsrÞ  2  s"  € åÝå*á‹?€DÙ��>‰>ÙˆgŒä	Ð(¨¨	Ð
2Ô3ä	��	˜Ð&¨Ô	,°Ø	�‰�4—=‘=¤¤T¨3¯:©:«<Ó!8Ó9Ð:Ô<÷ 
-ä	��	˜Ð&¨Ô	,°Ø	�‰�4×#Ñ# CÓ(Ð)Ô+÷ 
-ä	��	˜Ð% sÔ	+¨qØ	�‰�4—=‘= Ó%Ð&Ô(÷ 
,ä	��	˜Ð'¨Ô	-°Ø	�‰�4—?‘? 3Ó'Ð(Ô*÷ 
.Ð	-÷ 
-Õ	,úç	,Õ	,úç	+Õ	+úç	-Õ	-ús0   Á>D>Â!"EÃ"E Ä"E1Ä>
EÅ
EÅ 
E.Å1
E?c                  óz   • SSK Jn   SSKJn  U " S5      n[	        U5      u  p4pV[        [        XTUS9U5      nU" US9$ )Nr   )Úfind)ÚClassifierBasedPOSTaggerz.taggers/maxent_treebank_pos_tagger_tab/english)rê   )rn  )Ú	nltk.datarà  Únltk.tag.sequentialrá  rÑ  r   rÞ   )rà  rá  rË  rÍ  rÎ  rÏ  rÐ  Úmcs           r   Úmaxent_pos_taggerrå  I  sE   € ÝÝ<áÐCÓD€GÜ+¨GÓ4Ñ€CˆcÜ	Ü# CÀÑDÀcó
€Bñ $¨rÑ2Ð2r!   c                  ó<   • SSK Jn   U " [        R                  5      ng )Nr   )Ú
names_demo)Únltk.classify.utilrç  r   r¤   )rç  rn  s     r   Údemoré  X  s   € Ý-áÔ,×2Ñ2Ó3�Jr!   Ú__main__)r¯   NN)r¯   NNr   )z/tmp)1r´   r^  ÚImportErrorrª  r§  Úcollectionsr   Únltk.classify.apir   Únltk.classify.megamr   r   r   Únltk.classify.tadmr   r	   r
   rè  r   r   r   râ  r   Únltk.probabilityr   Ú	nltk.utilr   Ú__docformat__r   rb  r¹   rË   rÞ   r  r/  r@  r¡   r]  rg  r    rz  r~  r¢   r£   rÑ  rÞ  rå  ré  r°   rJ   r!   r   Ú<module>ró     s:  ðñ,ðZ	Ûó 
Û Ý #å )ß QÑ Qß MÑ Mß FÑ FÝ 'Ý /Ý !à€ôJA�{ô JAð\ $4Ð  ÷F$ñ F$ôR,*Ð*@ô ,*ô^G/Ð"8ô G/ôT:DÐ-ô :Dôz5/Ð%@ô 5/ôpa/Ð!7ô a/ðT 04ô_òDò
ð& 04ôYòx3ò8{ðP KLôT/ôx7&Ð+ô 7&ò~ô,+ò.	3ò4ð ˆzÓÙ…Fð øðM1 ó 	Ùð	ús   „C" Ã"C+Ã*C+