Computing precision and recall for two sets of key

2020-08-05 09:58发布

问题:

I am trying to compute precision and recall for two sets of keywords. The gold_standard has 823 terms and the test has 1497 terms.

Using nltk.metrics's version of precision and recall, I am able to provide the two sets just fine. But doing the same for Scikit is throwing me an error:

ValueError: Found arrays with inconsistent numbers of samples: [ 823 1497]

How do I resolve this?

#!/usr/bin/python3

from nltk.metrics import precision, recall
from sklearn.metrics import precision_score
from sys import argv
from time import time
import numpy
import csv

def readCSVFile(filename):
    termList = set()
    with open(filename, 'rt', encoding='utf-8') as f:
        reader = csv.reader(f)
        for row in reader:
            termList.update(row)
    return termList

def readDocuments(gs_file, fileToProcess):
    print("Reading CSV files...")
    gold_standard = readCSVFile(gs_file)
    test = readCSVFile(fileToProcess)
    print("All files successfully read!")
    return gold_standard, test

def calcPrecisionScipy(gs, test):
    gs = numpy.array(list(gs))
    test = numpy.array(list(test))
    print("Precision Scipy: ",precision_score(gs, test, average=None))

def process(datasest):
    print("Processing input...")
    gs, test = dataset
    print("Precision: ", precision(gs, test))
    calcPrecisionScipy(gs, test)

def usage():
    print("Usage: python3 generate_stats.py gold_standard.csv termlist_to_process.csv")

if __name__ == '__main__':
    if len(argv) != 3:
        usage()
        exit(-1)

    t0 = time()
    process(readDocuments(argv[1], argv[2]))
    print("Total runtime: %0.3fs" % (time() - t0))

I referred to the following pages for coding:

  • http://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_fscore_support.html
  • http://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html#sklearn.metrics.precision_score

=================================Update===================================

Okay, so I tried to add 'non-sensical' data to the list to make them equal length:

def calcPrecisionScipy(gs, test):
    if len(gs) < len(test):
        gs.update(list(range(len(test)-len(gs))))
    gs = numpy.array(list(gs))
    test = numpy.array(list(test))
    print("Precision Scipy: ",precision_score(gs, test, average=None))

Now I have another error:

UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples.

回答1:

seems scientifically not possible to compute precision or recall of two sets of different lengths. I guess what nltk must do is to truncate the sets to the same lengths, you can do the same in your script.

    import numpy as np
    import sklearn.metrics

    set1 = [True,True]
    set2 = [True,False,False]
    length = np.amin([len(set1),len(set2)])
    set1 = set1[:length]
    set2 = set2[:length]

    print sklearn.metrics.precision_score(set1,set2))