簡體   English   中英

如何用 numpy 構造秩數組? (什么是秩數組?)

[英]How to construct a rank array with numpy? (What is a rank array?)

我希望你們所有人都過得愉快。 在我的 python class 中,我們正在學習如何使用 Numpy,所以我們得到了一個關於它的作業。 我的問題是:什么是秩數組,如何使用 python 構造它? 我的導師試圖用這些話來解釋這一點,但我實際上什么都不懂:(這些是說明:

rank_calculator(A) - 5 分

給定一個 numpy ndarray A,返回它的秩數組。

Input: [[ 9 4 15 0 18]
        [16 19 8 10 1]]

Return value: [[4 2 6 0 8]
               [7 9 3 5 1]]

返回值應該是與原始數組 A 大小和形狀相同的 ndarray。

那么,有人可以解釋一下嗎? 我不太擅長 Python,不幸的是:(

Q) 什么是秩數組?

Ans:基本上是按其排序順序排列的元素。

基本上,您的老師要求您返回每個元素的位置(如果它們按升序排序)。

代碼:

import numpy as np

A = np.array([[9, 4, 15, 0, 18],
              [16, 19, 8, 10, 1]])

flatA = A.flatten()
sorted_flatA = sorted(flatA)  # will become -> [0, 1, 4, 8, 9, 10, 15, 16, 18, 19]

# Using a 'MAP' to map the values of sorted_faltA to the index of sorted_faltA.
MAP = {}
for i in range(len(sorted_flatA)):
    MAP[sorted_flatA[i]] = i

# Then simply going through the 2D array snd replacing the with their ranks.
res = np.zeros(A.shape)
for i in range(A.shape[0]):
    for j in range(A.shape[1]):
        res[i][j] = MAP[A[i][j]]

print(res)

您可以使用numpy.argsort多次來處理矩陣,如在 SO 上的這個答案中所建議的那樣。

import numpy as np

inp = np.array([[9,4,15,0,18],
                [16,19,8,10,1]])

inp.ravel().argsort().argsort().reshape(inp.shape)
array([[4, 2, 6, 0, 8],
       [7, 9, 3, 5, 1]])

什么是秩矩陣?

總之,如果我要取出矩陣中的所有整數,並將它們從小到大排序,然后為每個整數分配一個從 0 到 9 的rank ,這將產生等級矩陣。 請注意,最小的是 0,排名為 0,而最大的是 19,排名為 9。

雙 argsort 的工作原理

#printing them so they align nicely
print('Array ->', end='')
for i in inp.ravel().astype('str'):
    print(i.center(4), end='')
print('\n')
print('Sort1 ->', end='')
for i in inp.ravel().argsort().astype('str'):
    print(i.center(4), end='')
print('\n')
print('Sort2 ->', end='')
for i in inp.ravel().argsort().argsort().astype('str'):
    print(i.center(4), end='')
Array -> 9   4   15  0   18  16  19  8   10  1  

Sort1 -> 3   9   1   7   0   8   2   5   4   6  

Sort2 -> 4   2   6   0   8   7   9   3   5   1  

我們先總結一下argsort的作用。 它獲取每個元素的 position 並在排序后將它們放在它們所屬的位置 知道了這一點,我們就可以編寫一個本質上是三角形的后向邏輯。 讓我們從 sort2 開始,然后是 sort1,然后是數組。

  1. 0th個(在 sort2 中)是4th (在 sort1 中), 4th (在 sort1 中)是0th個(在數組中)。 所以0th個(在數組中)是0th個(在 sort2 中)

  2. 9th (在 sort2 中)是1st個(在 sort1 中), 1st個(在 sort1 中)是9th (在數組中)。 所以, 9th (在數組中)是9th (在 sort2 中)

  3. 6th (在 sort2 中)是9th (在 sort1 中), 9th (在 sort1 中)是6th (在數組中)。 所以, 6th (在數組中)是6th (在 sort2 中)

繞着它轉會有點混亂,但是一旦你理解了 argsort() 的工作原理,你就不應該有問題。

暫無
暫無

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

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