【问题标题】:numpy.sum with conditionalnumpy.sum 有条件的
【发布时间】:2022-06-13 01:43:45
【问题描述】:

在以下代码中:

def compute_class_freqs():
    """
    Compute positive and negative frequences for each class.

    Returns:
        positive_frequencies (np.array): array of positive frequences for each
                                         class, size (num_classes)
        negative_frequencies (np.array): array of negative frequences for each
                                         class, size (num_classes)
    """
    ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###
    labels = [[0,1,0],[1,1,1],[0,1,1]]
    print(labels)
    # total number of patients (rows)
    N = labels[0]
    
    positive_frequencies = None
    negative_frequencies = None

    ### END CODE HERE ###
    return positive_frequencies, negative_frequencies

我想将每行中 1 的数量相加并将每个和附加到 positive_frequencies,并将每行中 0 的数量相加并将每个和附加到negative_frequencies。如何使用 numpy 函数 numpy.sum() 和 numpy.where() 做到这一点?

编辑:positive_frequencies 应该是每列中 1 的数量除以总行数,负频率应该是每列中 0 的数量除以总行数。基本上,该函数应该返回 numpy 浮点数组。

【问题讨论】:

标签: python numpy


【解决方案1】:

我认为这可能有效,我知道您的 cmets 中已经有一个答案,并且这不使用 np.sum 或 np.where,但我想我会分享我是如何做到的:

labels = [[0,1,0],[1,1,1],[0,1,1]]

positive_frequencies = [len([num for num in listOfNums if num == 1]) for listOfNums in labels]
negative_frequencies = [len([num for num in listOfNums if num == 0]) for listOfNums in labels]

print(positive_frequencies, negative_frequencies)

这让我得到了以下输出:

[1, 3, 2] [2, 0, 1]

【讨论】:

  • 这绝对是一种方法......虽然1)它不会按照函数的要求返回numpy数组; 2)它没有按照OP的要求利用numpy; 3) 由于第 2 点,它也是一个非常缓慢的解决方案。
  • positive_frequencies 应该是每列中 1 的数量除以总行数,负频率应该是每列中 0 的数量除以总行数。基本上,该函数应该返回浮点值的 numpy 数组
猜你喜欢
  • 1970-01-01
  • 2012-06-10
  • 2023-02-22
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
相关资源
最近更新 更多