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

yipeiwu_com5年前Python基础

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

相关文章

django 邮件发送模块smtp使用详解

前言 在Python中已经内置了一个smtp邮件发送模块,Django在此基础上进行了简单地封装,让我们在Django环境中可以更方便更灵活的发送邮件。 所有的功能都在django.co...

Django框架视图介绍与使用详解

Django框架视图介绍与使用详解

本文实例讲述了Django框架视图介绍与使用。分享给大家供大家参考,具体如下: 视图 视图:即一个python函数,可以叫 视图函数,或者简称 视图,定义在 应用/views.py...

对python csv模块配置分隔符和引用符详解

如下所示: file = open('./abc.csv') csv.reader(file, delimiter=',', quotechar='"') 说明:delimiter...

java中的控制结构(if,循环)详解

前几天在看一个camera CTS bug时,结果在一个java for循环上有点蒙。正好赶上这个点总结一下。 java中的控制结构: 条件结构 这里主要是一些if,...

使用Python判断质数(素数)的简单方法讲解

质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数整除的数。素数在数论中有着很重要的地位。比1大但不是素数的数称为合数。1和0既非素数也非合数。质数是与合数相...