【问题标题】:Ten fold classification and using lib svm to calculate accuracy in pythonpython中十倍分类及使用lib svm计算准确率
【发布时间】:2015-12-04 16:56:24
【问题描述】:

我有一个术语文档矩阵和相应的标签矩阵,我必须将数据集分成 10 个部分,并使用任意随机的 7 个部分来训练 libsvm 分类器并测试剩余的 3 个部分。 对于所有可能的情况,我必须这样做,即 10C7。 这是使用 SVM 进行训练和测试的代码,我无法理解如何对所有情况进行分类和迭代。

m = svm_train(labels[0:2000], rows_1[0:2000], '-c '+str(k)+' -g '+str(g))

p_label, p_acc, p_val = svm_predict(labels[2000:0], rows_1[2000:0], m)
acc.append(p_acc)

其中“labels”是标签数组,“rows_1”是术语文档矩阵的行。 我是新手,请帮忙!

【问题讨论】:

  • 为什么 7 个用于训练,3 个用于测试?
  • 当您标记此 scikit-learn 时,交叉验证的标准版本将是 cross_val_score(SVM(), rows_1, labels, cv=10),它将执行 10 倍分层交叉验证。您没有使用分层,这很可能会给您更多嘈杂的估计,因为不同的折叠将具有不同的类平衡。

标签: python machine-learning nlp scikit-learn libsvm


【解决方案1】:

您必须打乱数据并为训练和测试折叠创建索引。例如,如果你有 2000 个训练样例并且你想使用 10 折,那么你将有:

fold1
  test[0:200]
  train[200:2000]
fold2
  test[200:400]
  train[0:200, 400:2000]
etc

以下是 Python 中的示例代码:

import numpy as np
indices = np.random.permutation(2000)  # create a list of 2000 unique numbers in random order
n_folds = 10
fold_step = int(2000 / n_folds)
acc = []
for fold in range(0, 2000, fold_step):
    test_labels = [labels[i] for i in indices[fold:fold+fold_step]]
    train_labels = [l for l in labels if l not in test_labels]
    test_rows = [rows_1[i] for i in indices[fold:fold+fold_step]]
    train_rows = [r for r in rows_1 if r not in test_rows]

    m = svm_train(train_labels, train_rows, '-c '+str(k)+' -g '+str(g))
    p_label, p_acc, p_val = svm_predict(test_labels, test_rows, m)
    acc.append(p_acc)

print("Accuracy: {}%".format(np.mean(acc)))

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 2019-11-23
    • 2017-04-30
    • 2018-02-09
    • 2016-12-24
    • 2022-06-11
    • 1970-01-01
    • 2018-07-20
    • 2018-12-17
    相关资源
    最近更新 更多