文章目錄
- 1.torch.bitwise_not()
- 2.torch.bitwise_and()
- 3.torch.ceil()
- 3.torch.clamp()
- 4.torch.torch.floor()
1.torch.bitwise_not()
在 PyTorch 中,torch.bitwise_not() 是一個函數,用于執行逐元素的位非(bitwise NOT)操作。
torch.bitwise_not(input, out=None)
"""
input:輸入張量。
out:可選參數,輸出張量。
"""
import torchx = torch.tensor([5, 2, 7], dtype=torch.uint8)y = torch.bitwise_not(x)print(y)
tensor([250, 253, 248], dtype=torch.uint8)
當我們使用 torch.bitwise_not() 函數時,它會對輸入張量中的每個元素執行位非(bitwise NOT)操作。位非操作是對二進制表示的每一位進行取反的操作,即將 0 變為 1,將 1 變為 0。
例如,如果我們有一個輸入張量 x 包含了整數值 [5, 2, 7],這些值的二進制表示分別是 [101, 010, 111]。使用 torch.bitwise_not() 函數對 x 進行位非操作,得到的結果張量 y 的元素將是對應位置上的二進制取反結果。
在示例中,輸出張量 y 包含了 [250, 253, 248],這些值的二進制表示分別是 [11111010, 11111101, 11111000]。可以觀察到,每個元素的二進制表示中的每一位都被取反。
需要注意的是,輸入張量的數據類型對位非操作有影響。在示例中,我們使用了無符號8位整數 (torch.uint8) 的輸入張量 x。位非操作會在每個元素的二進制表示中逐位取反,并且結果張量 y 的數據類型仍然是無符號8位整數 (torch.uint8)。
2.torch.bitwise_and()
在 PyTorch 中,torch.bitwise_and() 是一個函數,用于執行逐元素的位與(bitwise AND)操作。
torch.bitwise_and(input, other, out=None)
"""
input:第一個輸入張量。
other:第二個輸入張量。
out:可選參數,輸出張量。
"""
import torchx = torch.tensor([5, 3, 7], dtype=torch.uint8)
y = torch.tensor([3, 6, 5], dtype=torch.uint8)z = torch.bitwise_and(x, y)print(z)
tensor([1, 2, 5], dtype=torch.uint8)
在這個示例中,我們使用 torch.bitwise_and() 函數對張量 x 和 y 中的元素執行位與操作。輸入張量 x 和 y 包含了無符號8位整數。torch.bitwise_and() 函數將 x 和 y 對應位置上的元素進行位與操作,得到了結果張量 z。
需要注意的是,位與操作將每個元素的二進制表示的對應位進行邏輯與操作,只有當對應位都為 1 時,結果位才為 1,否則為 0。輸出張量 z 的數據類型與輸入張量 x 和 y 相同。
3.torch.ceil()
在 PyTorch 中,torch.ceil() 函數用于執行逐元素的向上取整操作。它返回一個新的張量,其中的元素是輸入張量中對應元素的向上取整結果。
torch.ceil(input, out=None)
"""
input:輸入張量。
out:可選參數,輸出張量。
"""
import torchx = torch.tensor([1.2, 2.7, 3.5, 4.9])y = torch.ceil(x)print(y)
tensor([2., 3., 4., 5.])
3.torch.clamp()
在 PyTorch 中,torch.clamp() 函數用于對張量進行截斷操作,將張量中的元素限制在指定范圍內。它返回一個新的張量,其中的元素被限制在給定的范圍內。
torch.clamp(input, min, max, out=None)
"""
input:輸入張量。
min:指定的最小值,小于該值的元素會被替換為該值。
max:指定的最大值,大于該值的元素會被替換為該值。
out:可選參數,輸出張量。
"""
返回值是一個新的張量,其元素被截斷在 [min, max] 的范圍內。
import torchx = torch.tensor([1.2, -0.5, 3.7, 2.8])y = torch.clamp(x, min=0, max=2)print(y)
tensor([1.2000, 0.0000, 2.0000, 2.0000])
4.torch.torch.floor()
在 PyTorch 中,torch.floor() 函數用于執行逐元素的向下取整操作。它返回一個新的張量,其中的元素是輸入張量中對應元素的向下取整結果。
torch.floor(input, out=None)
"""
input:輸入張量。
out:可選參數,輸出張量。
"""
import torchx = torch.tensor([1.2, 2.7, 3.5, 4.9])y = torch.floor(x)print(y)
tensor([1., 2., 3., 4.])