PyTorch 实操笔记
1. 简单介绍
- PyTorch 是一个深度学习框架,主要用于研究和生产环境
- 由Meta AI(Facebook)人工智能研究小组开发的一种基于Lua编写的Torch库的Python实现的深度学习库,目前被广泛应用于学术界和工业界,相较于Tensorflow2.x,PyTorch在API的设计上更加简洁、优雅和易懂。
2. 前置技术依赖
3. 环境配置
- 查看显卡 cuda 版本
1
2
| # windows 命令行中输入命令查看显卡信息
nvidia-smi
|
PyTorch 向下兼容 CUDA 版本,根据 CUDA 版本安装合适的 PyTorch 版本:
- 安装或更新 CUDA
2.1 通过官网安装 CUDA
在 CUDA 官网 下载并安装合适版本的 CUDA
2.2 Conda 安装 CUDA 工具包
- 这种方式可以为每个 Conda 环境单独安装 CUDA 版本,避免版本冲突
1
2
3
4
5
6
7
8
| # CUDA
conda install cuda -c nvidia
# 指定版本安装,例如安装 CUDA 11.8.0
conda install cuda -c nvidia/label/cuda-11.8.0
# 安装完成后,使用以下命令测试安装成功
nvcc -V
|
- 安装 PyTorch
根据官网提供的安装命令安装 PyTorch
1
2
3
4
5
6
7
8
9
10
11
| # 示例:安装带有 CUDA 13.0 支持的 PyTorch
pip3 install torch torchvision --index-url https://download.pytorch.org/whl/cu130
# 验证 CUDA PyTorch
import torch
print(torch.__version__)
print(torch.version.cuda)
print(torch.backends.cudnn.version())
print(torch.cuda.is_available())
print(torch.cuda.get_device_name(0))
|
4. 基础用法
1. 张量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# 张量创建
## 使用数据创建
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
##使用 NumPy 数组创建
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
## 使用已有张量创建
x_ones = torch.ones_like(x_data) # retains the properties of x_data
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
## 通过随机或常量创建
shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
# 张量属性
tensor = torch.rand(3, 4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
# 张量操作
## 移动到 GPU(如果可用)
if torch.cuda.is_available():
tensor = tensor.to("cuda")
print(f"Device tensor is stored on: {tensor.device}")
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:, 1] = 0
print(tensor)
|
5. 常见问题与解决办法
6. tips
7. 参考资料