我需要幫助找到一種有效的方法(盡可能快)將一個 numpy 的標簽陣列轉換為一個 numpy 的顏色陣列。
我們舉一個簡單的例子:
A 包含標簽(整數):
A = [0,45,45,22,0,45,45,22]B 包含所有標簽:
B = np.unique(A) = [0,45,22]C 包含 RGB 值:
C = [[1,0,0], [0,1,0], [0,0,1]]
的第 i 個元素C是 中第 i 個標簽的顏色B。例如,標簽的顏色45是[0,1,0]。
據此,A應轉換為:
[[1,0,0], [0,1,0], [0,1,0], [0,0,1], ...]
我已經嘗試過以下代碼,但速度很慢:
result = np.array([C[np.where(B==x)[0][0]] for x in A])
有人知道更有效的解決方案嗎?
提前致謝 :)
uj5u.com熱心網友回復:
您可以np.unique為此使用 ' 逆索引:
import numpy as np
A = np.array([0,45,45,22,0,45,45,22])
C = np.array([[1,0,0], [0,1,0], [0,0,1]])
_, inverse_idx = np.unique(A, return_inverse=True)
result = C[inverse_idx]
# array([[1, 0, 0], [0, 0, 1], [0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 1], [0, 0, 1], [0, 1, 0]])
重要說明:np.unique將值和索引作為排序陣列回傳,所以np.unique(A)給出[0, 22, 35],而不是[0, 45, 22]。如果您確實希望按照它們出現的順序來使用它,則需要使用 A 值的原始索引進行額外的操作:
import numpy as np
A = np.array([0,45,45,22,0,45,45,22])
C = np.array([[1,0,0], [0,1,0], [0,0,1]])
_, idx, inverse_idx = np.unique(A, return_index=True, return_inverse=True)
result = C[idx.argsort()[inverse_idx]]
# array([[1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1]])
uj5u.com熱心網友回復:
A = np.array([0,45,45,22,0,45,45,22])
B = np.unique(A)
C = np.array([[1,0,0], [0,1,0], [0,0,1]])
from numba import njit
@njit
def f(arr, labels, colors):
result = np.zeros((len(arr), 3))
for i, label in enumerate(labels):
result[arr==label] = colors[i]
return result
使用來自的單個元素編譯函式A:
f(A[:1], B, C)
現在:
result = f(A, B, C)
9.5367431640625e-05在我的機器上它需要秒,3.123283e-04而你的解決方案需要秒
我還在 1'000'000 數字上嘗試了我的功能,A它需要你的解決方案的秒數0.03591942787170415.217064619064331
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483812.html
上一篇:如何從嵌套結構中生成JSON
