【问题标题】:NumPy / Sklearn: Get Highest in Row Subject to ConstraintNumPy / Sklearn:在约束条件下获得最高行
【发布时间】:2018-08-07 12:43:44
【问题描述】:

我有一个二维 NumPy 数组scores,其中列代表类,行代表样本。 ith 行和jth 列代表样本i 和类j 的分数。

如果该类的分数超过该类 70% 精度所需的阈值,我想创建另一个 2d NumPy 数组,其中 scores[i, j] 为 1。如果有平局,我们会以最高分打破它们。在我的输出 2d NumPy 数组中,每行应该有一个 1 条目。

我可以通过遍历每一列(类)并使用 sklearn.metrics.precision_recall_curve 计算获得 70% 精度所需的阈值来做到这一点。然后我可以像这样遍历每一行:

new_matrix = np.zeros(scores.shape)        
for i, row in enumerate(scores):
    max_score = 0
    max_index = -1
    for i, score in enumerate(row):
        if score > get_threshold(i) and score > max_score:
            max_score = score
            max_index = i
    if max_index != -1:
        new_matrix[i][max_index] = 1

1) 有没有办法可以将其向量化而不是使用 for 循环?

2) 是否有执行上述操作的库代码?我浏览了sklearn 文档,但我发现最接近的是precision_recall_curve,它适用于每个类,而不是每个二维 NumPy 数组。

谢谢!

【问题讨论】:

    标签: python numpy scikit-learn


    【解决方案1】:

    IIUC,下面的代码应该可以工作。但我不确定是否有更好的方法,仅供参考

    s = scores.copy()
    # mask scores which don't meet the thresholds, assuming original scores are non-negative
    s[s <= thresholds] = -1
    
    new_matrix = np.zeros(scores.shape)
    new_matrix[np.arange(scores.shape[0]), s.argmax(axis=1)] = 1
    new_matrix[s == -1] = 0
    

    thresholds 以上类似于np.array([get_threshold(i) for i in range(scores.shape[1])])

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多