我一直在嘗試從不同的二進制陣列計算距離矩陣,我只能使用 for 回圈來解決這個問題......
問題包括以下內容;想象一下,我有一個由不同行構建的二進制矩陣,如下所示,在這種情況下,維度 n=3,m=3:
np.matrix([[0,0,0],
[1,0,1],
[1,1,1]])
我想通過在每行上添加不同位置的數量來實作以下對稱矩陣:
np.matrix([[0,2,3],
[2,0,1],
[3,1,0]])
我一直在嘗試通過 2 個 for 回圈來完成它,并在 2 個位置時添加,!=但我無法知道如何正確地迭代這些向量......
有什么幫助嗎?
uj5u.com熱心網友回復:
如果我理解正確,你可以這樣做:
import numpy as np
mat = np.matrix([[0,0,0],
[1,0,1],
[1,1,1]])
result = np.zeros(np.shape(mat))
nrows, ncols = np.shape(mat)
for r in range(nrows):
# We only need to compare the upper triangular part of the matrix.
for i in range(r 1, nrows):
for j in range(ncols):
result[r, i] = mat[r, j] != mat[i, j]
# Here we copy the upper triangular part to lower triangular to make it symmetric.
result = result result.T
print(result)
array([[0, 2, 3],
[2, 0, 1],
[3, 1, 0]])
如果您至少可以使用一些 numpy 函式:
# You can also iterate matrices row by row.
for i, row in enumerate(mat):
# Sum differences. mat != row already calculates the differences with the whole matrix.
result[i, :] = np.sum(mat != row, axis=1).transpose()
print(result)
array([[0, 2, 3],
[2, 0, 1],
[3, 1, 0]])
如果你想看到一個巧妙的技巧,這里是你如何在不使用 for 回圈迭代的情況下做到這一點。以下代碼使用“廣播”。我們向陣列添加一個維度,以便使用每一行自動完成比較:
# For this trick we need to convert the matrix to an array.
mat_arr = np.asarray(mat)
result_broadcasting = np.sum(mat_arr != mat_arr[:, None], axis=2)
print(result_broadcasting)
array([[0, 2, 3],
[2, 0, 1],
[3, 1, 0]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/478306.html
