U à€C^³Wã@s–ddlmZmZmZddlZddlmZmZddl m Z Gdd„de ƒZ Gdd „d e ƒZ Gd d „d e ƒZd d „Zdd„Zdd„Zddd„Zdd„ZdS)é)ÚdivisionÚprint_functionÚunicode_literalsNé)Útags_to_entitiesÚ GoldParse)ÚErrorsc@sDeZdZdZdd„Zdd„Zedd„ƒZedd „ƒZed d „ƒZ d S) ÚPRFScorez( A precision / recall / F score cCsd|_d|_d|_dS)Nr)ÚtpÚfpÚfn©Úself©rú//tmp/pip-install-6_kvzl1k/spacy/spacy/scorer.pyÚ__init__szPRFScore.__init__cCsH|jt| |¡ƒ7_|jt||ƒ7_|jt||ƒ7_dS©N)r ÚlenÚ intersectionr r ©rZcandÚgoldrrrÚ score_setszPRFScore.score_setcCs|j|j|jdS©Nç0Žä.ÿ++)r r r rrrÚ precisionszPRFScore.precisioncCs|j|j|jdSr)r r r rrrÚrecallszPRFScore.recallcCs$|j}|j}d||||dS)Nér)rr)rÚpÚrrrrÚfscore!szPRFScore.fscoreN) Ú__name__Ú __module__Ú __qualname__Ú__doc__rrÚpropertyrrrrrrrr s  r c@s,eZdZdZdd„Zdd„Zedd„ƒZdS) Ú ROCAUCScorez An AUC ROC score. cCsg|_g|_d|_d|_dS)Ngr)ÚgoldsÚcandsÚ saved_scoreÚsaved_score_at_lenr rrrr-szROCAUCScore.__init__cCs|j |¡|j |¡dSr)r'Úappendr&rrrrr3s zROCAUCScore.score_setcCs^t|jƒ|jkr|jSzt|j|jƒ|_Wn tk rJtdƒ |_YnXt|jƒ|_|jS)NÚinf)rr&r)r(Ú_roc_auc_scorer'Ú ValueErrorÚfloatr rrrÚscore7s zROCAUCScore.scoreN)r r!r"r#rrr$r/rrrrr%(s r%c@s´eZdZdZd!dd„Zedd„ƒZedd „ƒZed d „ƒZed d „ƒZ edd„ƒZ edd„ƒZ edd„ƒZ edd„ƒZ edd„ƒZedd„ƒZedd„ƒZedd„ƒZd"dd „ZdS)#ÚScorerzCompute evaluation scores.FNcCsòtƒ|_tƒ|_tƒ|_tƒ|_tƒ|_tƒ|_tƒ|_tƒ|_ ||_ d|_ tƒ|_ d|_ d|_|rî|D]„\}}|dkrh|j dd¡|_ |j r–tƒ|_ |j dd¡sÌd|_|j dg¡D]}tƒ|j |<q¸qh|j dg¡D]}tƒ|j |<qÚqhdS)zèInitialize the Scorer. eval_punct (bool): Evaluate the dependency attachments to and from punctuation. RETURNS (Scorer): The newly created object. DOCS: https://spacy.io/api/scorer#init NFÚtextcatZpositive_labelZexclusive_classesTÚlabels)r ÚtokensZsbdÚ unlabelledÚlabelledÚdictÚlabelled_per_depÚtagsÚnerÚ ner_per_entsÚ eval_punctr1Útextcat_per_catÚtextcat_positive_labelÚtextcat_multilabelÚcfgÚgetr%)rr;ZpipelineÚnameÚmodelÚlabelrrrrHs2  zScorer.__init__cCs |jjdS)zhRETURNS (float): Part-of-speech tag accuracy (fine grained tags, i.e. `Token.tag`). éd)r8rr rrrÚtags_accmszScorer.tags_acccCs |jjdS)z'RETURNS (float): Tokenization accuracy.rD)r3rr rrrÚ token_acctszScorer.token_acccCs |jjdS)z-RETURNS (float): Unlabelled dependency score.rD)r4rr rrrÚuasysz Scorer.uascCs |jjdS)z+RETURNS (float): Labelled dependency score.rD)r5rr rrrÚlas~sz Scorer.lascCsdd„|j ¡DƒS)z5RETURNS (dict): Scores per dependency label. cSs0i|](\}}||jd|jd|jddœ“qS©rD)rrÚf©rrr©Ú.0ÚkÚvrrrÚ ‡sÿz'Scorer.las_per_type..)r7Úitemsr rrrÚ las_per_typeƒsþzScorer.las_per_typecCs |jjdS)z3RETURNS (float): Named entity accuracy (precision).rD)r9rr rrrÚents_pŒsz Scorer.ents_pcCs |jjdS)z0RETURNS (float): Named entity accuracy (recall).rD)r9rr rrrÚents_r‘sz Scorer.ents_rcCs |jjdS)z1RETURNS (float): Named entity accuracy (F-score).rD)r9rr rrrÚents_f–sz Scorer.ents_fcCsdd„|j ¡DƒS)z1RETURNS (dict): Scores per entity label. cSs0i|](\}}||jd|jd|jddœ“qSrIrKrLrrrrPŸsÿz(Scorer.ents_per_type..)r:rQr rrrÚ ents_per_type›sþzScorer.ents_per_typecCsn|jsB|jr|jjdStdd„|j ¡Dƒƒt|jƒddSttdd„|j ¡Dƒƒt|jƒddƒS)zÀRETURNS (float): f-score on positive label for binary exclusive, macro-averaged f-score for 3+ exclusive, macro-averaged AUC ROC score for multilabel (-1 if undefined) rDcSsg|]\}}|j‘qSr)r©rMrCr/rrrÚ °sz(Scorer.textcat_score..rcSsg|]\}}|j‘qSr)r/rWrrrrX¶séÿÿÿÿ) r>r=r1rÚsumr<rQrÚmaxr rrrÚ textcat_score¤s  ÿþÿ ÿýzScorer.textcat_scorecCs.|jsdd„|j ¡DƒSdd„|j ¡DƒS)z2RETURNS (dict): Scores per textcat label. cSs0i|](\}}||jd|jd|jddœ“qSrIrKrLrrrrPÀsÿz+Scorer.textcats_per_cat..cSs"i|]\}}|dt|jdƒi“qS)Z roc_auc_scorerY)r[r/rLrrrrPÄsÿ)r>r<rQr rrrÚtextcats_per_cat»sþþzScorer.textcats_per_catc Cs2|j|j|j|j|j|j|j|j|j|j |j dœ S)z“RETURNS (dict): All scores with keys `uas`, `las`, `ents_p`, `ents_r`, `ents_f`, `tags_acc`, `token_acc`, and `textcat_score`. © rGrHrRrSrTrUrVrErFr\r]r^r rrrÚscoresÉsõz Scorer.scores©rÚpunctc&sÜt|ƒt|ƒkr.t |tt|jŽƒ|jf¡}tƒ}i}tƒ}ttdd„|jDƒƒƒ}|jD]š\} } } } } }|  | | f¡| dkr\|   ¡|kr\|  | | |   ¡f¡|   ¡|j krÀt ƒ|j |   ¡<|   ¡|krÚtƒ||   ¡<||   ¡  | | |   ¡f¡q\tƒ}i}tƒ}|D�]8}|j  ¡�r"�q |j|j}|dk�rJ|jjd7_n |jjd7_|  ||jf¡|j  ¡|k�r |j  ¡�r |j|jj}|dk�s¨|dk�rÊ|jjd7_|jjd7_nz|  |||j  ¡f¡|j  ¡|j k�rt ƒ|j |j  ¡<|j  ¡|k�r$tƒ||j  ¡<||j  ¡  |||j  ¡f¡�q ddd„|jDƒk�r´tdd„|Dƒd d„|jDƒƒ}d d „|Dƒ}|D]:‰ˆ|jk�r®t ƒ|jˆ<|ˆ ‡fd d„|Dƒ¡�q’tƒ}d d „|Dƒ}|jD]ˆ}|j|j}|j|jd}|dk�s|dk�rD|jjd7_|j|j jd7_n*|  |j ||f¡||j   |j ||f¡�qè|j !¡D](\}}||k�r|| "||||¡�q||j "||¡|j# "||¡|j "||¡|j D],} |j |  "| $| tƒ¡| $| tƒ¡¡�qÖ|j "tdd„|Dƒƒtdd„|Dƒƒ¡t|jƒdk�r2t|j%ƒt|jƒk�r2t|jƒt|jƒk�r2t&|j|jj$d�}t&|j|jj$d�}|j'�rÈ|j( "t|j'gƒt|gƒ@t|j'gƒt|gƒ@¡|j%D]`} |j)�rú|j%|  "|j| |j| ¡n2|j%|  "t| gƒt|gƒ@t| gƒt|gƒ@¡�qÎn8t|j%ƒdk�rjt|j%ƒ}!t|jƒ}"t*t+j,j-|!|"d�ƒ‚|�rØdd„|jDƒ}#||D]"\}$}%} t.d|#|$| |#|%ƒ�qˆ||D]"\}$}%} t.d|#|$| |#|%ƒ�q´dS)a¼Update the evaluation scores from a single Doc / GoldParse pair. doc (Doc): The predicted annotations. gold (GoldParse): The correct annotations. verbose (bool): Print debugging information. punct_labels (tuple): Dependency labels for punctuation. Used to evaluate dependency attachments to punctuation if `eval_punct` is `True`. DOCS: https://spacy.io/api/scorer#score cSsg|] }|d‘qS©rYr)rMZannotrrrrXïsz Scorer.score..)NÚNrú-cSsg|] }|d‘qSrbr)rMÚtokenrrrrXscSsg|] }|d‘qS©rr©rMÚxrrrrXscSsg|] }|j‘qSr)Úlabel_)rMrNrrrrXscSsi|] }|tƒ“qSr©Úset©rMÚ ent_labelrrrrPsz Scorer.score..csg|]}|dˆkr|‘qSrfrrg©rmrrrXs cSsi|] }|tƒ“qSrrjrlrrrrP"scss|]}|dd…VqdS)Nrr©rMÚitemrrrÚ 9szScorer.score..r)Úkey)Ú model_labelsÚ eval_labelscSsg|] }|d‘qS)rrrorrrrXWsÚFÚM)/rrZfrom_annot_tuplesÚtupleÚzipZ orig_annotZcatsrkrÚaddÚlowerr7r Zorth_ÚisspaceZ cand_to_goldÚir3r r Ztag_Zdep_ÚstripÚheadr4r5Zentsr:ÚupdateÚstartÚendr9rirQrr8r@r<r[r=r1r>r-rZE162ÚformatÚprint)&rÚdocrÚverboseZ punct_labelsZ gold_depsZgold_deps_per_depZ gold_tagsZ gold_entsZid_ÚwordÚtagr~Údepr9Z cand_depsZcand_deps_per_depZ cand_tagsreZgold_iZ gold_headZ ent_labelsZ gold_per_entsZ cand_entsZ cand_per_entsÚentÚfirstÚlastrNrOZgoldcatZcandcatrCrsrtZ gold_wordsZw_idZh_idrrnrr/ÜsÞ ÿ     ÿ"  ÿ      ÿÿ ÿþýþ  ÿ ÿ   ÿz Scorer.score)FN)Fr`)r r!r"r#rr$rErFrGrHrRrSrTrUrVr\r]r_r/rrrrr0Es6 %            r0cCs6tt |¡ƒdkrttjƒ‚t||ƒ\}}}t||ƒS)a�Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores. Note: this implementation is restricted to the binary classification task Parameters ---------- y_true : array, shape = [n_samples] or [n_samples, n_classes] True binary labels or binary label indicators. The multiclass case expects shape = [n_samples] and labels with values in ``range(n_classes)``. y_score : array, shape = [n_samples] or [n_samples, n_classes] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). For binary y_true, y_score is supposed to be the score of the class with greater label. The multiclass case expects shape = [n_samples, n_classes] where the scores correspond to probability estimates. Returns ------- auc : float References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic `_ .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition Letters, 2006, 27(8):861-874. .. [3] `Analyzing a portion of the ROC curve. McClish, 1989 `_ r)rÚnpÚuniquer-rZE165Ú _roc_curveÚ_auc)Úy_trueÚy_scoreÚfprÚtprÚ_rrrr,„s$ r,cCs t||ƒ\}}}tjd|f}tjd|f}tj|dd|f}|ddkr`t tj|j¡}n ||d}|ddkrŠt tj|j¡}n ||d}|||fS)aÍCompute Receiver operating characteristic (ROC) Note: this implementation is restricted to the binary classification task. Parameters ---------- y_true : array, shape = [n_samples] True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. y_score : array, shape = [n_samples] Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by "decision_function" on some classifiers). Returns ------- fpr : array, shape = [>2] Increasing false positive rates such that element i is the false positive rate of predictions with score >= thresholds[i]. tpr : array, shape = [>2] Increasing true positive rates such that element i is the true positive rate of predictions with score >= thresholds[i]. thresholds : array, shape = [n_thresholds] Decreasing thresholds on the decision function used to compute fpr and tpr. `thresholds[0]` represents no instances being predicted and is arbitrarily set to `max(y_score) + 1`. Notes ----- Since the thresholds are sorted from low to high values, they are reversed upon returning them to ensure they correspond to both ``fpr`` and ``tpr``, which are sorted in reversed order during their calculation. References ---------- .. [1] `Wikipedia entry for the Receiver operating characteristic `_ .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition Letters, 2006, 27(8):861-874. rrrY)Ú_binary_clf_curverŒÚr_ÚrepeatÚnanÚshape)r�r‘ÚfpsÚtpsZ thresholdsr’r“rrrrŽ®s.    rŽc Csžd}t |¡}t |¡}||k}tj|dd�ddd…}||}||}d}t t |¡¡d}tj||jdf}t||ƒ|}d||}||||fS)aöCalculate true and false positives per binary classification threshold. Parameters ---------- y_true : array, shape = [n_samples] True targets of binary classification y_score : array, shape = [n_samples] Estimated probabilities or decision function Returns ------- fps : array, shape = [n_thresholds] A count of false positives, at index i being the number of negative samples assigned a score >= thresholds[i]. The total number of negative samples is equal to fps[-1] (thus true negatives are given by fps[-1] - fps). tps : array, shape = [n_thresholds <= len(np.unique(y_score))] An increasing count of true positives, at index i being the number of positive samples assigned a score >= thresholds[i]. The total number of positive samples is equal to tps[-1] (thus false negatives are given by tps[-1] - tps). thresholds : array, shape = [n_thresholds] Decreasing score values. gð?Z mergesort)ÚkindNrYrr)rŒÚravelZargsortÚwhereÚdiffr–ÚsizeÚ_stable_cumsum) r�r‘Z pos_labelZdesc_score_indicesZweightZdistinct_value_indicesZthreshold_idxsr›ršrrrr•ñs   r•çñh㈵øä>ç:Œ0âŽyE>c CsVtj||tjd�}tj||tjd�}t tj|jd|d�|||dd�¡sRttj ƒ‚|S)aÉUse high precision for cumsum and check that final value matches sum Parameters ---------- arr : array-like To be cumulatively summed as flat axis : int, optional Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. rtol : float Relative tolerance, see ``np.allclose`` atol : float Absolute tolerance, see ``np.allclose`` )ÚaxisÚdtyperY)r¤T)ÚrtolÚatolZ equal_nan) rŒZcumsumZfloat64rZÚallÚiscloseZtaker-rZE163)Zarrr¤r¦r§ÚoutÚexpectedrrrr¡'s ÿÿ r¡cCs€t |¡}t |¡}d}t |¡}t |dk¡rTt |dk¡rDd}nttj |¡ƒ‚|t  ||¡}t |tj ƒr||j   |¡}|S)a¿Compute Area Under the Curve (AUC) using the trapezoidal rule This is a general function, given points on a curve. For computing the area under the ROC-curve, see :func:`roc_auc_score`. Parameters ---------- x : array, shape = [n] x coordinates. These must be either monotonic increasing or monotonic decreasing. y : array, shape = [n] y coordinates. Returns ------- auc : float rrrY)rŒr�rŸÚanyr¨r-rZE164r‚ZtrapzÚ isinstanceZmemmapr¥Útype)rhÚyÚ directionZdxÚarearrrr�As     r�)Nr¢r£)Ú __future__rrrZnumpyrŒrrrÚerrorsrÚobjectr r%r0r,rŽr•r¡r�rrrrÚs A*C6