转自:https://blog.csdn.net/weixin_40446557/article/details/88221851

1. Pytorch上的数据类型

Pytorch的类型可以分为CPU和GPU上的Tensor, 它们拥有的数据类型是基本上是一样的:

  • tensor.FloatTensor
  • tensor.LongTensor
  • tensor.ByteTensor
  • tensor.CharTensor
  • tensor.ShortTensor
  • tensor.IntTensor
  • torch.LongTensor

其中torch.Tensor是默认的tensor.FloatTensor的简称。

2. pytorch数据类型之间的转换

tensor = torch.Tensor(3, 5)
## torch.long() 将tensor投射为long类型:
newtensor = torch.long()
## torch.int()将该tensor投射为int类型:
newtensor = torch.int()
## torch.double()将该tensor投射为double类型:
newtensor = torch.double()

一般,只要在Tensor后加long(), int(), double(), float(), byte()等函数就能将Tensor的类型进行转换
除此之外,可以使用type()函数,data为Tensor数据类型,data.type()给出data的类型,如果使用data.type(torch.FloatTensor)则强制转换为torch.FloatTensor类型的张量, 如果不知道什么类型,可以使用tensor_1.type_as(tensor_2), 将tensor_1转换成tensor_2

self = torch.LongTensor(3, 5)
# 转换为其他类型
print self.type(torch.FloatTensor)

3. cuda数据类型,cpu类型和一般的数据类型

  • 如果没有特别说明:tensor是cpu上的变量
  • 使用gpu张量:tensor.cuda()
  • 使用cpu张量:tensor.cpu()
  • Variable转换成普通的Tensor: variable.data()
  • Tesnor转换成numpy array的格式:tensor.numpy()
  • numpy数据转换成Tensor: torch.from_numpy(np_data)
  • Tensor转换成Variable: Variable(tensor)

Pytorch数据类似pytorch中的tensor, 更重要的是tensor可以使用GPU来加速,并且变成Variable可以实现自动求导的功能,Variable是对Tensor对象的封装。

转载链接:https://www.jianshu.com/p/eb7c6af28922

逻辑值True和False转成0和1. +0

print(y)
print(y+0)
## 输出结果
tensor([ True, False, False,  True,  True, False, False,  True,  True, False])
tensor([1, 0, 0, 1, 1, 0, 0, 1, 1, 0])

3. torch转成numpy数据

tensor.numpy()

import torch
a = torch.tensor(5.388) ## 创建torch变量
print('1',type(a))
a = a.numpy() ## torch转成numpy
print('2',type(a))
a = a.item()## numpy 标量转 python 标量
print('3',type(a))

在这里插入图片描述

4. numpy转成python数据

  • numpy标量转python类型
    numpy_scalar.item()

  • numpy数组转python类型
    numpy_array.tolist()

a = np.array([5.388,0.5])
b = a.tolist()
print('a',type(a))
print('b',type(b))

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