A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
(tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]]),
B = A.clone() # 通过分配新内存,将A的一个副本分配给B
A * B#对应元素相乘
x = torch.arange(4, dtype=torch.float32)
x.sum()#对张量的元素进行求和
A_sum_axis0 = A.sum(axis=0)#对所有行的元素来求和降维
A_sum_axis0, A_sum_axis0.shape
#结果为 (tensor([40., 45., 50., 55.])
A.numel()#求A中元素数量
A.mean(axis=0)#对列求和,在求平均值, A.sum(axis=0) / A.shape[0]#表示矩阵的行数
#调用函数来计算总和或均值时保持轴数不变会很有用
sum_A = A.sum(axis=1, keepdims=True)
#结果为tensor([[ 6.],
# [22.],
# [38.],
# [54.],
# [70.]])
A.cumsum(axis=0)
#结果为:tensor([[ 0., 1., 2., 3.],
# [ 4., 6., 8., 10.],第一行加第二行
# [12., 15., 18., 21.],第三行加第二行
# [24., 28., 32., 36.], .....
# [40., 45., 50., 55.]]) ...
y = torch.ones(4, dtype = torch.float32)
x, y, torch.dot(x, y)#同torch.sum(x * y)
#结果:(tensor([0., 1., 2., 3.]), tensor([1., 1., 1., 1.]), tensor(6.))
A.shape, x.shape, torch.mv(A, x)#矩阵-向量积
结果为:tensor([ 14., 38., 62., 86., 110.])
#L2范数是向量元素平方和的平方根
u = torch.tensor([3.0, -4.0])
torch.norm(u)#结果为5
#L1范数向量元素的绝对值之和
torch.abs(u).sum()
#Frobenius范数(Frobenius norm)是矩阵元素平方和的平方根
torch.norm(torch.ones((4, 9)))#结果为 6
自动求导例题:
import torch
import numpy as np
import matplotlib.pyplot as plt
x=torch.arange(0.,10.,0.1)
print(x)
x.requires_grad_(True)
x1=x.detach()#x在进行求导之后,值就会发生变化,提前为绘图保存一下
y=torch.sin(x)
print(y)
y.sum().backward()
plt.plot(x1,x.grad)
plt.show()
线性代数 pytorch
于 2023-05-16 13:14:35 首次发布