作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有没有办法矢量化 np.meshgrid 的创建?
#Example of normal np.meshgrid
x = [1.22749725, 2.40009184, 1.48602747, 2.83286752, 2.37426951]
y = [1.23816021, 1.69811451, 2.08692546, 2.13706377, 1.60298873]
gridrez=10
X,Y = np.meshgrid(np.linspace(min(x), max(x), endpoint=True, num=gridrez),
np.linspace(min(y), max(y), endpoint=True, num=gridrez))
# X.shape = 10x10
# Y.shape = 10x10
我想复制此功能,但 x,y 不是 1x5 数组,而是 1000x5 数组,结果 X,Y 将是 1000x10x10。注意我已经找到了一种矢量化 np.linspace 的方法,所以不用担心。假设我们有两个 (1000x10) 数组并想要创建一个 1000x10x10 的网格。当我输入答案时,我得到一个 (10000,10000) 网格而不是 1000x10x10
最佳答案
这里使用 vectorized-linspace : create_ranges
-
# https://stackoverflow.com/a/40624614/ @Divakar
def create_ranges(start, stop, N, endpoint=True):
if endpoint==1:
divisor = N-1
else:
divisor = N
steps = (1.0/divisor) * (stop - start)
return steps[:,None]*np.arange(N) + start[:,None]
def linspace_nd(x,y,gridrez):
a1 = create_ranges(x.min(1), x.max(1), N=gridrez, endpoint=True)
a2 = create_ranges(y.min(1), y.max(1), N=gridrez, endpoint=True)
out_shp = a1.shape + (a2.shape[1],)
Xout = np.broadcast_to(a1[:,None,:], out_shp)
Yout = np.broadcast_to(a2[:,:,None], out_shp)
return Xout, Yout
linspace_nd
的最终输出将是矢量化 linspace 输出的 3D
GridView ,因此内存效率高,因此性能也很好。
或者,如果您需要具有自己的内存空间而不是 View 的输出,则可以使用 np.repeat
进行复制 -
Xout = np.repeat(a1[:,None,:],a2.shape[1],axis=1)
Yout = np.repeat(a2[:,:,None],a1.shape[1],axis=2)
使用 View
创建此类数组的时机 -
In [406]: np.random.seed(0)
...: x = np.random.rand(1000,5)
...: y = np.random.rand(1000,5)
In [408]: %timeit linspace_nd(x,y,gridrez=10)
1000 loops, best of 3: 221 µs per loop
关于python - 从 2D 数组创建矢量化 numpy.meshgrid 以创建 3D 网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55378816/
我是一名优秀的程序员,十分优秀!