1.pytorch基础知识

1.0 前言

主要记录一些初学pytorch的常用操作。

# 表示注释 ##表示输出内容

所用环境为Jupyter,pytorch。python版本为3.8。

1.1 tensor的属性

import torch

a=torch.tensor([1,2,3],dtype=int)

# 打印
print(a)
## tensor([1, 2, 3])

# 查看数据类型
a.dtype
## torch.int64

b=torch.tensor([4,5,6],dtype=float)
print(b)
## tensor([4., 5., 6.], dtype=torch.float64)

# 查看数据的维度
tensor.ndim
## 2

# 查看数据的形状1
tensor.shape
## torch.Size([2, 3])

# 查看数据形状2
tensor.size()
## torch.Size([2, 3])

1.2 数据的生成

import torch

# 生成一个两行三列全都为1的矩阵
torch.ones(2,3)
##tensor([[0., 0., 0.],
##        [0., 0., 0.],
##        [0., 0., 0.]])

# 生成一个三行四列的随机数,将光标移到括号内按shift+Table可以查看生成的详细规则
torch.rand(3,4)
##tensor([[2.9515e-01, 7.3428e-01, 8.9959e-01, 6.3524e-01],
##        [5.3016e-01, 3.9627e-01, 8.7005e-01, 5.7334e-04],
##        [2.3536e-01, 4.9142e-01, 3.9047e-01, 9.7247e-01]])

# 生成随机整数,前两个参数表示范围,最后一个括号表示生成形状,下述即为生成0-10,两行三列的随机整数
torch.randint(0,10,(2,3))
##tensor([[6, 9, 7],
##        [5, 6, 6]])

# 生成一个三行四列满足标准正态分布的随机数
torch.randn(3,4)
##tensor([[-0.1052,  0.2741, -0.5110, -0.0900],
##        [ 0.9309,  0.5888, -0.4381,  1.0873],
##        [ 0.5446, -0.5408, -0.9702,  1.8956]])
# 先创建一个a
a=torch.tensor([[1,2],[3,4],[5,6]])
a
##tensor([[1, 2],
##        [3, 4],
##        [5, 6]])

# 生成一个随机的,但是和上述a相似的数据
b=torch.rand_like(a,dtype=float)
b
##tensor([[0.2532, 0.5850],
##        [0.5458, 0.8853],
##        [0.6719, 0.1596]], dtype=torch.float64)

print(b.shape)
## torch.Size([3, 2])

# view的作用是修改数据的维度,也可以使用reshape
c=b.view(6)
c
##tensor([0.2532, 0.5850, 0.5458, 0.8853, 0.6719, 0.1596], ##dtype=torch.float64)

c.shape
## torch.Size([6])

d=c.view(2,3)
d
##tensor([[0.2532, 0.5850, 0.5458],
##        [0.8853, 0.6719, 0.1596]], dtype=torch.float64)

d=d.reshape(6)
d
##tensor([0.2532, 0.5850, 0.5458, 0.8853, 0.6719, 0.1596],  ##dtype=torch.float64)

#获取对应元素
d[1]
## tensor(0.5850, dtype=torch.float64)

d[1].item()
## 0.5849620756308062

# 导入numpy
import numpy as np

# 将上述的d转化为numpy中的数组
e=np.array(d)
e
##array([0.25321075, 0.58496208, 0.54582996, 0.88534755, 0.67190851,
##       0.15958087])

array=np.array([1,2,3])
array
## array([1, 2, 3])

# 将array转换为tensor
tensor=torch.tensor(array)
tensor
## tensor([1, 2, 3], dtype=torch.int32)

1.3 基本运算

import torch

a=torch.randint(1,5,(2,3))
b=torch.randint(1,5,(2,3))
print(a)
print(b)
## tensor([[3, 4, 3],
##        [1, 3, 1]])
## tensor([[2, 4, 2],
##        [4, 1, 1]])

# 加法即为对应位置相加,也可以使用torch.add()
a+b
## tensor([[5, 8, 5],
##        [5, 4, 2]])

c=torch.add(a,b)
c
## tensor([[5, 8, 5],
##        [5, 4, 2]])

