Pytorch | Tensor

创建Tensor

创建一个 5x3 的未初始化的 Tensor:

x = torch.empty(5, 3)
print(x)

创建一个 5x3 的随机初始化的 Tensor:

x = torch.rand(5, 3)
print(x)

创建一个 5x3 的long型全0的 Tensor:

x = torch.zeros(5, 3, dtype=torch.long)
print(x)

直接根据数据创建

x = torch.tensor([5.5, 3])
print(x)

tensor([5.5000, 3.0000])

还可以通过现有的Tensor来创建,此方法会默认重用输入Tensor的一些属性,例如数据类型,除非自定义数据类型。

# 返回的tensor默认具有相同的torch.dtype和torch.device
x = x.new_ones(5, 3, dtype=torch.float64) 
print(x)

# 指定新的数据类型
x = torch.randn_like(x, dtype=torch.float)
print(x)

我们可以通过 shape 或者 size() 来获取 Tensor 的形状

print(x.size())

torch.Size([5, 3])

print(x.shape)

torch.Size([5, 3])

注意:返回的torch.Size其实就是一个tuple, 支持所有tuple的操作。

操作

算术操作

y = torch.rand(5, 3)
print(x + y)
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)

索引

我们还可以使用类似NumPy的索引操作来访问Tensor的一部分,需要注意的是:索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改。

y = x[0, :]
y += 1
print(y)
print(x[0, :])   # 源tensor也被修改了

改变形状

用 view() 来改变 Tensor 的形状:

y = x.view(15)
z = x.view(-1, 5)  # -1所指的维度可以根据其他维度的值推算出来,自适应
print(x.size(), y.size(), z.size())

注意 view() 返回的新tensor与源tensor共享内存,也即更改其中的一个,另外一个也会跟着改变。

广播机制

x = torch.arange(1, 3).view(1, 2)
print(x)
y = torch.arange(1, 4).view(3, 1)
print(y)
print(x + y)

运算的内存开销

x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
print(id_before)
y = y + x
print("y: ", y)
print(id(y) == id_before)
print(id(y))

4784743336
y:  tensor([4, 6])
False
4784545152

x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y[:] = y + x
print(y)
print(id(y) == id_before) 

tensor([4, 6])
True

x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
torch.add(x, y, out=y)  # y += x, y.add_(x)
print(id(y) == id_before)

True

Tensor 和 NumPy 相互转换

numpy() 和 from_numpy() 这两个函数产生的 Tensor 和 NumPy array实际是使用的相同的内存,改变其中一个时另一个也会改变。
Tensor 转 NumPy

a = torch.ones(5)
b = a.numpy()
print(a, b)

a += 1
print(a, b)

b += 1
print(a, b)

Numpy数组转Tensor

import numpy as np

a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)

a += 1
print(a, b)

b += 1
print(a, b)

Tensor on GPU

# 以下代码只有再Pytorch GPU版本上才会执行
if torch.cuda.is_available():
    device = torch.device("cuda")   # GPU
    y = torch.one_like(x, device=device) # 直接创建一个再GPU上的Tensor
    x = x.to(device)     # 等价于 .to("cuda")
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))  # to()还可以同时更改数据类型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值