np.apply_along_axis()函数似乎非常慢(15分钟后没有输出).有没有一种快速的方法在长阵列上执行此功能而无需并行化操作?我特别谈论有数百万个元素的数组.
这是我想要做的一个例子.请忽略my_func的简单定义,目标不是将数组乘以55(当然这可以在适当的位置完成),而是一个例子.在实践中,my_func稍微复杂一些,需要额外的参数,因此a的每个元素都被不同地修改,即不仅仅乘以55.
>>> def my_func(a):
... return a[0]*55
>>> a = np.ones((200000000,1))
>>> np.apply_along_axis(my_func, 1, a)
Run Code Online (Sandbox Code Playgroud)
编辑:
a = np.ones((20,1))
def my_func(a, i,j):
... b = np.zeros((2,2))
... b[0,0] = a[i]
... b[1,0] = a[i]
... b[0,1] = a[i]
... b[1,1] = a[j]
... return linalg.eigh(b)
>>> my_func(a,1,1)
(array([ 0., 2.]), array([[-0.70710678, 0.70710678],
[ 0.70710678, 0.70710678]]))
Run Code Online (Sandbox Code Playgroud) 在下面的代码中,y1和y2应该相等,但它们不是.vectorize()或dot()中可能有错误吗?
import numpy as np
interval = np.arange(0, 30, 0.1)
y1 = [- 1.57 * max(0, x - 10) - 0.72 * max(0, 15 - x)
- 1.09 * max(0, 20 - x) for x in interval]
def fun(x, pivot, truth):
if truth: return max(0, x - pivot)
else: return max(0, pivot - x)
pivots = [10, 15, 20]
truths = [ 1, 0, 0]
coeffs = [-1.57, -0.72, -1.09]
y2 = [np.dot(np.vectorize(fun)(x, pivots, truths), coeffs) for x in interval] …Run Code Online (Sandbox Code Playgroud)