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 判断字符串中是否含有汉字或非汉字的实例

model中compile值可以根据需要更改,满足不同的检测需求 #判断一段文本中是否包含简体中文 import re zhmodel = re.compile(u'[\u4e00-...

Python上传package到Pypi(代码简单)

废话不多说了,直接给大家贴代码了。 编写setup.py后 $ python setup.py register $ python setup.py sdist upload 以上...

如何用Python实现简单的Markdown转换器

如何用Python实现简单的Markdown转换器

今天心血来潮,写了一个 Markdown 转换器。 import os, re,webbrowser text = ''' # TextHeader ## Header1 Li...

python写日志封装类实例

本文实例讲述了python实现写日志封装类。分享给大家供大家参考。具体如下: # encoding:utf-8 import sys import logging import ti...

解决python通过cx_Oracle模块连接Oracle乱码的问题

用python连接Oracle是总是乱码,最有可能的是oracle客户端的字符编码设置不对。 本人是在进行数据插入的时候总是报关键字"From"不存在,打印插入的Sql在pl/sql中进...