获取python中多个列的argmin

2024-10-01 04:45:01 发布

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

我目前正在运行一些代码,通过使用np.linalg.norm将函数结果与“查找表”进行比较,找到最准确地描述函数的角度。目前,我正在使用for循环对模拟的每个时间步执行此操作,如下所示(我还将它与之进行比较,以强调它是必须在每个时间步进行比较的张量)

    Int3det = TMake.intfromcoordrodswvl(coordinates, avgintensity, wavelength, NAobj, NAcond, alpha3, ndetectors=3) # make 3 by N_timesteps vector
    xpdens = 180 # number of points in x angle 
    ypdens = 360 # number of points in y angle


    thetarange = np.linspace(0, np.pi, xpdens) # range of theta angles
    phirange = np.linspace(-np.pi, np.pi, ypdens) # range of phi angles
    matrix3pol = np.zeros([xpdens, ypdens, 3]) # initialise matrix of intensities for 3 detectors
    for j in enumerate(thetarange): # for angles in theta
        tempmatrix = IntGen.intensitydistribution(j[1], phirange, wavelength, NAobj, NAcond, alpha3, 3) # make intensities for theta, phirange angles for 3 detectors
        matrix3pol[j[0], :, 0] = tempmatrix[:, 0] # put detector 1 in axis 1
        matrix3pol[j[0], :, 1] = tempmatrix[:, 1] # put detector 2 in axis 2
        matrix3pol[j[0], :, 2] = tempmatrix[:, 2] # put detector 3 in axis 3


    for tstep in np.arange(0, len(Int3det)): # for timestep in time trace
         indices3 = np.unravel_index(np.argmin(np.linalg.norm(np.subtract(matrix3pol, Int3det.values[tstep, :]), axis=-1)), matrix3pol[:, :, 0].shape) # get what angle most likely for time step
         Int3res[tstep, 0] = thetarange[indices3[0]] # put theta in result matrix for time step
         Int3res[tstep, 1] = phirange[indices3[1]] # put phi in result matrix for time step

for循环的执行花费了相当长的时间(毫不奇怪)。有没有办法加快执行速度

谢谢


Tags: ofinfortimeputnp时间angles
1条回答
网友
1楼 · 发布于 2024-10-01 04:45:01

我相信这不是一个答案,但它太长了,无法发表评论。 由于您试图查找差异最小的值(根查找),因此根本没有必要使用np.linalg.norm(),您可以尝试比较非规范化和(平方或绝对):

difference = np.sum(np.abs(np.subtract(matrix3pol, Int3det.values[tstep, :])))
# or, whichever is faster
difference = np.sum((np.subtract(matrix3pol, Int3det.values[tstep, :]))**2)
# then
np.unravel_index(np.argmin(difference, axis=-1)), matrix3pol[:, :, 0].shape)

另一种方法可以是使用Scipy.optimize,即受约束的L-BFGS-B。尽管比暴力根查找更复杂,但优化例程的计算速度通常更快

此外,考虑到thetarangephirange是有限的,并且事先就知道,所以尝试真正的表查找也是值得的。其思想很简单:计算一次包含Intensities(theta,phi)的数组,然后使用计算出的值查找参数,而不进行减法运算。因此,强度值稍后用作数组指示符,以找到相应的θ和φ。我经常做很多事情

也请考虑使用Numba来加速事情。然而,对于性能关键例程,我通常在C++中编写一个库,并从Python调用它。p>

相关问题 更多 >