PyTorch 学习笔记(一)
1 . Tensor
可以认为是一个高维数组,可以使用 GPU 进行加速。
Input:1
2
3
4
5
6
7
8
9
10
11
12import torch as t
x = t.Tensor(5, 3) # 只分配了空间,未初始化
x = t.Tensor([[1, 2], [3, 4]])
print(x)
# 使用 [0, 1] 均匀分布随机初始化二维数组
x = t.rand(5, 3)
print(x)
# 查看 x 的形状
print(x.size())
# 查看 x 中列的个数,两种写法等价
print(x.size()[1])
print(x.size(1))
Output:torch.Size
是 tuple 对象的子类,因此它支持 tuple 的所有操作,如 x.size()[0]
等。
2 . 加法的三种写法。
1 | y = t.rand(5, 3) |
1 | print('最初 y') |
函数名后面带下划线 _
的函数会改变 Tensor 本身。
3 . Tensor 与 Numpy。
1 | x[:, 1] # 选取 x 的第一列所有内容,与 Numpy 相似 |
Tensor 和 Numpy 的数组之间的互操作非常容易且快速,对于 Tensor 不支持的操作,可以先转换为 Numpy 数组处理,之后再转换回 Tensor。
Input:1
2
3
4
5
6
7
8
9
10
11
12
13
14import tensor as t
import numpy as np
a = t.ones(5) # 新建一个全 1 的 Tensor
print(a)
b = a.numpy() # Tensor ----> Numpy
print(b)
a = np.ones(5)
print(a)
b = t.from_numpy(a) # Numpy ----> Tensor
print(b)
# Tensor 与 Numpy 共享内存
b.add_(1) # 以 _ 结尾的函数会修改 Tensor 自身
print(a)
print(b)
Output:
Tensor 和 Numpy 对象共享内存,如果其中一个变了,另外一个也会随之改变。
4 . 如果想获取某一个元素的值,可以使用 scalar.item
,直接 tensor[idx]
得到的还是一个 tensor,一个 0-dim 的 tensor,一般称为 scalar。
Input:1
2
3
4scalar = b[0]
print(scalar)
print(scalar.size()) # 0-dim
print(scalar.item())
Output:
Input:1
2
3
4
5
6 # 注意和 scalar 的区别
tensor = t.tensor([2])
print(tensor)
print(tensor.size())
# 只有一个元素的 tensor 也可以调用 tensor.item()
print(tensor.item())
Output:
5 . t.tensor()
总会进行数据拷贝,新 tensor 和原来的数据不共享内存,如果想要共享内存的话,建议使用 torch.from_numpy()
或者 tensor.detach()
来新建一个 tensor,二者共享内存。
Input:1
2
3
4
5
6
7
8
9
10tensor = t.tensor([3, 4])
old_tensor = tensor
new_tensor = t.tensor(old_tensor)
new_tensor[0] = 1111
print(old_tensor)
print(new_tensor)
new_tensor = old_tensor.detach()
new_tensor[0] = 1111
print(old_tensor)
print(new_tensor)
Output:
6 . Tensor 可以通过 .cuda
方法转换为 GPU 的 Tensor,从而享受 GPU 带来的加速运算。
1 | # 在不支持 CUDA 的机器上,下一步还是在 CPU 上运行 |
笔记来源:《pytorch-book》