
    Qd2                     V    d dl mZ  G d d          Zd Zedk    r e             dS dS )    )FreqDistc                   ^    e Zd ZdZddZd Zd Zd Z	 	 	 	 dd	Zd
 Z	d Z
d ZddZddZdS )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.
    Fc                    	
 t          |          t          |          k    rt          d          |rFt          |          
t          |          
fd}t          t	          ||z             |          nt          t	          ||z                       d t                    D             }fdD             	d}t          ||          D ]O\  }}	||                  ||         xx         dz  cc<   t          |	||                  ||                            }P| _        || _	        	| _
        || _        t          |          | _        t          	fdt          t                              D                       | _        d	S )
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    S N )v	ref_fdist
test_fdists    <lib/python3.11/site-packages/nltk/metrics/confusionmatrix.pykeyz%ConfusionMatrix.__init__.<locals>.key5   s    "1
1566    r   c                     i | ]\  }}||	S r	   r	   ).0ivals      r   
<dictcomp>z,ConfusionMatrix.__init__.<locals>.<dictcomp>=   s    <<<hq#3<<<r   c                 (    g | ]}d  D             S )c                     g | ]}d S )r   r	   )r   _s     r   
<listcomp>z7ConfusionMatrix.__init__.<locals>.<listcomp>.<listcomp>@   s    (((Aa(((r   r	   )r   r   valuess     r   r   z,ConfusionMatrix.__init__.<locals>.<listcomp>@   s(    999Q(((((999r   r      c              3   4   K   | ]}|         |         V  d S r   r	   )r   r   	confusions     r   	<genexpr>z+ConfusionMatrix.__init__.<locals>.<genexpr>Q   s+      HHIaLOHHHHHHr   N)len
ValueErrorr   sortedset	enumeratezipmax_values_indices
_confusion	_max_conf_totalsumrange_correct)self	referencetestsort_by_countr   indicesmax_confwgr   r   r   r   s            @@@@r   __init__zConfusionMatrix.__init__    s    y>>SYY&&?@@@  		3 ++I!$J7 7 7 7 7 7 C	D 011s;;;FFC	D 01122F =<)F*;*;<<< :999&999		4(( 	H 	HDAqgaj!'!*---2---8Ywqz%:71:%FGGHH #!)nnHHHHU3v;;5G5GHHHHHr   c                 f    |\  }}| j         |         }| j         |         }| j        |         |         S )z
        :return: The number of times that value ``li`` was expected and
        value ``lj`` was given.
        :rtype: int
        )r'   r(   )r.   li_lj_tupleliljr   js         r   __getitem__zConfusionMatrix.__getitem__S   s7     RM"M"q!!$$r   c                 (    d| j          d| j         dS )Nz<ConfusionMatrix: /z	 correct>)r-   r*   r.   s    r   __repr__zConfusionMatrix.__repr__^   s    JDMJJDKJJJJr   c                 *    |                                  S r   )pretty_formatr?   s    r   __str__zConfusionMatrix.__str__a   s    !!###r   TNc           	           j         } j        }|rt          | fd          }|r
|d|         }|rd |D             }n&d t          t	          |                    D             }t          d |D                       }dt          |          z   dz   }	|rd	}
d
}d}nAt	          t           j                            }
dt          |
          z   dz   }d|
dz
  z  dz   }d}t          |          D ]m}|d|z  dz   z  }|D ]X}||t	          |          z
  k    r5||||z
  t	          |          z                                |
dz             z  }M|d|
dz   z  z  }Y|dz  }n|d	                    d|z  d|
dz   t	          |          z  z            z  }t          ||          D ]\  }} j        |         }||	|z  z  }|D ]} j        |         }||         |         dk    r||z  }n6|r ||d||         |         z   j        z  z  z  }n||||         |         z  z  }||k    r4|                    d          }|d|         dz   ||dz   d         z   dz   }|dz  }|dz  }|d	                    d|z  d|
dz   t	          |          z  z            z  }|dz  }|s'|dz  }t          |          D ]\  }}|d|dz   |fz  z  }|S )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?
        c                 P    t          j        j        |                              S r   r+   r(   r'   r
   r.   s    r   <lambda>z/ConfusionMatrix.pretty_format.<locals>.<lambda>~   s     s4?4=;K+L'M'M&M r   r   Nc                     g | ]}d |z  S )z%sr	   r   r   s     r   r   z1ConfusionMatrix.pretty_format.<locals>.<listcomp>   s    :::CTCZ:::r   c                 2    g | ]}t          |d z             S )r   )str)r   ns     r   r   z1ConfusionMatrix.pretty_format.<locals>.<listcomp>   s"    DDDASQZZDDDr   c              3   4   K   | ]}t          |          V  d S r   r   rJ   s     r   r   z0ConfusionMatrix.pretty_format.<locals>.<genexpr>   s(      99Cs3xx999999r   %zs |    z%5.1f%%z     .d r   . z |z |
