【发布时间】:2022-07-31 18:23:25
【问题描述】:
我有一个 648 * 2340 矩阵,其中包含 1 和 0,但大部分都是零。我想将矩阵减少到 216 * 780,就矩阵元素而言,它小了 9 倍。话虽如此,我需要将大矩阵划分为许多 3 * 3 矩阵,这些矩阵最终折叠成一个元素。如果 3 * 3 矩阵中存在 1,则元素的值应为 1,否则为 0。对此有哪些方法?谢谢。
【问题讨论】:
我有一个 648 * 2340 矩阵,其中包含 1 和 0,但大部分都是零。我想将矩阵减少到 216 * 780,就矩阵元素而言,它小了 9 倍。话虽如此,我需要将大矩阵划分为许多 3 * 3 矩阵,这些矩阵最终折叠成一个元素。如果 3 * 3 矩阵中存在 1,则元素的值应为 1,否则为 0。对此有哪些方法?谢谢。
【问题讨论】:
使用稀疏矩阵表示。 它是矩阵的表示,其中仅存储包含非空值(在您的情况下为 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)
【讨论】:
可以这样做:
import numpy as np
np.random.seed(123)
n, m = 12, 12
a1, a2 = np.random.choice([0,0,0,0,0,1], size=(n, m), replace=True), np.zeros((int(n/3), int(m/3)), dtype=int)
for i, x in enumerate(np.linspace(0, n, int(n/3+1), endpoint=True, dtype=int, axis=0)[:-1]):
for j, y in enumerate(np.linspace(0, m, int(m/3+1), endpoint=True, dtype=int, axis=0)[:-1]):
s = a1[x:x+3, y:y+3].sum()
if s > 0: a2[i, j] = 1
生成矩阵a1:
array([[1, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]])
输出矩阵a2:
array([[1, 1, 0, 0],
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]])
【讨论】: