gpt4 book ai didi

python - Python 中 NumPy 或 SciPy 中 Wolfram Mathematica 的模拟函数

转载 作者:行者123 更新时间:2023-12-01 01:18:50 33 4
gpt4 key购买 nike

我正在将用 Wolfram Mathematica 编写的一些代码重写为 Python。而且,在某个时刻我需要一个类似的函数 ArrayResample[array,dspec] 。也许您知道任何包(NumPy 或 SciPy)中的函数?

最佳答案

您可以使用 scipy.ndimage.map_coordinates 。这里是map_coordinate ArrayResample examples 的等效项:

In [51]: import scipy.ndimage as ndimage

In [67]: ndimage.map_coordinates(np.array([1,2,3,4,5], dtype=float), [np.linspace(0,4,9)], order=1)
Out[67]: array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])

In [68]: ndimage.map_coordinates(np.array([1,2,3,4,5], dtype=float), [np.linspace(0,4,3)], order=1)
Out[68]: array([1., 3., 5.])

In [65]: ndimage.map_coordinates(np.array([(1,2,3), (2,3,4), (3,4,5)], dtype=float), np.meshgrid(np.linspace(0,2,6), np.linspace(0,2,6), indexing='ij'), order=1)
Out[65]:
array([[1. , 1.4, 1.8, 2.2, 2.6, 3. ],
[1.4, 1.8, 2.2, 2.6, 3. , 3.4],
[1.8, 2.2, 2.6, 3. , 3.4, 3.8],
[2.2, 2.6, 3. , 3.4, 3.8, 4.2],
[2.6, 3. , 3.4, 3.8, 4.2, 4.6],
[3. , 3.4, 3.8, 4.2, 4.6, 5. ]])

ndimage.map_coordinates 的第一个参数主要是不言自明的。与 Mathematica 的 ArrayResample 函数不同,第二个参数是您希望对数组重新采样的坐标

调用ndimage.map_coordinates(input, coordinates)时,如果input是一个N维数组,则 coordinates预计序列为 N数组——每个轴一个数组。

<小时/>

如果A是形状为 (h, w) 的数组,并且您希望重新采样 A到一个新的形状数组 (H, W) ,那么你会使用

ndimage.map_coordinates(A, np.meshgrid(np.linspace(0,h-1,H), np.linspace(0,w-1,W), 
indexing='ij'), order=1)

np.linspace 用于生成 0 之间等距的值和h-1 (以及 0w-1 )。这些值是一维坐标。 np.meshgrid 用于将一维坐标组合成二维网格。

关于python - Python 中 NumPy 或 SciPy 中 Wolfram Mathematica 的模拟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54044589/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com