问题是如何使用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
注意。不要使用sum
和min
作为变量名,它们是python内置的
输出:
array([[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])