【问题标题】:Apply a function along all elements in a array沿数组中的所有元素应用函数
【发布时间】:2019-02-25 15:28:01
【问题描述】:

我有一些数组:

array = np.array([[1, 0], [1, 0], [1, 0]])

我想以这样的方式计算np.kron

def func(array):
    res = array[0]
    for i in range(1, len(array)):
        res = np.kron(res, array[i]) 
    return res

但是如何以更 numpy 的方式来做呢?

我试过np.apply_along_axis

res = np.apply_along_axis(np.kron, 1, array)

但我没有成功。

【问题讨论】:

  • 您希望输出结果如何?
  • @Soften98 tensor(kroneker) 数组所有向量的乘积。
  • 那么,像kron(kron(kron(kron(a[0], a[1]), a[2]), a[3]), a[4])?
  • @Alfe 是的,正是我想要的!
  • 我担心这是不可能的(目前)。 numpy 的方法是通过numpy.ufunc.reducenumpy.ufunc.accumulate,也可以通过e。 G。通过numpy.add.accumulate 等。不幸的是kron 函数没有实现为ufunc,因此不能在这些函数中使用。我没有理由知道它为什么不能这样实现,所以我想在numpy 的更高版本(也许你的比我的年轻?)中它可能是可能的。到目前为止,@slashCoder 的解决方案是我能想到的最好的。

标签: python arrays numpy matrix


【解决方案1】:

我不知道它是否更“numpy”,但绝对更pythonic的方式是使用reduce内置函数:

reduce(np.kron, array)

【讨论】:

  • 是的,task 理解并提供了一个有效的纯 Python 解决方案。但是这样进行的评估不会得到优化。如果有一个 numpy-variant 可以准确地表达这一点,它会更快。
  • 顺便说一句,因为 Python3 你需要from functools import reduce
猜你喜欢
  • 2012-11-28
  • 2023-01-24
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 2017-03-09
相关资源
最近更新 更多