簡體   English   中英

如何從每一行中找到最小值(如果一行中有很多最小值保留第一個)並將矩陣的其他元素替換為 0?

[英]How to find a minimum from every rows(if there are many minimums in a row keep the first one ) and replace else elements of matrix with 0?

問題是如何使用 skylearn 從 'sum' 中獲取矩陣 'a'?

data_points = np.array([[1,2,0],[1,0,1],[0,1,1],[0,1,2],[1,1,0]])
centers = np.array([[0,0,0],[1,1,1],[1,1,0],[1,0,0]])
sum = np.sum((data_points[:, np.newaxis] - centers)**2,axis=2)
min = np.min(sum,axis=1)
a=np.array([[0,0,1,0],[0,1,0,0],[0,1,0,0],[0,1,0,0],[0,0,1,0]])
print("The question is how to get matrix 'a' from 'sum' by using skylearn?\n",a)

您可以使用numpy.argmin獲取第一個最小值的索引:

my_sum = np.sum((data_points[:, np.newaxis] - centers)**2,axis=2)
idx_min = np.argmin(my_sum,axis=1)

# set up output
a = np.zeros(my_sum.shape, 'int')
a[np.arange(a.shape[0]), idx_min] = 1

注意。 不要使用summin作為變量名,它們是 python 內置的

output:

array([[0, 0, 1, 0],
       [0, 1, 0, 0],
       [0, 1, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM