0. CUDA, Pytorch, gym安装
1. 安装CUDA
官网选择相应的系统与版本,之后通过终端安装。
https://developer.nvidia.com/cuda-downloads
3. 安装Pytorch
从官网选取对应的操作系统与版本,之后使用终端安装。
https://pytorch.org/get-started/locally/
4. 安装gym
pip install gym
1. Tensor创建
x = torch.empty(5,3) #空的5*3矩阵
x = torch.rand(5, 3) #随机填充5*3矩阵
x = torch.zeros(5, 3, dtype = torch.long) #创建值全为0的5*3矩阵,且指定类型为long
x = torch.tensor([5.5, 3]) #直接根据给予的值创建tensor
x = torch.new_ones(5, 3, dtype=torch.double) #在已有tensor的基础上覆写新值为5*3的全1矩阵,类型为double。
x = torch.randn_like(x, dtype=torch.float) #创建新tensor,size和x一样,随机赋值,且类型为float
可以使用torch.Size()查看一个tensor的大小情况。
2. Tensor运算
x = torch.rand(5, 3)
y = torch.rand(5, 3)
res = torch.empty(5, 3)
以下三个等价:
res = x + y
res = torch.add(x, y)
torch.add(x, y, out=res)
in_place 运算,在pytorch中in_place运算都有个下划线后缀
y.add_(x) #相当于python中 y += x
3. tensor取值,Resize操作
Numpy的取值方法都适用
x[:, n] #即取所有数据的第n列数据,也可以是[:,1:3],即取1到2列的数据,含左不含右
例:x = [[0, 1], [2, 3], [4, 5]]
x[:, 1] = [1, 3, 5]
x[1:] = [[2, 3], [4, 5]] #取下标1以后的数据
tensor的Resize操作:
x = torch.rand(4, 4)
z = x.view(16) #变为一行16个元素的矩阵
z = x.view(-1, 8) #变为一列8个元素,多少行根据计算得到,此处是16/8 = 2,所以是2*8的矩阵
4. tensor转换为标准python变量,numpy等
当tensor中只有一个元素时:
x = torch.randn(1) #x = tensor([-1.2951])
x.item() #x = -1.2950637340545654
转Numpy:
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
out:
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
改变Numpy数组的时候,会自动改变tensor
5. CUDA Tensor
if torch.cuda.is_available():
device = torch.device("cuda") # 建立一个CUDA对象
y = torch.ones_like(x, device=device) #直接在GPU创建变量
x = x.to(device) # 将x放入GPU
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` 也可以改变数据类型
out:
tensor([-0.2951], device='cuda:0')
tensor([-0.2951], dtype=torch.float64)
6. 自动求导
x = torch.randn(3, requires_grad=True)
y = x * 2
while y.data.norm() < 1000: #对y进行运算,此处只是表示进行了运算,与求导过程无关
y = y * 2
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v) #对y就行backward,相当于说明对谁进行求导。参数v是求导的系数,具体可去查阅
print(x.grad) #求关于x的导数
out:
tensor([1.0240e+02, 1.0240e+03, 1.0240e-01])
不需要求导时,用no_grad()标记
print(x.requires_grad)
print((x ** 2).requires_grad)
with torch.no_grad():
print((x ** 2).requires_grad)
out:
True
True
False
7. 神经网络
介绍比较多,见pytorch官方指南
其中
torch.nn 只接受 mini-batches,单个的数据需要使用 input.unsqueeze(0)生成虚拟的batch。
nn.Conv2d()有四个参数:nSamples x nChannels x Height x Width.
8. FAQ
- 在macos下使用conda时,安装matplotlib用conda install,不要用pip否则会出问题。
连载中。。。