在二维numpy数组上广播函数

在二维numpy数组上广播函数

本文介绍了在二维numpy数组上广播函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在 numpy 数组上而不是 for循环上计算一次函数来提高代码速度,而该函数在 python库.如果我具有以下功能:

I would like to improve the speed of my code by computing a function once on a numpy array instead of a for loop is over a function of this python library. If I have a function as following:

import numpy as np
import galsim
from math import *
M200=1e14
conc=6.9
def func(M200, conc):
    halo_z=0.2
    halo_pos =[1200., 3769.7]
    halo_pos = galsim.PositionD(x=halo_pos_arcsec[0],y=halo_pos_arcsec[1])
    nfw      = galsim.NFWHalo(mass=M200, conc=conc, redshift=halo_z,halo_pos=halo_pos, omega_m = 0.3, omega_lam =0.7)
    for i in range(len(shear_z)):
       shear_pos=galsim.PositionD(x=pos_arcsec[i,0],y=pos_arcsec[i,1])
       model_g1, model_g2  = nfw.getShear(pos=self.shear_pos, z_s=shear_z[i])
    l=np.sum(model_g1-model_g2)/sqrt(np.pi)
    return l

pos_arcsec24000x2的二维数组,而shear_z是具有24000元素的一维数组.主要问题是我想在M200=np.arange(13., 16., 0.01)conc = np.arange(3, 10, 0.01)的网格上计算此函数.我不知道如何在M200conc上广播此二维数组的估计函数.运行代码需要很多时间.我正在寻找加速这些计算的最佳方法.

While pos_arcsec is a two-dimensional array of 24000x2 and shear_z is a 1D array with 24000 elements as well.The main problem is that I want to calculate this function on a grid where M200=np.arange(13., 16., 0.01) and conc = np.arange(3, 10, 0.01). I don't know how to broadcast this function to be estimated for this two dimensional array over M200 and conc. It takes a lot to run the code. I am looking for the best approaches to speed up these calculations.

推荐答案

使用 numpy.linalg.norm

如果有数组:

import numpy as np
import numpy.linalg as la

a = np.array([[3, 4], [5, 12], [7, 24]])

然后您可以通过以下方式确定所得向量的大小(sqrt(a ^ 2 + b ^ 2))

then you can determine the magnitude of the resulting vector (sqrt(a^2 + b^2)) by

b = np.sqrt(la.norm(a, axis=1)

>>> print b
array([  5.,  15.  25.])

这篇关于在二维numpy数组上广播函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:01