# add()可以有第三个参数,在里面存入结果
result=torch.zeros(2,3)
torch.add(a,b,out=result)
result
## tensor([[5., 8., 5.],
##        [5., 4., 2.]])

# 下述操作即为 a=a+b
# 注意 任何使张量tensor发生变化的操作都有一个前缀'_',例如: a.add_(),a.sub_()
a.add_(b)
a
## tensor([[5, 8, 5],
##        [5, 4, 2]])

a-b
## tensor([[3, 4, 3],
##        [1, 3, 1]])

a*b
## tensor([[10, 32, 10],
##        [20,  4,  2]])

a/b
## tensor([[2.5000, 2.0000, 2.5000],
##        [1.2500, 4.0000, 2.0000]])

# 取余
a%b
## tensor([[1, 0, 1],
##        [1, 0, 0]])

# 整除
a//b
## tensor([[2, 2, 2],
##        [1, 4, 2]])

tensor=torch.ones(3,5)
tensor
## tensor([[1., 1., 1., 1., 1.],
##        [1., 1., 1., 1., 1.],
##        [1., 1., 1., 1., 1.]])

a=a.float()
a
## tensor([[5., 8., 5.],
##        [5., 4., 2.]])

# 矩阵乘法 a为2×3 tensor为3×5,可以进行
# 同时注意数据类型应一致
torch.matmul(a,tensor)
## tensor([[18., 18., 18., 18., 18.],
##        [11., 11., 11., 11., 11.]])

# 矩阵的转置
a.T
## tensor([[5., 5.],
##        [8., 4.],
##        [5., 2.]])

sample=torch.rand(3,2)
sample
## tensor([[0.5270, 0.9099],
##        [0.1966, 0.1493],
##        [0.0846, 0.6870]])

# 求和
torch.sum(sample)
## tensor(2.5544)

# 最小值
torch.min(sample)
## tensor(0.0846)

# 最大值
torch.max(sample)
## tensor(0.9099)

#求最小值所在的位置
torch.argmin(sample)
## tensor(4)

#求最大值所在的位置
torch.argmax(sample)
## tensor(1)

# 求平均值
torch.mean(sample)
## tensor(0.4257)

# 求中位数
torch.median(sample)
## tensor(0.1966)

# 求开方
torch.sqrt(sample)
## tensor([[0.7260, 0.9539],
##        [0.4434, 0.3864],
##        [0.2909, 0.8288]])

# 求平方
sample**2
## tensor([[0.2778, 0.8279],
##        [0.0387, 0.0223],
##        [0.0072, 0.4719]])

1.4 数据的索引

import torch

tensor=torch.arange(2,14)
tensor
## tensor([ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13])

# 从左往右取是从0开始 从右往左是从-1开始
print(tensor[0])
print(tensor[-1])
## tensor(2)
## tensor(13)

# 连续取
print(tensor[1:4])
## tensor([3, 4, 5])

print(tensor[2:-1])
## tensor([ 4,  5,  6,  7,  8,  9, 10, 11, 12])

# 冒号左边啥都没有说明从头开始
# 冒号右边啥都没有说明取到最后
print(tensor[:5])
print(tensor[-3:])
## tensor([2, 3, 4, 5, 6])
## tensor([11, 12, 13])

# 可以用下述方式连续取出指定值
index=[1,1,2,6,7]
tensor[index]
## tensor([3, 3, 4, 8, 9])

# 遍历
for t in tensor:
    print(t)
## tensor(2)
## tensor(3)
## tensor(4)
## tensor(5)
## tensor(6)
## tensor(7)
## tensor(8)
## tensor(9)
## tensor(10)
## tensor(11)
## tensor(12)
## tensor(13)

1.5 自动求导

import torch

# 后面一个参数代表可以计算梯度
x=torch.ones((2,2),requires_grad=True)
x
## tensor([[1., 1.],
##        [1., 1.]], requires_grad=True)

y=x+2
z=y*y*3
out=z.mean()
out
## tensor(27., grad_fn=<MeanBackward0>)

#求out关于x的导数
out.backward()
print(x.grad)
## tensor([[4.5000, 4.5000],
##        [4.5000, 4.5000]])