torch.frombuffer#
- torch.frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) Tensor#
從實現 Python buffer 協議的物件建立一個一維
Tensor。跳過 buffer 中的前
offset位元組,並將剩餘的原始位元組解釋為指定dtype型別、包含count個元素的⼀維張量。注意,以下條件之一必須滿足:
1.
count為正且非零,並且 buffer 中的總位元組數大於offset加上count乘以dtype的大小(以位元組為單位)。2.
count為負數,並且 buffer 的長度(位元組數)減去offset是dtype的大小(以位元組為單位)的倍數。返回的 tensor 和 buffer 共享相同的記憶體。對 tensor 的修改將反映在 buffer 中,反之亦然。返回的 tensor 不可調整大小。
注意
此函式會增加擁有共享記憶體的物件的引用計數。因此,此類記憶體不會在返回的 tensor 作用域結束前被釋放。
警告
當傳遞一個實現了 buffer 協議但其資料不在 CPU 上的物件時,此函式的行為未定義。這樣做很可能會導致段錯誤。
- 引數
buffer (object) – 一個公開 buffer 介面的 Python 物件。
- 關鍵字引數
dtype (
torch.dtype) – 返回 tensor 的期望資料型別。count (int, optional) – 要讀取的期望元素數量。如果為負數,則讀取所有元素(直到 buffer 末尾)。預設為 -1。
offset (int, optional) – 要在 buffer 開頭跳過的位元組數。預設為 0。
requires_grad (bool, optional) – 如果 autograd 應記錄在返回的張量上的操作。預設值:
False。
示例
>>> import array >>> a = array.array('i', [1, 2, 3]) >>> t = torch.frombuffer(a, dtype=torch.int32) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3]) >>> # Interprets the signed char bytes as 32-bit integers. >>> # Each 4 signed char elements will be interpreted as >>> # 1 signed 32-bit integer. >>> import array >>> a = array.array('b', [-1, 0, 0, 0]) >>> torch.frombuffer(a, dtype=torch.int32) tensor([255], dtype=torch.int32)