JL i1DddlmZGddZdZedk(reyy))FreqDistc\eZdZdZd dZdZdZdZ ddZdZ d Z d Z dd Z dd Z y)ConfusionMatrixa The confusion matrix between a list of reference values and a corresponding list of test values. Entry *[r,t]* of this matrix is a count of the number of times that the reference value *r* corresponds to the test value *t*. E.g.: >>> from nltk.metrics import ConfusionMatrix >>> ref = 'DET NN VB DET JJ NN NN IN DET NN'.split() >>> test = 'DET VB VB DET NN NN NN IN DET NN'.split() >>> cm = ConfusionMatrix(ref, test) >>> print(cm['NN', 'NN']) 3 Note that the diagonal entries *Ri=Tj* of this matrix corresponds to correct values; and the off-diagonal entries correspond to incorrect values. c t|t|k7r td|r6t|t|fd}tt ||z|}ntt ||z}t |Dcic]\}}|| }}}|D cgc]} |D cgc]} dc} c} d} t ||D]3\} } || || xxdz cc<t| || || } 5||_||_ |_ | |_ t||_ t fdtt|D|_ycc}}wcc} wcc} w)a Construct a new confusion matrix from a list of reference values and a corresponding list of test values. :type reference: list :param reference: An ordered list of reference values. :type test: list :param test: A list of values to compare against the corresponding reference values. :raise ValueError: If ``reference`` and ``length`` do not have the same length. z Lists must have the same length.c||z SN)v ref_fdist test_fdists b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/metrics/confusionmatrix.pykeyz%ConfusionMatrix.__init__..key5s"1 1 566rrc3.K|] }||ywrr ).0i confusions r z+ConfusionMatrix.__init__..QsHIaLOHsN)len ValueErrorrsortedset enumeratezipmax_values_indices _confusion _max_conf_totalsumrange_correct)self referencetest sort_by_countrvaluesrvalindices_max_confwgrr r s @@@r __init__zConfusionMatrix.__init__ sV y>SY &?@ @  +I!$J 7C D 01s;FC D 012F+4F*;)r%r"r&s r __repr__zConfusionMatrix.__repr__^s#DMM?!DKK= JJrc"|jSr) pretty_formatr:s r __str__zConfusionMatrix.__str__as!!##rNc j}j}|rt|fd}|r|d|}|r|Dcgc]}d|z }}n-tt |D cgc]} t | dz}} t d|D} dt| zdz} |rd } d } d }n:t tj} dt| zd z} d | dz zdz}d}t| D]_}|d | zdzz }|D]H}|| t |z k\r*|||| z t |zj| dzz }>|d | dzzz }J|dz }a|djd| zd| dzt |zzz }t||D]\}}j|}|| |zz }|D]}j|}|||dk(r||z }n/|r|| d|||zjz zz }n|| |||zz }||k(r&|jd }|d|dz||dzdzdz}}|d z }|dz }|djd| zd| dzt |zzz }|dz }|s%|dz }t|D]\}}|d|dz|fzz }|Scc}wcc} w)a :return: A multi-line string representation of this confusion matrix. :type truncate: int :param truncate: If specified, then only show the specified number of values. Any sorting (e.g., sort_by_count) will be performed before truncation. :param sort_by_count: If true, then sort by the count of each label in the reference data. I.e., labels that occur more frequently in the reference label will be towards the left edge of the matrix, and labels that occur less frequently will be towards the right edge. @todo: add marginals? cPtjj| Srr#r rr r&s r z/ConfusionMatrix.pretty_format..~s!s4??4==;K+L'M&MrrNz%src32K|]}t|ywrr)rr+s r rz0ConfusionMatrix.pretty_format..s9Cs3x9%zs | z%5.1f%%z .d .z |z | z {}-+-{}+ -rgY@<>z| z(row = reference; col = test) Value key: z%6d: %s )r rrr$rstrrreprr!rjustformatrrr"rfindr)r& show_percentsvalues_in_charttruncater)rr*r+ value_stringsnvaluelen value_formatentrylen entry_formatzerostrsrr4r5r6 prevspacevalues` r r=zConfusionMatrix.pretty_formatds1*OO  MF IX&F 39:CTCZ:M:16s6{1CDASQZDMD9=99T(^+f4 H$LG4/0Hh/#5LX\*S0G x A #.D( (A$ .3s8++Q\CH45;;HqLIIA1 --A  . KA  \ xAV8T1U VV=&1 GC b!A # #A MM"%Q<?a'LA"1a)@4;;)NOOA ! Q77A6 ! I*9 +a A .@@3FAHA  JA! & \ xAV8T1U VV ..  A%f- 25[AE5>11 2y;Ds JJc |j}d}ttt|dz }dt|zdz}|djt t|Dcgc] }||||fzc}z }|Scc}w)NrPrz %zd: %s rL)rrrRjoinr$)r&r*rQindexlen key_formatrs r rzConfusionMatrix.keysytCK!O,-T(^+i7  rwwU3v;=OP a^3PQQ Qs"A> chf}tfdjD}|dk(ry||z S)aGiven a value in the confusion matrix, return the recall that corresponds to this value. The recall is defined as: - *r* = true positive / (true positive + false positive) and can loosely be considered the ratio of how often ``value`` was predicted correctly relative to how often ``value`` was the true result. :param value: value used in the ConfusionMatrix :return: the recall corresponding to ``value``. :rtype: float c3,K|] }|f ywrr )r pred_valuer&rbs r rz)ConfusionMatrix.recall..sK D *+Krr#r)r&rbTPTP_FNs`` r recallzConfusionMatrix.recall;%, KdllKK A:Ezrchf}tfdjD}|dk(ry||z S)aGiven a value in the confusion matrix, return the precision that corresponds to this value. The precision is defined as: - *p* = true positive / (true positive + false negative) and can loosely be considered the ratio of how often ``value`` was predicted correctly relative to the number of predictions for ``value``. :param value: value used in the ConfusionMatrix :return: the precision corresponding to ``value``. :rtype: float c3,K|] }|f ywrr )r real_valuer&rbs r rz,ConfusionMatrix.precision..sK DU*+Krjrrkrl)r&rbrmTP_FPs`` r precisionzConfusionMatrix.precisionrprc~|j|}|j|}|dk(s|dk(ryd||z d|z |z zz S)ao Given a value used in the confusion matrix, return the f-measure that corresponds to this value. The f-measure is the harmonic mean of the ``precision`` and ``recall``, weighted by ``alpha``. In particular, given the precision *p* and recall *r* defined by: - *p* = true positive / (true positive + false negative) - *r* = true positive / (true positive + false positive) The f-measure is: - *1/(alpha/p + (1-alpha)/r)* With ``alpha = 0.5``, this reduces to: - *2pr / (p + r)* :param value: value used in the ConfusionMatrix :param alpha: Ratio of the cost of false negative compared to false positives. Defaults to 0.5, where the costs are equal. :type alpha: float :return: the F-measure corresponding to ``value``. :rtype: float rkg?r)ruro)r&rbalphaprs r f_measurezConfusionMatrix.f_measuresL2 NN5 ! KK  8qCxeai1u9/122rc Jj}|rt|fd}|r|d|}ttd|Dd}d|dz zdd|zd }|D]J}||d |d d j|d d j |d d j ||ddz }L|S)aG Tabulate the **recall**, **precision** and **f-measure** for each value in this confusion matrix. >>> reference = "DET NN VB DET JJ NN NN IN DET NN".split() >>> test = "DET VB VB DET NN NN NN IN DET NN".split() >>> cm = ConfusionMatrix(reference, test) >>> print(cm.evaluate()) Tag | Prec. | Recall | F-measure ----+--------+--------+----------- DET | 1.0000 | 1.0000 | 1.0000 IN | 1.0000 | 1.0000 | 1.0000 JJ | 0.0000 | 0.0000 | 0.0000 NN | 0.7500 | 0.7500 | 0.7500 VB | 0.5000 | 1.0000 | 0.6667 :param alpha: Ratio of the cost of false negative compared to false positives, as used in the f-measure computation. Defaults to 0.5, where the costs are equal. :type alpha: float :param truncate: If specified, then only show the specified number of values. Any sorting (e.g., sort_by_count) will be performed before truncation. Defaults to None :type truncate: int, optional :param sort_by_count: Whether to sort the outputs on frequency in the reference label. Defaults to False. :type sort_by_count: bool, optional :return: A tabulated recall, precision and f-measure string :rtype: str cPtjj| SrrArBs r rCz*ConfusionMatrix.evaluate..:s"s4??4==QRCS3T/U.UrrNc32K|]}t|ywrrE)rtags r rz+ConfusionMatrix.evaluate..>s :cS :rFrJz"Tag | Prec. | Recall | F-measure rMz -+--------+--------+----------- rOrLz | z<6.4f)rwz.4f )rrrrurorz)r&rwrXr)tagstag_column_lenr`r~s` r evaluatezConfusionMatrix.evaluates@|| $$UVD  ?DS :T ::A>nq()**M^#$$E G  C q(()>>#&u-S;;s#E*#>>#U>3C8< A r)F)FTNF)?)rNF)__name__ __module__ __qualname____doc__r1r7r;r>r=rrorurzrr rr rr sL$1If %K$  ]~,,3>9rrcFdj}dj}td|td|tdtt||tt||jdtt||j dy) Nz DET NN VB DET JJ NN NN IN DET NNz DET VB VB DET NN NN NN IN DET NNz Reference =z Test =zConfusion matrix:T)r)VB)splitprintrr=ro)r'r(s r demorRs288:I - 3 3 5D -# +t  /)T *+ /)T * 8 8t 8 LM /)T * 1 1$ 78r__main__N)nltk.probabilityrrrrr rr rs0&BBJ 9 zFr