Pytorch基础知识(1)操作PyTorch的Tensor

定义Tensor数据类型

Tensor默认的数据类型是torch.float32。让我们来看一个例子:

  1. 定义一个默认数据类型的tensor
    下面展示一些 内联代码片
x =  torch.ones(2, 2)
print(x)
print(x.dtype())

tensor([[1., 1.],
		[1., 1.]])
torch.float32
  1. 当定义一个tensor的时候指定数据类型
# define a tensor with specific data type
x = torch.ones(2, 2, dtype=torch.int8)
print(x)
print(x.dtype())

tensor([[1., 1.],
		[1., 1.]], dtype=torch.int8)
torch.int8

改变tensor的数据类型

使用.type方法来改变tensor的数据类型:

  1. 定义一个torch.uint8类型的tensor:
x = torch.ones(1, dtype=torch.uint8)
print(x.dtype)

torch.uint8
  1. 改变数据类型
x = x.type(torch.float)
print(x.type)

torch.float32

把tensor转换为numpy数组

  1. 定义一个tensor
x = torch.rand(2, 2)
print(x)
print(x.dtype)

tensor([[0.8074, 0.5738],
		[0.1123, 0.2345]])
torch.float32
  1. 把tensor转换为numpy数组
y = x.numpy()
print(y)
print(y.dtype)

[[0.8074, 0.5738],
 [0.1123, 0.2345]]
dtype('float32')

把numpy数组转换为tensor

  1. 定义一个numpy数组
import numpy as np
x = np.zeros((2, 2), dtype=np.float32)
print(x)
print(x.dtype)

[[0., 0.],
 [0., 0.]]
float32
  1. 把numpy数组转换为tensor
y = torch.from_numpy(x)
print(y)
print(y.dtype)

tensor([[0., 0.],
 [0., 0.]])
torch.float32

在设备之间移动tensor

PyTorch的tensors默认存储在CPU,可以使用GPU来加速。与numpy相比,这是主要的优势。我们可以使用.to方法来实现将tensors移动到CUDA 设备上。

  1. 在CPU 上定义一个tensor:
x = torch.tensor([1.5, 2])
print(x)
print(x.device)

tensor([1.5, 2.])
cpu
  1. 定义一个CUDA 设备
# define a cuda/gpu device
if torch.cuda.is_available():
	device = torch.device("cuda:0")
  1. 将tensor移动到CUDA上:
x = x.to(device)
print(x)
print(x.device)

tensor([1.5, 2.], device="cuda:0)
cuda:0
  1. 我们也可以将CUDA 上的tensor移动到CPU 上:
# define a cpu device
device = torch.device("cpu")
x = x.to(device)
print(x)
print(x.device)

tensor([1.5, 2.])
cpu
  1. 我们也可以直接在指定的设备上创建tensor:
# define a tensor on device
device = torch.device("cuda:0")
x = torch.ones(2, 2, device=device)
print(x)

tensor([[1., 1.],
		[1., 1.], device="cuda:0")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值