【问题标题】:How to calculate precision, recall and F-score with libSVM in python如何在 python 中使用 libSVM 计算精度、召回率和 F 分数
【发布时间】:2013-05-31 10:43:44
【问题描述】:

我想在 Python 中使用 libsvm 计算 precisionrecallf-score,但我不知道如何。我找到了this site,但我不明白如何调用该函数,如果你能通过示例帮助我。

【问题讨论】:

    标签: python machine-learning libsvm precision-recall


    【解决方案1】:

    您可以利用 scikit-learn,它是 Python 中机器学习的最佳软件包之一。它的 SVM 实现使用libsvm,您可以计算出精度、召回率和 f-score,如下面的 sn-p 所示:

    from sklearn import svm
    from sklearn import metrics
    from sklearn.cross_validation import train_test_split
    from sklearn.datasets import load_iris
    
    # prepare dataset
    iris = load_iris()
    X = iris.data[:, :2]
    y = iris.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    
    # svm classification
    clf = svm.SVC(kernel='rbf', gamma=0.7, C = 1.0).fit(X_train, y_train)
    y_predicted = clf.predict(X_test)
    
    # performance
    print "Classification report for %s" % clf
    print
    print metrics.classification_report(y_test, y_predicted)
    print
    print "Confusion matrix"
    print metrics.confusion_matrix(y_test, y_predicted)
    

    这将产生类似这样的输出:

    Classification report for SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.7,
    kernel=rbf, max_iter=-1, probability=False, shrinking=True, tol=0.001,
    verbose=False)
    
                 precision    recall  f1-score   support
    
              0       1.00      1.00      1.00         9
              1       0.90      0.69      0.78        13
              2       0.64      0.88      0.74         8
    
    avg / total       0.86      0.83      0.84        30
    
    
    Confusion matrix
    [[9 0 0]
     [0 9 4]
     [0 1 7]]
    

    当然,您可以使用您提到的libsvm tools,但它们仅适用于二进制分类,而scikit允许您使用多类。

    【讨论】:

    • 您正在加载什么数据集?例如,如果我的数据集在文本文件中,如何使用它们?
    • 在示例中,我使用了一个名为 iris 的预定义数据集,它带有 scikit-learn。对于特定数据集,您需要将文本数据转换为 numpy 矩阵。
    猜你喜欢
    • 2016-02-14
    • 2011-11-01
    • 2019-12-14
    • 2020-07-12
    • 2014-11-20
    • 2012-11-26
    • 2016-07-26
    • 2017-08-21
    • 2019-11-27
    相关资源
    最近更新 更多