没有合适的资源?快使用搜索试试~ 我知道了~
首页pytorch中tensor张量数据类型的转化方式
1.tensor张量与numpy相互转换 tensor ----->numpy import torch a=torch.ones([2,5]) tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]]) # ********************************** b=a.numpy() array([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]], dtype=float32) numpy ----->tensor import numpy as np a=np.ones
资源详情
资源评论
资源推荐

pytorch中中tensor张量数据类型的转化方式张量数据类型的转化方式
1.tensor张量与张量与numpy相互转换相互转换
tensor ----->numpy
import torch
a=torch.ones([2,5])
tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
# **********************************
b=a.numpy()
array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]], dtype=float32)
numpy ----->tensor
import numpy as np
a=np.ones([2,5])
array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
# **********************************
b=torch.from_numpy(a)
tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]], dtype=torch.float64)
2.tensor张量与张量与list相互转换相互转换
tensor—>list
a=torch.ones([1,5])
tensor([[1., 1., 1., 1., 1.]])
# ***********************************
b=a.tolist()
[[1.0, 1.0, 1.0, 1.0, 1.0]]
list—>tensor
a=list(range(1,6))
[1, 2, 3, 4, 5] # **********************************
b=torch.tensor(a)
tensor([1, 2, 3, 4, 5])
3.tensor张量见类型转换张量见类型转换
构建一个新的张量,你要转变成不同的类型只需要根据自己的需求选择即可
tensor = torch.Tensor(3, 5)
# torch.long() 将tensor投射为long类型
newtensor = tensor.long()
# torch.half()将tensor投射为半精度浮点类型
newtensor = tensor.half()
# torch.int()将该tensor投射为int类型
newtensor = tensor.int()
# torch.double()将该tensor投射为double类型
newtensor = tensor.double()



















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0