脚本专栏 
首页 > 脚本专栏 > 浏览文章

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

(编辑:jimmy 日期: 2025/3/4 浏览:3 次 )

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张量数据类型的转化方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:Pytorch 多块GPU的使用详解
下一篇:Pyorch之numpy与torch之间相互转换方式
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?