PyTorch深度学习(二):2. PyTorch的基本运算操作


本文主要讲PyTorch对数据的基本运算操作,奥利给!

1. 对数据的基本运算(加减乘除)

进行基本运算时,操作的数据必须保持形状相同,即均为2行3列或均为4行3列。

1.1 加减乘除的几种方法:

首先生成两组2行3列的随机数

#输入:
a = torch.randint(1,5,(2,3))
b = torch.randint(1,5,(2,3))
print(a)
print(b)

#输出:
tensor([[3, 3, 4],
        [3, 3, 4]])
tensor([[2, 3, 1],
        [3, 4, 4]])

1、直接用“+”进行相加操作

a + b

#输出:
tensor([[5, 6, 5],
        [6, 7, 8]])

2、调用add()函数

torch.add(a,b)

#输出:
tensor([[5, 6, 5],
        [6, 7, 8]])

3、使用前缀“_”进行操作

# a = a + b
# 注意:任何能使张量tensor会发生变化的操作都有前缀‘_’,例如加法:a.add_,减法:b.sub()
a.add_(b)
#表示为: a = a + b

#输出:
tensor([[5, 6, 5],
        [6, 7, 8]])

1.2 取余与取整:

1、取余数

#取余数
a % b

#输出
tensor([[1, 0, 0],
        [0, 3, 0]])

2、取整数

#取整
a//b

#输出
tensor([[2, 2, 5],
        [2, 1, 2]])

1.3 矩阵乘法

调用matmul()函数,注意,要保证数据类型一样才可进行矩阵匀速,比如均为int64或均为float32

1、数据类型的转换

a = torch.randint(1,5,(2,3))
a

#输出
tensor([[3, 2, 2],
        [4, 4, 2]])

查看a和tensor的数据类型

#查看a和tensor的数据类型
a.dtype
tensor.dtype

#输出
torch.int64
torch.float32

转换a的数据类型

a = a.float()
a.dtype

#输出
torch.float32

2、矩阵的乘法运算

tensor = torch.ones(3,5)
tensor

#输出
tensor([[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]])

相乘

#一个2×3的矩阵乘以一个3×5的矩阵,得到一个2×5的矩阵
torch.matmul(a,tensor)

#输出
tensor([[ 7.,  7.,  7.,  7.,  7.],
        [10., 10., 10., 10., 10.]])

2. 对数据的基本运算(数学运算)

定义三行两列随机整数

sample = torch.randint(1,10,(3,2))
#为方便后续运算,转化为浮点数
sample = sample.float()
sample

#显示输出
tensor([[1., 3.],
        [4., 5.],
        [5., 8.]])

2.1 求和函数

torch.sum(sample)

#显示输出
tensor(26)

2.2 最大最小函数

torch.max(sample)
torch.min(sample)

#显示输出
tensor(8)
tensor(1)

2.3 求最值索引函数

注意索引位置从0开始

#求最小值的索引位置,数字从0开始
torch.argmin(sample)

#显示输出
tensor(0)
#求最大值的索引位置,数字从0开始
torch.argmax(sample)

#显示输出
tensor(5)

2.4 求平均值函数

#求平均值
torch.mean(sample)

#显示输出
tensor(4.3333)

2.4 求中位数函数

#求中位数
torch.median(sample)

#显示输出
tensor(4.)

2.5 求开方

#求开方
torch.sqrt(sample)

#显示输出
tensor([[1.0000, 1.7321],
        [2.0000, 2.2361],
        [2.2361, 2.8284]])

2.6 求二次方/高次方

#求平方
sample ** 2

#显示输出
tensor([[ 1.,  9.],
        [16., 25.],
        [25., 64.]])
#求高次方
sample ** 3

#显示输出
tensor([[  1.,  27.],
        [ 64., 125.],
        [125., 512.]])
发布了27 篇原创文章 · 获赞 6 · 访问量 537

猜你喜欢

转载自blog.csdn.net/qq_43246110/article/details/104192441