numpy与tensor张量的转换

numpy与tensor的转换

文章目录

  • numpy与tensor的转换
  • 前言
  • 一、numpy数组转tensor张量
  • 二、tensor张量转numpy数组
  • 三、tensor张量转其他

前言

在卷积神经网络时经常会用到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))

二、tensor张量转numpy数组

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() # 用了detach(),不需要计算梯度了

三、tensor张量转其他

使用.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)]

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年5月9日
下一篇 2023年5月9日

相关推荐