矢量化函数重分类numpy浮点阵列时的广播错误

2024-04-29 03:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算2D numpy float数组中的每个值,如果它落在某个数值类的最小、最大边界内。接下来,我要将该值重新分配给与该类关联的“score”

例如,阶级界限可以是:

>>> class1 = (0, 1.5)
>>> class2 = (1.5, 2.5)
>>> class3 = (2.5, 3.5)

班级成绩为:

>>> score1 = 0.75
>>> score2 = 0.50
>>> score3 = 0.25

任何类之外的值都应默认为99

我尝试了以下操作,但由于广播而遇到了一个值错误

>>> import numpy as np

>>> arr_f = (6-0)*np.random.random_sample((4,4)) + 0  # array of random floats


>>> def reclasser(x, classes, news):
>>>     compare = [x >= min and x < max for (min, max) in classes]
>>>     try:
>>>         return news[compare.index(True)
>>>     except Value Error:
>>>         return 99.0


>>> v_func = np.vectorize(reclasser)
>>> out = v_func(arr_f, [class1, class2, class3], [score1, score2, score3])

ValueError: operands could not be broadcast together with shapes (4,4) (4,2) (4,) 

如果您有任何关于此错误发生的原因以及如何纠正的建议,我们将不胜感激。另外,如果我使用向量化函数完全走错了路,我也很高兴听到这个消息


Tags: numpy错误nprandomclassescomparenewsarr
1条回答
网友
1楼 · 发布于 2024-04-29 03:16:58

首先尝试在不使用np.vectorize的情况下使代码正常工作。上面的代码即使以一个float作为第一个参数也不起作用。你拼错了ValueError;另外,使用minmax作为变量名也不是一个好主意(它们是Python函数)。reclasser的固定版本是:

def reclasser(x, classes, news):
    compare = [min(cls) < x < max(cls) for cls in classes]
    try:
        return news[compare.index(True)]
    except ValueError:
        return 99.0

也就是说,我认为使用reclasser和np.vectorize是不必要的复杂。相反,你可以这样做:

# class -> score mapping as a dict
class_scores = {class1: score1, class2: score2, class3: score3}
# matrix of default scores
scores = 99 * np.ones(arr_f.shape)

for cls, score in class_scores.items():
    # see which array values belong into current class
    in_cls = np.logical_and(cls[0] < arr_f, arr_f < cls[1])
    # update scores for current class
    scores[np.where(in_cls)] = score

scores将是与原始数据数组相对应的分数数组

相关问题 更多 >