温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

pytorch中tensor张量数据类型的转化方式

发布时间:2020-09-21 14:31:17 来源:脚本之家 阅读:181 作者:|晴天| 栏目:开发技术

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()

# torch.float()将该tensor投射为float类型
newtensor = tensor.float()

# torch.char()将该tensor投射为char类型
newtensor = tensor.char()

# torch.byte()将该tensor投射为byte类型
newtensor = tensor.byte()

# torch.short()将该tensor投射为short类型
newtensor = tensor.short()

4.type_as() 将张量转换成指定类型张量

>>> a=torch.Tensor(2,5)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30],
    [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])
>>> b=torch.IntTensor(1,2)
>>> b
tensor([[16843009,    1]], dtype=torch.int32)
>>> a.type_as(b)
tensor([[     0, -2147483648,      0,      0, -2147483648],
    [-2147483648, -2147483648,      0, -2147483648, -2147483648]],
    dtype=torch.int32)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30],
    [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])

以上这篇pytorch中tensor张量数据类型的转化方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI