# 什么是Pytorch - Pytorch入门笔记

Mr::Z::
4个月前 阅读 24 点赞 0

• 替代NumPy以使用GPU的功能
• 提供最大灵活性和速度的深度学习研究平台

## 入门

### 张量

from __future__ import print_function
import torch


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


tensor([[2.2175e-06, 9.3046e-43, 2.2175e-06, 9.3046e-43],
[2.2175e-06, 9.3046e-43, 2.2175e-06, 9.3046e-43],
[2.2175e-06, 9.3046e-43, 2.2175e-06, 9.3046e-43],
[1.0720e-05, 9.3046e-43, 5.7422e-06, 9.3046e-43],
[1.0691e-05, 9.3046e-43, 1.0702e-05, 9.3046e-43]])


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


tensor([[0.2217, 0.2328, 0.2461, 0.9303],
[0.6475, 0.5343, 0.2883, 0.7229],
[0.4985, 0.3712, 0.0861, 0.9239],
[0.8324, 0.2922, 0.7670, 0.1293],
[0.1383, 0.6214, 0.5711, 0.6211]])


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


tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])


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


tensor([5.5000, 3.0000])


x = x.new_ones(5, 3, dtype=torch.double)      # new_* methods take in sizes
print(x)

x = torch.randn_like(x, dtype=torch.float)    # override dtype!
print(x)                                      # result has the same size


tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[ 0.7439,  1.5300,  1.3811],
[-1.7157,  1.5165, -0.3656],
[-0.3837, -1.0080,  0.6171],
[ 1.5008,  0.7158,  1.2910],
[-0.8027,  1.5907,  0.8117]])


print(x.size())


torch.Size([5, 3])


torch.Size 实际上是一个元组，因此它支持所有元组操作。

### 运算方法

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


tensor([[ 0.9677,  1.6589,  1.9352],
[-1.3216,  1.9978, -0.1499],
[ 0.0919, -0.0465,  1.1896],
[ 2.1469,  1.4338,  2.0504],
[ 0.0121,  2.0782,  0.9128]])


print(torch.add(x, y))


tensor([[ 0.9677,  1.6589,  1.9352],
[-1.3216,  1.9978, -0.1499],
[ 0.0919, -0.0465,  1.1896],
[ 2.1469,  1.4338,  2.0504],
[ 0.0121,  2.0782,  0.9128]])


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


tensor([[ 0.9677,  1.6589,  1.9352],
[-1.3216,  1.9978, -0.1499],
[ 0.0919, -0.0465,  1.1896],
[ 2.1469,  1.4338,  2.0504],
[ 0.0121,  2.0782,  0.9128]])


# adds x to y
print(y)


tensor([[ 0.9677,  1.6589,  1.9352],
[-1.3216,  1.9978, -0.1499],
[ 0.0919, -0.0465,  1.1896],
[ 2.1469,  1.4338,  2.0504],
[ 0.0121,  2.0782,  0.9128]])


print(x[:, 1])


tensor([ 1.5300,  1.5165, -1.0080,  0.7158,  1.5907])


x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())


torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])


x = torch.randn(1)
print(x)
print(x.item())


tensor([0.7378])
0.7378432154655457