如何缩小二进制矩阵的大小并保留python中的所有二进制矩阵



我有一个648*2340矩阵,它包含1和0,但大部分是零。我想把矩阵减少到216*780,就矩阵元素而言,它小了9倍。话虽如此,我需要将大矩阵划分为许多3*3矩阵,这些矩阵最终折叠成一个元素。如果3*3矩阵中存在1,则元素的值应为1,否则为0。对此有什么方法?谢谢

可以这样做:

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]])

需要时,可以通过更改m1n1的值来轻松更改输入阵列a1的大小,通过更改m2n2(在您的情况下为:6482340216780(来轻松更改输出阵列a2的大小。输入阵列a1中的01值的概率在该示例中被设置为.9.1,但是也可以改变。

使用稀疏矩阵表示。它是矩阵的表示,其中只存储包含非空值(在您的情况下为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://en.wikipedia.org/wiki/Sparse_matrix

最新更新