-
环境搭建参考如下链接就好:
https://pytorch.org/ -
Pytorch基本语法
1.导入库,查看torch版本
from __future__ import print_function
import torch
import numpy as np
print (torch.__version__)
1.5.0+cpu
2.定义矩阵
#定义矩阵
x = torch.empty(2,2)
print (x)
tensor([[-6.2004e+22, 4.5916e-41],
[-6.2004e+22, 4.5916e-41]])
3.定义随机初始化矩阵
#定义随机初始化矩阵
x = torch.randn(2,2)
print (x)
tensor([[-0.2061, 0.3232],
[ 0.0651, 1.1239]])
4.定义初始化为0
#定义初始化为0
x = torch.zeros(3,3)
print (x)
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
5.tensor
#tensor
x = torch.tensor([5.1,2.,3.,1.])
print (x)
tensor([5.1000, 2.0000, 3.0000, 1.0000])
6.操作(加)
# 操作
a = torch.tensor([1.,2,2,3,3,4,5,6,1,1,1,1])
b = torch.tensor([2,2,3,4,5,5,6,4,1,1,1,1])
c = a.add(b)
print (c)
tensor([ 3., 4., 5., 7., 8., 9., 11., 10., 2., 2., 2., 2.])
7.维度变换
#维度变换
a = a.view(4,-1)
b = b.view(4,-1)
c = torch.add(a,b)
print (c,a.size(),b.size())
tensor([[ 3., 4., 5.],
[ 7., 8., 9.],
[11., 10., 2.],
[ 2., 2., 2.]]) torch.Size([4, 3]) torch.Size([4, 3])
8.转为numpy
na = a.numpy()
nb = b.numpy()
print (na,nb)
[[1. 2. 2.]
[3. 3. 4.]
[5. 6. 1.]
[1. 1. 1.]]
[[2 2 3]
[4 5 5]
[6 4 1]
[1 1 1]]
- np操作
# np操作
d = np.array([1,1,1,1,2,2,23,3,3,3,3,3],dtype=np.float32)
print (d.reshape(4,3))
d = torch.from_numpy(d.reshape(4,3))
s = torch.sub(c,d)
print (s,s.size())
[[ 1. 1. 1.]
[ 1. 2. 2.]
[23. 3. 3.]
[ 3. 3. 3.]]
tensor([[ 2., 3., 4.],
[ 6., 6., 7.],
[-12., 7., -1.],
[ -1., -1., -1.]]) torch.Size([4, 3])
10.use cuda
# use cuda
if torch.cuda.is_available():
res = d.cuda() + b.cuda()
print (res)
11.自动梯度
# 自动梯度
x = torch.randn(1, 5, requires_grad=True)
y = torch.randn(5,3,requires_grad=True)
z = torch.randn(3,1,requires_grad=True)
print ('\nx:',x,'\ny:',y,'\nz:',z)
xy = torch.matmul(x,y)
xyz = torch.matmul(xy,z)
xyz.backward()
print (x.grad,y.grad,z.grad)
x: tensor([[-0.7731, 0.3810, -0.5315, -1.2280, -1.3546]], requires_grad=True)
y: tensor([[ 0.7235, -1.2894, -1.3353],
[-0.1372, 0.2929, 1.0247],
[-0.1232, 0.5163, -0.1604],
[-0.3164, 0.9756, -0.4557],
[ 1.0728, -0.0426, -1.2801]], requires_grad=True)
z: tensor([[ 0.8124],
[-1.5013],
[-0.3891]], requires_grad=True)
tensor([[ 3.0432, -0.9499, -0.8128, -1.5444, 1.4336]]) tensor([[-0.6280, 1.1606, 0.3008],
[ 0.3096, -0.5721, -0.1483],
[-0.4318, 0.7980, 0.2068],
[-0.9976, 1.8436, 0.4779],
[-1.1005, 2.0337, 0.5271]]) tensor([[-1.6109],
[-0.3063],
[ 3.8016]])