python - 堆叠稀疏矩阵
问题描述
我有具有以下功能的密集数组的现有代码,并且也希望支持稀疏矩阵。
特别是,我有一个四维tensor
的形状(k, k, n, n)
,我部分地压平成这样matrix
的形状(k * n, k * n)
。
# Roll the third dimension to the second position to get a tensor
# with shape (k, n, k, n)
rolled = np.rollaxis(tensor, 2, 1)
# Extract the dimensions
k, n = rolled.shape[:2]
# Reshape to partially flatten the array
matrix = rolled.reshape((k * n, k * n))
在稀疏设置中,我有一个k
由k
列表组成的列表,其中每个元素都是一个n
稀疏n
矩阵。使用np.rollaxis
不是一种选择,因为有些维度是稀疏的,有些是密集的。关于如何实现相同行为的任何想法,以便我最终得到一个带有 shape 的稀疏矩阵(k * n, k * n)
?
一种选择是使用坐标格式并单独设置每个元素matrix
,但这似乎很麻烦且容易出错。
解决方案
推荐阅读
- mysql - Typeorm 批量更新 - 仅在正文中存在时更新
- c++ - 空函数的stackoverflow
- spring-boot - 从 Spring Boot 在 Cosmos DB 中自动生成 id
- javascript - 在 Rails 6 中安装 bootstrap-table-rails
- java - keycloak:检查旧密码是否匹配,如果匹配,则更改为另一个
- ios - 如何快速防止 UIViewController 的多次推送?
- firebase - 为什么我仍然能够在我的 Google Analytics(分析)仪表板中看到分析数据?
- php - 为什么 PHP 将我的数组识别为标量值?
- python - Numpy索引分配保留连续性?
- charts - 带顶点图的半圆环图