2.8 排序

2.8 排序

 

import numpy as np
x = np.array([2, 1, 4, 3, 5])
np.sort(x)  # x的排序結果
array([1, 2, 3, 4, 5])

 

x.sort()  # 排序後賦值給x
x
array([1, 2, 3, 4, 5])

 

x = np.array([2, 1, 4, 3, 5])
i = np.argsort(x)  # x排序後的索引值
i
array([1, 0, 3, 2, 4], dtype=int32)

 

x[i]
array([1, 2, 3, 4, 5])

 

rand = np.random.RandomState(42)
X = rand.randint(0, 10, (4, 6))
X
array([[6, 3, 7, 4, 6, 9],
       [2, 6, 7, 4, 3, 7],
       [7, 2, 5, 4, 1, 7],
       [5, 1, 4, 0, 9, 5]])

 

np.sort(X, axis=0)  # 對每列排序
array([[2, 1, 4, 0, 1, 5],
       [5, 2, 5, 4, 3, 7],
       [6, 3, 7, 4, 6, 7],
       [7, 6, 7, 4, 9, 9]])

 

np.sort(X, axis=1)  # 對每行排序
array([[3, 4, 6, 6, 7, 9],
       [2, 3, 4, 6, 7, 7],
       [1, 2, 4, 5, 7, 7],
       [0, 1, 4, 5, 5, 9]])

不進行完全排序,而只是想得到數組中前 K

小的值,可以用如下方法:

 

x = np.array([7, 2, 3, 1, 6, 5, 4])
np.partition(x, 3)  # K=3
array([2, 1, 3, 4, 6, 5, 7])

該方法將前 K

小的值放到返回數組的前 K

個位置,後邊的值是任意順序。

 

np.partition(X, 2, axis=1)  # 按行分隔出前2個小值
array([[3, 4, 6, 7, 6, 9],
       [2, 3, 4, 7, 6, 7],
       [1, 2, 4, 5, 7, 7],
       [0, 1, 4, 5, 9, 5]])

K

個最近鄰

該示例展示如何用 argsort 函數沿着多個軸快速找到集合中每個點的最近鄰。首先,創建10個二維點:

 

X = rand.rand(10, 2)
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn; seaborn.set()
plt.scatter(X[:, 0], X[:, 1], s=100);

 

# 在座標系中計算每對點的差值
differences = X[:, np.newaxis, :] - X[np.newaxis, :, :]
differences.shape
(10, 10, 2)

 

# 求出差值的平方
sq_differences = differences**2
sq_differences.shape
(10, 10, 2)

 


 
# 將差值求和獲得平方距離
dist_sq = sq_differences.sum(-1)
dist_sq.shape
(10, 10)

 


 
dist_sq.diagonal()  # 對角線數值,應該全爲0
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

 

# 當有了這個轉化爲兩點見的平方距離的矩陣後,
# 就可用np.argsort函數沿着每行進行排序了。
# 最左邊的列給出的索引值就是最近鄰
# 注意:第一列是按照0-9排列的,因每個點的最近鄰是其自身
nearest = np.argsort(dist_sq, axis=1)
nearest
array([[0, 3, 9, 7, 1, 4, 2, 5, 6, 8],
       [1, 4, 7, 9, 3, 6, 8, 5, 0, 2],
       [2, 1, 4, 6, 3, 0, 8, 9, 7, 5],
       [3, 9, 7, 0, 1, 4, 5, 8, 6, 2],
       [4, 1, 8, 5, 6, 7, 9, 3, 0, 2],
       [5, 8, 6, 4, 1, 7, 9, 3, 2, 0],
       [6, 8, 5, 4, 1, 7, 9, 3, 2, 0],
       [7, 9, 3, 1, 4, 0, 5, 8, 6, 2],
       [8, 5, 6, 4, 1, 7, 9, 3, 2, 0],
       [9, 7, 3, 0, 1, 4, 5, 8, 6, 2]], dtype=int32)

 


 
# 如果僅關心k個最近鄰,
# 那麼唯一需要的是分隔每一行,這樣最小的k+1的平方距離將排在最前面,
# 其他更長的距離佔據矩陣該行的其他位置
k = 2
nearest_partition = np.argpartition(dist_sq, k+1, axis=1)
plt.scatter(X[:, 0], X[:, 1], s=100);
# 將每個點與它的兩個最近鄰連接,畫出
for i in range(X.shape[0]):
    for j in nearest_partition[i, :k+1]:
        # 畫一條從X[i]到X[j]的線段
        # 用zip方法實現
        plt.plot(*zip(X[j], X[i]), color='black')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章