pytorch入门,Tensors张量

什么是张量

https://www.zhihu.com/question/23720923知乎可以看看,虽然看不太懂吧

pytorch中张量

张量(Tensors)

张量类似于numpy的ndarrays,不同之处在于张量可以使用GPU来加快计算。

from __future__ import print_function
import torch

构建一个未初始化的5*3的矩阵:

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

输出 :

1.00000e-10 *
 -1.1314  0.0000 -1.1314
  0.0000  0.0000  0.0000
  0.0000  0.0000  0.0000
  0.0000  0.0000  0.0000
  0.0000  0.0000  0.0000
[torch.FloatTensor of size 5x3]

构建一个随机初始化的矩阵

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

输出:

[[0.2475, 0.0531, 0.1944],
[0.8902, 0.5929, 0.9189],
[0.8254, 0.4602, 0.8709],
[0.2652, 0.8813, 0.9607],
[0.9615, 0.5618, 0.3431]]
[torch.FloatTensor of size 5x3]

获取矩阵的大小:

print(x.size())

输出:

torch.Size([5, 3])

注意

torch.Size实际上是一个元组,所以它支持元组相同的操作。

操作

张量上的操作有多重语法形式,下面我们一加法为例进行讲解。

语法1

y = torch.rand(5,3)
#输出
print(y)
[[0.2492, 0.1385, 0.9537],
[0.2903, 0.9815, 0.4912],
[0.9231, 0.8237, 0.1434],
[0.5521, 0.2803, 0.3559],
[0.5036, 0.8756, 0.6960]]
y = torch.rand(5, 3)
print(x + y)

输出:

[[0.4967, 0.1916, 1.1481],
[1.1805, 1.5744, 1.4101],
[1.7485, 1.2839, 1.0143],
[0.8173, 1.1616, 1.3166],
[1.4651, 1.4374, 1.0391]]
[torch.FloatTensor of size 5x3]

语法二

print(torch.add(x, y))

输出:

[[0.4967, 0.1916, 1.1481],
[1.1805, 1.5744, 1.4101],
[1.7485, 1.2839, 1.0143],
[0.8173, 1.1616, 1.3166],
[1.4651, 1.4374, 1.0391]]
[torch.FloatTensor of size 5x3]

语法三:给出一个输出向量

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

输出:

[[0.4967, 0.1916, 1.1481],
[1.1805, 1.5744, 1.4101],
[1.7485, 1.2839, 1.0143],
[0.8173, 1.1616, 1.3166],
[1.4651, 1.4374, 1.0391]]
[torch.FloatTensor of size 5x3]

语法四:原地操作(in-place)

# 把x加到y上
y.add_(x)
print(y)

输出:

[[0.4967, 0.1916, 1.1481],
[1.1805, 1.5744, 1.4101],
[1.7485, 1.2839, 1.0143],
[0.8173, 1.1616, 1.3166],
[1.4651, 1.4374, 1.0391]]
[torch.FloatTensor of size 5x3]

注意

任何在原地(in-place)改变张量的操作都有一个’_’后缀。例如x.copy_(y), x.t_()操作将改变x.

你可以使用所有的numpy索引操作。

print(x[:, 1])

输出:

[0.3655, 0.7734, 0.0316, 0.9519, 0.3036]
[torch.FloatTensor of size 5]

 

你可能感兴趣的:(深度学习)