python - 用 2d 矩阵填充 4D 矩阵
问题描述
我想知道是否有一个 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)
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()
感谢您的贡献。我是新来的 ;)
解决方案
由于密度保持不变,与其调用_rand_sparse
多次生成许多小的稀疏二维数组,不如调用_rand_sparse
一次生成一个大的稀疏二维数组,然后使用该reshape
方法将 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
由于消除了双 for 循环,因此该解决方案将比随着 和 的值变大(即随着 for 循环中的迭代次数增加)alt
快得多。事实上,即使对于上面使用的小值,也已经(几乎 8 倍)快于:orig
x
y
alt
orig
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
推荐阅读
- sinon - 如何在 TypeORM 中使用 sinon 存根链接函数
- vue.js - 如何在 natviescript-vue vuex 商店操作中使用 $navigateTo?
- c# - 单击按钮以表单形式发送后,我想要一个模态
- html - 如何使用 CSS 最好地替代聊天气泡定位?
- python - 熊猫连续检测负数并返回值
- oauth - 开放 ID 令牌与 Oauth 令牌
- php - foreach 回显数组回显“数组”而不是值
- regex - 是否可以仅定义 ^ 的字符类?
- c# - Xamarin Android Manifest.xml ${applicationId} 构建错误
- php - 我需要将 vue 数据传递给 PHP