我有一个648 * 2340矩阵,它包含1和0,但大部分是零。我想将矩阵减少到216 * 780,这是矩阵元素的9倍。尽管如此,我需要将大矩阵分解成许多3×3矩阵,它们最终折叠成一个元素。如果在3*3矩阵中存在元素,则元素的值应为1,否则为0。解决这个问题的方法是什么?谢谢。
发布于 2022-07-31 10:23:25
可以这样做:
import numpy as np
np.random.seed(42)
m1, n1 = 12, 12 # dimensions input array
a1 = np.random.choice((0, 1), size=(m1, n1), replace=True, p=(.9, .1)) # input array
m2, n2 = 4, 4 # dimensions output array
a2 = np.zeros((m2, n2), dtype=int) # output array
s1, s2 = int(m1/m2), int(n1/n2) # dimensions 'subset array'
for i, x in enumerate(np.linspace(0, m1, int(m1/s1), endpoint=False, dtype=int, axis=0)):
for j, y in enumerate(np.linspace(0, n1, int(n1/s1), endpoint=False, dtype=int, axis=0)):
if a1[x:x+s1, y:y+s2].sum() > 0:
a2[i, j] = 1
生成矩阵a1
array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0]])
输出矩阵a2
array([[1, 0, 0, 1],
[1, 1, 1, 1],
[0, 0, 1, 0],
[1, 1, 1, 0]])
在需要时,您可以通过更改a1
和n2
(在您的示例中是:648
、2340
、216
、780
)更改m1
和n1
的值以及输出数组a2
的值来轻松地更改输入数组a2
的大小。在示例中,0
和1
值在输入数组a1
中的概率设置为.9
和.1
,但也可以更改。
发布于 2022-07-31 09:51:10
使用稀疏矩阵表示。它是矩阵的表示,其中只存储包含非空值的条目(在本例中为1)。
sparseMatrix = [[0,0,1,0,1],[0,0,1,1,0],[0,0,0,0,0],[0,1,1,0,0]]
# initialize size as 0
size = 0
for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
size += 1
# number of columns in compactMatrix(size) should
# be equal to number of non-zero elements in sparseMatrix
rows, cols = (3, size)
compactMatrix = [[0 for i in range(cols)] for j in range(rows)]
k = 0
for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
compactMatrix[0][k] = i
compactMatrix[1][k] = j
compactMatrix[2][k] = sparseMatrix[i][j]
k += 1
for i in compactMatrix:
print(i)
https://stackoverflow.com/questions/73181951
复制相似问题