torch.median¶
- torch.median(input) Tensor ¶
傳回
input
中值的的中位數。注意
對於具有偶數個元素的
input
張量,中位數並非唯一。 在這種情況下,會傳回兩個中位數中較小的一個。 若要計算兩個中位數的平均值,請改用torch.quantile()
,並將q=0.5
作為參數傳入。警告
此函數會產生確定性的(次)梯度,與
median(dim=0)
不同。- 參數
input (Tensor) – 輸入張量。
範例
>>> a = torch.randn(1, 3) >>> a tensor([[ 1.5219, -1.5212, 0.2202]]) >>> torch.median(a) tensor(0.2202)
- torch.median(input, dim=-1, keepdim=False, *, out=None)
傳回一個 namedtuple
(values, indices)
,其中values
包含input
在維度dim
中每列的中位數,而indices
包含在維度dim
中找到的中位數值的索引。預設情況下,
dim
是input
張量的最後一個維度。如果
keepdim
為True
,則輸出張量的大小與input
相同,但在維度dim
中,它們的大小為 1。 否則,dim
會被壓縮(請參閱torch.squeeze()
),從而導致輸出張量的維度比input
少 1。注意
對於在維度
dim
中具有偶數個元素的input
張量,中位數並非唯一。 在這種情況下,會傳回兩個中位數中較小的一個。 若要計算input
中兩個中位數的平均值,請改用torch.quantile()
,並將q=0.5
作為參數傳入。警告
indices
不一定包含找到的每個中位數值的第一次出現,除非它是唯一的。 確切的實作細節是裝置特定的。 一般來說,不要期望在 CPU 和 GPU 上運行時獲得相同的結果。 出於同樣的原因,不要期望梯度是確定性的。- 參數
- 關鍵字參數
out ((Tensor, Tensor), optional) – 第一個張量將填充中位數值,第二個張量(必須具有 dtype long)將填充它們在
input
的維度dim
中的索引。
範例
>>> a = torch.randn(4, 5) >>> a tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) >>> torch.median(a, 1) torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3]))