Python 用2d矩阵填充4D矩阵
我想知道是否有一个numpy函数可以让它更快。下面是我正在尝试做的一个例子Python 用2d矩阵填充4D矩阵,python,numpy,Python,Numpy,我想知道是否有一个numpy函数可以让它更快。下面是我正在尝试做的一个例子 def _sparse_4D_rand_mat(self, x, y, density): _4D_mat = np.empty((x, y, x, y)) for i in range(self.size): for j in range(self.size): _4D_mat[:,i,j,:] = self._rand_sparse(x, y, density)
def _sparse_4D_rand_mat(self, x, y, density):
_4D_mat = np.empty((x, y, x, y))
for i in range(self.size):
for j in range(self.size):
_4D_mat[:,i,j,:] = self._rand_sparse(x, y, density)
return _4D_mat
def _rand_sparse(self, m, n, density, format='csr'):
nnz = max(min(int(m * n * density), m * n), 0)
row = np.random.random_integers(low=0, high=m - 1, size=nnz)
col = np.random.random_integers(low=0, high=n - 1, size=nnz)
data = np.ones(nnz, dtype=float)
data = np.random.dirichlet(data)
return csr_matrix((data, (row, col)), shape=(m, n)).toarray()
谢谢你的贡献。
我是新来的;) 由于密度保持不变,因此不必多次调用
\u rand\u sparse
来生成许多小的稀疏2D数组,您可以调用\u rand\u sparse
一次来生成一个大的稀疏2D数组,然后使用重塑
方法将2D结果重塑为4D数组:
_4D_mat = _rand_sparse(x * y * x, y, density)
_4D_mat = _4D_mat.reshape((x, y, x, y))
比如说,
import numpy as np
import scipy.sparse as sparse
def _rand_sparse(m, n, density, format='csr'):
nnz = max(min(int(m * n * density), m * n), 0)
# use randint since random_integer is deprecated in NumPy 1.11.0
row = np.random.randint(low=0, high=m, size=nnz)
col = np.random.randint(low=0, high=n, size=nnz)
data = np.ones(nnz, dtype=float)
data = np.random.dirichlet(data)
return sparse.csr_matrix((data, (row, col)), shape=(m, n)).toarray()
def orig(x, y, density):
_4D_mat = np.empty((x, y, x, y))
for i in range(y):
for j in range(x):
_4D_mat[:, i, j, :] = _rand_sparse(x, y, density)
return _4D_mat
def alt(x, y, density):
_4D_mat = _rand_sparse(x * y * x, y, density)
_4D_mat = _4D_mat.reshape((x, y, x, y))
return _4D_mat
x, y, density = 2, 4, 0.5
由于alt
消除了双for循环,因此当x
和y
的值增大时(即,for循环中的迭代次数增大时),此解决方案将比orig
快得多。事实上,即使对于上面使用的较小值,alt
也比orig
快(几乎8倍):
In [108]: %timeit orig(x, y, density)
100 loops, best of 3: 2.24 ms per loop
In [109]: %timeit alt(x, y, density)
1000 loops, best of 3: 281 µs per loop
我需要4D数组中每个2D数组的和为1 要规范化适当的切片,可以使用:
totals = np.nansum(_4D_mat, axis=0, keepdims=True)
totals = np.nansum(totals, axis=3, keepdims=True)
_4D_mat /= totals
self.\u rand\u sparse
和\u 4D\u mat
的数据类型是什么?两者都是numpy.matrixOh wait\u rand\u sparse
看起来像一个函数。因此,为了加快速度,更应该看到它的实现。第一个函数x,y,density都保持不变抱歉,我忘了提到我需要4D数组中每个2D数组的和为1。