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设计】。

相关文章

Python中字符串格式化str.format的详细介绍

前言 Python 在 2.6 版本中新加了一个字符串格式化方法: str.format() 。它的基本语法是通过 {} 和 : 来代替以前的 %.。 格式化时的占位符语法: rep...

快速解决PyCharm无法引用matplotlib的问题

序 笔者今天用PyCharm安装了一些数据分析的时候比较有用的模块,系统是ubuntu,说实话,ubuntu(linux)在这方面还真是很方便,几条语句就把这几个模块下载安装编译过了,比...

Python利用PyExecJS库执行JS函数的案例分析

Python利用PyExecJS库执行JS函数的案例分析

  在Web渗透流程的暴力登录场景和爬虫抓取场景中,经常会遇到一些登录表单用DES之类的加密方式来加密参数,也就是说,你不搞定这些前端加密,你的编写的脚本是不可能...

Python数据类型详解(三)元祖:tuple

一.基本数据类型   整数:int   字符串:str(注:\t等于一个tab键)   布尔值: bool   列表:list   列表用[]   元祖:tuple   元祖用()...

Python操作CouchDB数据库简单示例

安装python couchDb库: https://pypi.python.org/pypi/CouchDB/0.10 连接服务器 复制代码 代码如下: >>> im...