z	{}-+-{}+
-r   g      Y@<>z|
z(row = reference; col = test)
Value key:
z%6d: %s
)r(   r&   r!   r,   r   r%   reprr)   rjustformatr$   r'   r*   rfindr#   )r.   show_percentsvalues_in_charttruncater1   r   r   value_stringsvaluelenvalue_formatentrylenentry_formatzerostrsr   r   r9   r:   r;   	prevspacevalues   `                    r   rB   zConfusionMatrix.pretty_formatd   s   * O	 	MMMM  F  	'IXI&F 	E::6:::MMDDs6{{1C1CDDDM 99=99999T(^^+f4 	1H$LGG4//00Hh/#5LX\*S0G x 	 	A#.D((A$ . .3s88+++Q\CHH45;;HqLIIIAA1--AAKAA 	
\  xAV8T1UVVV =&11 	 	GCb!A##A  M"%Q<?a''LAA" 81a)@4;)NOOAA	!Q77A66 !I*9*+a	A.@@3FAAHAAJAA 	
\  xAV8T1UVVV 	
.. 	2A%f-- 2 25[AE5>11r   c                     | j         }d}t          t          t          |          dz
                      }dt          |          z   dz   }t          t          |                    D ]}|||||         fz  z  }|S )NrY   r   z  %zd: %s
)r&   r   rZ   r,   )r.   r   rL   indexlen
key_formatr   s         r   r   zConfusionMatrix.key   s}    tCKK!O,,--T(^^+i7
s6{{## 	/ 	/A:F1I..CC
r   c                 v      f         }t           fd j        D                       }|dk    rdS ||z  S )a  Given 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
        c              3   ,   K   | ]}|f         V  d S r   r	   )r   
pred_valuer.   ri   s     r   r   z)ConfusionMatrix.recall.<locals>.<genexpr>   s-      KK
D
*+KKKKKKr   r           r+   r&   )r.   ri   TPTP_FNs   ``  r   recallzConfusionMatrix.recall   S     %,KKKKKdlKKKKKA::3Ezr   c                 v      f         }t           fd j        D                       }|dk    rdS ||z  S )a  Given 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
        c              3   ,   K   | ]}|f         V  d S r   r	   )r   
real_valuer.   ri   s     r   r   z,ConfusionMatrix.precision.<locals>.<genexpr>   s-      KK
DU*+KKKKKKr   r   rp   rq   )r.   ri   rr   TP_FPs   ``  r   	precisionzConfusionMatrix.precision   ru   r         ?c                     |                      |          }|                     |          }|dk    s|dk    rdS d||z  d|z
  |z  z   z  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
        rp   g      ?r   )rz   rt   )r.   ri   alphaprs        r   	f_measurezConfusionMatrix.f_measure   sX    2 NN5!!KK88qCxx3eai1u9/122r   c                 z     j         }|rt          | fd          }|r
|d|         }t          t          d |D                       d          }d|dz
  z   dd|z   d	}|D ]U}||d
| d                     |          dd                     |          dd                     ||          ddz  }V|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
        <BLANKLINE>

        :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
        c                 P    t          j        j        |                              S r   rF   rG   s    r   rH   z*ConfusionMatrix.evaluate.<locals>.<lambda><  s!    s4?4=QRCS3T/U/U.U r   r   Nc              3   4   K   | ]}t          |          V  d S r   rO   )r   tags     r   r   z+ConfusionMatrix.evaluate.<locals>.<genexpr>@  s(       : :cS : : : : : :r      rS   z"Tag | Prec.  | Recall | F-measure
rV   z -+--------+--------+-----------
rX   z | z<6.4f)r}   z.4f
)r&   r!   r%   rz   rt   r   )r.   r}   r`   r1   tagstag_column_lenrg   r   s   `       r   evaluatezConfusionMatrix.evaluate  sH   @ |  	W$$U$U$U$UVVVD 	#		?DS : :T : : :::A>> nq() G G^#G G G 	
  	 	C < <- < <>>#&&1< <;;s##.< < >>#U>33;< < <AA r   )F)FTNF)r{   )r{   NF)__name__
__module____qualname____doc__r6   r<   r@   rC   rB   r   rt   rz   r   r   r	   r   r   r   r      s         $1I 1I 1I 1If	% 	% 	%K K K$ $ $
 ] ] ] ]~    ,  ,3 3 3 3>9 9 9 9 9 9r   r   c                     d                                 } d                                 }t          d|            t          d|           t          d           t          t          | |                     t          t          | |                              d                     t          t          | |                              d                     d S )	Nz DET NN VB DET JJ NN NN IN DET NNz DET VB VB DET NN NN NN IN DET NNzReference =z	Test    =zConfusion matrix:T)r1   VB)splitprintr   rB   rt   )r/   r0   s     r   demor   T  s    288::I-3355D	-###	+t	
	/)T
*
*+++	/)T
*
*
8
8t
8
L
LMMM	/)T
*
*
1
1$
7
788888r   __main__N)nltk.probabilityr   r   r   r   r	   r   r   <module>r      s}    & % % % % %D D D D D D D DN
	9 	9 	9 zDFFFFF r   