1、张量基本操作
张量表示由一些数据组成的数组,张量可以有多个维度
张量的一些操作:shape属性、size()方法、reshape()方法、numel()方法
a = torch.tensor([1, 2, 3, 4, 5, 4, 3, 6])
print(a.shape)
print(a.size())
print(a.numel())
b = torch.tensor([[1, 2, 3, 4, 5, 4, 3, 6], [1, 2, 3, 4, 5, 4, 3, 6]])
"""shape属性和size()方法都可以得到tensor的维度"""
print(b.shape)
print(b.size())
print(b.shape[0])
print(b.size(1))
# numel()方法获得tensor中的元素个数
print(b.numel())
b = torch.tensor([[1, 2, 3, 4, 5, 4, 3, 6], [1, 2, 3, 4, 5, 4, 3, 6]])
x1 = b.reshape(4, 4)
print(x1)
x2 = b.reshape(8, 2)
print(x2)
运行结果


张量拼接操作
# torch.arange()生成一个tensor类型的数据,第一个参数表示tensor中元素取值的范围,dtype表示元素的类型
x = torch.arange(12, dtype=torch.float32).reshape(3, 4)
print(x)
# 利用torch.tensor()生成一个tensor数据
y = torch.tensor([[2, 3, 4, 5], [1, 3, 5, 4], [0, 2, 4, 6]])
print(y)
# torch.cat()拼接tensor,第一个参数是要拼接的两个tensor,第二个参数表示拼接的维度:0表示按行拼接,1表示按列拼接
z1 = torch.cat((x, y), dim=0)
print(z1)
z2 = torch.cat((x, y), dim=1)
print(z2)
运行结果

张量求和操作,求和后的结果为0维的张量(一个数)
对上面代码中的z1求和
z1 = torch.tensor([[0., 1., 2., 3.],
[4., 5., 6., 7.],
[8., 9., 10., 11.],
[2., 3., 4., 5.],
[1., 3., 5., 4.],
[0., 2., 4., 6.]])
print(z1)
# .sum()方法可以对张量中所有元素求和
s = z1.sum()
print(s)
运行结果:

广播机制,不同尺寸tensor计算
a = torch.arange(3).reshape(3, 1)
print('a', a)
b = torch.arange(2).reshape(1, 2)
print('b', b)
c = a + b
print('c', c)
运行结果

张量求和
A = torch.arange(20.0).reshape(5, 4)
print("向量A:", A)
B = A.clone()
print("向量B:", B)
print("向量元素求和:", A.sum())
print("向量元素个数:", A.numel())
print("向量的平均值(.mean()方法):", A.mean())
print("向量的平均值(求和再除以个数):", A.sum()/A.numel())
print(A.sum(axis=0))
print('保持维度', A.sum(axis=1, keepdim=True))

向量点积操作
"""向量的点积支持一维向量"""
x = torch.arange(5)
y = torch.arange(5)
print('向量点积', torch.dot(x, y))
"""多维向量之间相乘是按元素对应相乘"""
A = torch.arange(20.0).reshape(5, 4)
print("向量A:", A)
B = A.clone()
print("向量B:", B)
print('向量相乘', A*B)
![]()

矩阵与向量的相乘torch.mv(A,B)
"""矩阵与向量的积torch.mv(A, B)"""
a = torch.ones(3, 3)
b = torch.arange(3.0)
print('矩阵与向量的积', torch.mv(a, b))
![]()
张量按照矩阵方式相乘torch.mm(A,B)
"""多维向量之间按矩阵方式相乘,torch.mm(A, B)"""
# 创建一个3*3的单位矩阵
a1 = torch.ones(3, 3)
b1 = torch.arange(9.0).reshape(3, 3)
print('a1', a1)
print('b1', b1)
print('a1与b1按矩阵方式相乘', torch.mm(a1, b1))

对张量进行降维(通过.sum()方法按指定轴求和降维)
# 创建一个三维向量(两个5*4向量组成的三维向量)
d = torch.arange(40).reshape(2, 5, 4)
print('三维张量:', d)
# 降维(按照维度进行求和,比如三维向量d的三个维度:0是channel,1是行数,2是列数)
# 对某个维度降维就是按照这个维度将张量挤压(求和)
d_sum_axis0 = d.sum(axis=0)
# 将d按照维度0挤压到一起,就是将两个5*4的二维矩阵相加
print('按维度0降维:', d_sum_axis0)
# 按照行进行降维,即将列压缩到一起,行的维度就降低了
d_sum_axis1 = d.sum(axis=1)
print(d_sum_axis1)
# 按照列降维,即将行压缩到一起,列的维度就降低了
d_sum_axis2 = d.sum(axis=2)
print(d_sum_axis2)

Flatten函数
import torch
# torch.randn()从01正态分布中生成一个四维的32*1*5*5的张量
a = torch.randn(32, 1, 5, 5)
print(a)
Flaten = torch.nn.Flatten(1, 3)
# print(out.shape())
out = Flaten(a)
print(out)
print(out.size())
Flaten1 = torch.nn.Flatten(0, 2)
out1 = Flaten1(a)
print(out1)
print(out1.size())

本文介绍了PyTorch中的张量操作,包括张量的shape、size、reshape、numel等属性和方法,以及张量的拼接、求和。此外,还探讨了广播机制在不同尺寸张量计算中的应用,以及张量的矩阵乘法和降维操作。

被折叠的 条评论
为什么被折叠?



