以下源代码在我的机器上产生了一个内存错误:
import numpy as np
x = np.random.random([100,100,100])
y = np.random.random([100,100,100])
c_sort = np.argsort(x, axis = 2)
f = y[c_sort]
你有一个很好的想法,如何避免内存错误?
另一种方法是
x = np.random.random([100,100,100])
y = np.random.random([100,100,100])
f = np.zeros([100,100,100])
for i in range(100):
for j in range(100):
f[i,j,:] = y[i,j, np.argsort(x[i,j,:])]
但我想知道为什么上述解决方案不会导致相同的结果?
答案 0 :(得分:1)
在评论中讨论后,似乎循环版本是正确的。因此,为了优化它,我们可以使用Could not resolve com.android.support:appcompat-v7:26.1.0. Required by: project :app No cached version of com.android.support:appcompat-v7:26.1.0 available for offline mode. No cached version of com.android.support:appcompat-v7:26.1.0 available for offline mode. Could not resolve com.android.support.constraint:constraint-layout:1.1.0-beta3. Required by: project :app No cached version of com.android.support.constraint:constraint-layout:1.1.0-beta3 available for offline mode. No cached version of com.android.support.constraint:constraint-layout:1.1.0-beta3 available for offline mode. Could not resolve com.android.support:design:26.1.0. Required by: project :app No cached version of com.android.support:design:26.1.0 available for offline mode. No cached version of com.android.support:design:26.1.0 available for offline mode. Could not resolve com.android.support:cardview-v7:26.1.0. Required by: project :app No cached version of com.android.support:cardview-v7:26.1.0 available for offline mode. No cached version of com.android.support:cardview-v7:26.1.0 available for offline mode. Could not resolve com.google.android.gms:play-services-ads:11.4.2. Required by: project :app No cached version of com.google.android.gms:play-services-ads:11.4.2 available for offline mode. No cached version of com.google.android.gms:play-services-ads:11.4.2 available for offline mode. Could not resolve com.android.support:support-v4:26.1.0. Required by: project :app No cached version of com.android.support:support-v4:26.1.0 available for offline mode. No cached version of com.android.support:support-v4:26.1.0 available for offline mode.
。因此,假设argsort指数为advanced-indexing
,我们可以idx = np.argsort(x,axis=2)
这样 -
f
m,n = y.shape[:2]
f = y[np.arange(m)[:,None,None], np.arange(n)[:,None], idx]
take_along_axis
的通用帮助函数可能很有用。