Deep Learning With PyTorch - Full Course
1. Installation PyTorch
2. Tensor Basics import torch torch.zeros() torch.ones() torch.rand() # 正数随机(0, 1) torch.randn() # 带负数的随机(-1, 1) torch.tensor([[1, 1], [2, 3]]) torch.add(a, b) torch.mul(a, b) # 哈德马积 torch.mm(a, b) # 矩阵相乘 a.t() # 转置 a.add_(1) # 矩阵内数值全部+1 # 也可以直接 a+=1, 在numpy中也可以用 a = torch.rand(2, 4) a.view(-1, 2) #使矩阵从(2, 4)->(4, 2), -1是缺省值自动计算 torch.xxxx(xxxxx ,dtype=float (int32)) # 可以定义数据类型 import numpy as np a = np.ones() b = torch.from_numpy(a) # np.ndarray -> tensor c = b.numpy() # tensor -> np.ndarray # 书中的一些其他基础函数 a = torch.arange(12) # 新定义1-12个元素张量 # tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) x.shape # 显示张量的形状 # torch.Size([12]) x.numel() # 只显示张量的元素数量 # 12 tensor格式是专门为cuda准备的 tensor和np.ndarray 相互转换时, 变量的内存共享, eg: 使用add_, 都会变. if torch.cuda.is_available(): device = torch.device("cuda") x = torch.ones(5, device=device) # 写入显存 y = torch.ones(5) y = y.to(device) # 写入显存2 z = x + y print(z) # z = z.to("cpu") # 只有参数放回内存之后才可以改为numpy格式 z.numpy() # 报错, 显存中的tensor参数不能变成numpy格式 numpy格式无法放入显存
选定显卡
import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" # or # when loading model model.load_state_dict(torch.load(PATH, map_location="cuda:0")) model.to(device) # or when initing the model model_load = NeuralNetMultiClass(input_size, hidden_size, num_classes).to(device) ...