PyTorch张量

 

基本数据类型

  • 标量(0维)
    一维长度为1的张量确实也可以表示张量 为了语义更清晰,在版本PyTorch0.3之后,两个概念从形式上加以区分,并增加了长度为零的 tensor。
  • 张量(1维) Bias or Linear input (单张图片输入)
  • 张量(2维) Linear input batch (多张图片输入)
  • 张量(3维) RNN input Batch (循环神经网络批量输入) [word,sentence,feature]
  • 张量(4维) CNN input Batch (卷积神经网络批量输入) [batch,channel,height,width] ’r’,’g’,’b’三原色通道

张量 Tensors

from __future__ import print_function
import torch

引入pytorch

创建一个 5x3 矩阵, 但是未初始化:

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

创建一个随机初始化的矩阵:

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

创建一个0填充的矩阵,数据类型为long:

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

创建tensor并使用现有数据初始化:

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

根据现有的张量创建张量:

这些方法将重用输入张量的属性,例如, dtype,除非设置新的值进行覆盖

x = x.new_ones(5, 3, dtype=torch.double)      # new_* 方法来创建对象
print(x)

x = torch.randn_like(x, dtype=torch.float)    # 覆盖 dtype!
print(x)                                      #  对象的size 是相同的,只是值和类型发生了变化

获取size

print(x.size())

加法

加法1

y = torch.rand(5, 3)
print(x + y)
tensor([[ 0.2218,  0.8329, -1.3406],
        [-0.2737,  0.8382,  1.4644],
        [-0.3806,  0.2332, -0.4300],
        [-0.6603,  1.8713,  1.9648],
        [ 1.4351, -0.6195, -0.5985]])

加法2

print(torch.add(x, y))

提供输出tensor作为参数

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

替换

# adds x to y
y.add_(x)
print(y)

任何 以_ 结尾的操作都会用结果替换原变量. 例如: x.copy_(y), x.t_(), 都会改变 x.

使用索引操作张量

print(x[:, 1])
tensor([ 1.6401,  0.3637,  1.5745, -1.9971,  1.2926])

torch.view 改变张量的维度和大小

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  #  size -1 从其他维度推断
print(x.size(), y.size(), z.size())

如果你有只有一个元素的张量

使用.item()来得到Python数据类型的数值

x = torch.randn(1)
print(x)
print(x.item())
tensor([-0.4353])
-0.43528521060943604