日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Tensor?和?NumPy?相互轉換的實現_python

作者:xzw96 ? 更新時間: 2023-04-24 編程語言

我們很容易用numpy()和from_numpy()將Tensor和NumPy中的數組相互轉換。但是需要注意的一點是: 這兩個函數所產生的Tensor和NumPy中的數組共享相同的內存(所以他們之間的轉換很快),改變其中一個時另一個也會改變!

1. Tensor 轉 NumPy

a = torch.ones(6)
b = a.numpy()
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)
tensor([1., 1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1. 1.]
tensor([2., 2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3. 3.]

2. NumPy 數組轉 Tensor

import numpy as np
a = np.ones(7)
b = torch.from_numpy(a)
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)
[1. 1. 1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1., 1., 1.], dtype=torch.float64)
[2. 2. 2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2., 2., 2.], dtype=torch.float64)
[3. 3. 3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3., 3., 3.], dtype=torch.float64)

3. torch.tensor() 將 NumPy 數組轉換成 Tensor

直接用torch.tensor()將NumPy數組轉換成Tensor,該方法總是會進行數據拷貝,返回的Tensor和原來的數據不再共享內存。

import numpy as np
a = np.ones((2,3))
c = torch.tensor(a)
a += 1
print('a:',a)
print('c:',c)
print(id(a)==id(c))
a: [[2. 2. 2.]
 [2. 2. 2.]]
c: tensor([[1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
False

原文鏈接:https://blog.csdn.net/qq_40630902/article/details/119574712

欄目分類
最近更新