【问题标题】:Vectorize a function - Invalid index to scalar variable向量化函数 - 标量变量的索引无效
【发布时间】:2020-04-04 08:57:41
【问题描述】:

我是 python 新手。 我发现了一篇关于矢量化的有趣文章,所以我开始研究它。 虽然我能够做到这一点:

 def cost(a, b):
    "Return a-b if a>b, otherwise return a+b"
    if a > b:
        return a - b
    else:
        return a + b

cost_vector= np.vectorize(cost)
print(z([1,2,3],[3,4,5]))

输出:[4 6 8]

我不能这样做:

ww = [[1,2,3,4,5,6],[2,2,3,4,5,6],[3,2,3,4,5,6],[4,2,3,4,5,6],[5,2,3,4,5,6],[6,2,3,4,5,6]]

def cost(ww, a, b):
    if a > b:
        return ww[a][b]
    else:
        return ww[b][a]

z = np.vectorize(cost)
print(z(ww, [1,2,3], [3,4,5]))

输出:IndexError: invalid index to scalar variable.

我不知道如何映射到我的数组

谢谢

【问题讨论】:

  • 这是什么文章?它似乎在没有足够的警告和重要细节的情况下建议 np.vectorize
  • numpy 初学者不应该使用np.vectorize。当使用快速编译的numpy 方法无法执行操作时,这是一种备用方法。首先了解numpy 基础知识。它不是一个速度工具,并且有许多给天真的用户带来问题的功能。

标签: python-3.x numpy vectorization


【解决方案1】:

您的代码的问题是np.vectorize() 试图分解所有参数,包括ww。 根据documentation,您需要通过exclude 参数将其排除,例如:

import numpy as np


ww = [[1, 2, 3, 4, 5, 6], [2, 2, 3, 4, 5, 6], [3, 2, 3, 4, 5, 6],
      [4, 2, 3, 4, 5, 6], [5, 2, 3, 4, 5, 6], [6, 2, 3, 4, 5, 6]]


def cost(ww, a, b):
    if a > b:
        return ww[a][b]
    else:
        return ww[b][a]


v_cost = np.vectorize(cost, excluded={0})
print(v_cost(ww, [1, 2, 3], [3, 4, 5]))
# [2 3 4]

请注意,您可以在 NumPy 中执行此操作,而无需 np.vectorize()-decorated 函数。 你只需要确保ww 是一个NumPy 数组并使用np.where() 两次:

import numpy as np


ww = [[1, 2, 3, 4, 5, 6], [2, 2, 3, 4, 5, 6], [3, 2, 3, 4, 5, 6],
      [4, 2, 3, 4, 5, 6], [5, 2, 3, 4, 5, 6], [6, 2, 3, 4, 5, 6]]


def cost(ww, a, b):
    return np.array(ww)[np.where(a > b, a, b), np.where(a > b, b, a)]


print(cost(ww, [1, 2, 3], [3, 4, 5]))
# [2 3 4]

【讨论】:

  • 谢谢norok2,这应该是np.where(a
  • 什么意思?
  • 而不是 np.array(ww)[np.where(a > b, a, b), np.where(a > b, b, a)] 它应该是: np.array (ww)[np.where(a > b, a, b), np.where(a
  • 代码看起来是正确的。请注意,一旦最后两个参数是a, b,另一个时间是b, a。通过您的修改,您会得到不同的结果。
猜你喜欢
  • 2020-05-17
  • 2020-06-20
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多