numpy与tensor张量的转换

在卷积神经网络时经常会用到numpy的数组变量类型与tensor张量类型之间的转换,在这里总结了一下。


import numpy as np
import torch
a = np.random.normal(0, 1, (2, 3))
b= torch.tensor(a)
a,b

(array([[-0.37468825, 0.81942854, -1.56010579],
[-0.00805839, 0.9578339 , 1.95072451]]),
tensor([[-0.3747, 0.8194, -1.5601],
[-0.0081, 0.9578, 1.9507]], dtype=torch.float64))

a = np.random.normal(0, 1, (4, 5))
b= torch.from_numpy(a)
a,b

(array([[-0.47197733, 1.53828686, -1.72156097],
[-2.05017441, 1.23956538, -0.80934275]]),
tensor([[-0.4720, 1.5383, -1.7216],
[-2.0502, 1.2396, -0.8093]], dtype=torch.float64))

import numpy as np
import torch
t = torch.arange(1, 10).reshape(3, 3)
x = t.numpy()
t,x

(tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]),
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=int64))

x = t.detach().numpy()

使用.item将张量转化为单独的数值进行输出

a = torch.tensor(1)
a.item()

tensor(1)
1

t = torch.arange(10)
t1 = t.tolist()
t2 = list(t)
t,t1,t2

(tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

[tensor(0),
tensor(1),
tensor(2),
tensor(3),
tensor(4),
tensor(5),
tensor(6),
tensor(7),
tensor(8),
tensor(9)]

Original: https://blog.csdn.net/weixin_45464524/article/details/127953053
Author: Chaoy6565
Title: numpy与tensor张量的转换

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/761273/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球