【问题标题】:Numpy Apply Custom Function Along Axis (or Map)Numpy沿轴(或地图)应用自定义函数
【发布时间】:2021-05-18 00:51:31
【问题描述】:

Related to this question:

我有以下带有自定义函数的代码:

import numpy as np
from scipy.integrate import quad
from scipy.special import binom
from scipy.stats import norm
import math as mt
ranks = np.array([[8, 5, 3, 7, 6, 2, 1, 4],
       [8, 5, 3, 7, 6, 2, 1, 4]])

def E(r, n):
    print(r,n)
    def f(x):
        F = Phi(x)
        return x*(1-F)**(r-1)*F**(n-r)*phi(x)
    return -r*binom(n, r)*quad(f, -inf, inf)[0]

我想对数组ranks的每一行应用函数E。

我尝试了np.apply_along_axis,但我遇到的问题是该函数有 2 个参数:数组行中元素的单个等级 (r) 和该行的长度 (@ 987654326@).

另外,我想知道使用map 是否会更快更好,就像上面提到的问题的公认答案一样(因为速度对此很重要)。

这是我尝试过的:

result = np.apply_along_axis(E, 1, ranks)

问题:我需要提供 n 参数。此外,这可能比映射慢。

#not sure if the "*" is needed or what it does.
def E2(i):
    return [*E(ranks[i], len(ranks[i]))]

it = 2 #2 rows (iterations)
indx = np.arange(it)
result = np.array(list(map(E2, indx))) 

问题:每行一次需要 1 个等级。不知道如何实现。

提前致谢!

【问题讨论】:

  • 如果我理解正确,n 是len(r),因此传递该信息是多余的。它应该只是在函数内部计算。
  • apply_along_axis 不是速度工具。迭代超过 2 维或更多维(3d+ 数组)时可能很方便,但它不会使迭代更快。如果使用起来不方便,那就算了。我更喜欢列表理解而不是地图,因为它的表现力。
  • @Reti43 我愿意尝试,但这意味着我需要将行的每个元素和行本身传递给该行的每个值的函数。

标签: python arrays function numpy


【解决方案1】:

由于您尚未指定 Phiquad 等的导入,因此我不会尝试提供工作示例。

def E(r, n):
    print(r,n)
    def f(x):
        F = Phi(x)
        return x*(1-F)**(r-1)*F**(n-r)*phi(x)
    return -r*binom(n, r)*quad(f, -inf, inf)[0]

一个简单的列表理解:

res = [E(r,n) for r in ranks]

我希望将f(x) 定义从E 中移出。这可能更多的是风格问题而不是性能问题。

def f(x,r):
    F = Phi(x)
    return x*(1-F)**(r-1)*F**(n-r)*phi(x)

def E(r,n):
    temp = quad(f, -inf, inf, args=(r,))[0]
    return -r*binom(n, r)*temp

【讨论】:

  • 很抱歉。我已经添加了导入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 2016-12-20
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
相关资源
最近更新 更多