一边学习吴恩达老师的深度学习课程,一边学习PyTorch深度学习框架,这篇博客就来记录昨天学习的PyTorch基础知识。
tensor性质
import torch
import numpy as np
a = torch.tensor([1,2,3],dtype=torch.int)
print(a)
#形状
print(a.shape)
#属性
print(a.dtype)
#维度
print(a.ndim)
#数据生成
#生成2*3全1矩阵
b1 = torch.ones(2,3)
#生成3*3全0矩阵
b2 = torch.zeros(3,3)
#生成3*4在0-1的矩阵
b3 = torch.rand(3,4)
#生成2*3在0-10之间的矩阵
b4 = torch.randint(0,10,(2,3))
#生成3*4正态分布的矩阵
b5 = torch.randn(3,4)
#view 和reshape的作用一样
b6 = torch.rand(2,3).view(6,1)
#取出一个具体的数值
print(b6[1,0].item())
print(b6[1][0].item())
#将tensor转成narray
b7 = np.array(b6)
#将array转成tensor
b8 = torch.tensor(np.array([1,2,3]))
tensor运算
import torch
a = torch.randint(1,5,(2,3))
b = torch.randint(1,5,(2,3))
print(a)
print(b)
print(a+b)
print(a-b)
print(a*b)
print(a/b)
a1 = torch.randint(1,5,(2,3))
b1 = torch.randint(3,5,(3,5))
#矩阵乘法
res = torch.matmul(a1,b1)
print(res)
#矩阵转置
print(res.T)
#求和
print(torch.sum(res))
#最大
print(torch.max(res))
#最小
print(torch.min(res))
#最大索引
print(torch.argmin(res))
#最小索引
print(torch.argmax(res))
a = torch.arange(1,23)
print(a)
print(a[1])
print(a[2:4])
for i in a:
print(i)
自动求导
import torch
#自动求导
#requires_grad=True 可以计算梯度
x = torch.ones((2,2),requires_grad=True)
y = x+2
z = y*y*3
res = z.mean()
print(res)
res.backward()
print(x.grad)