import torch
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
B = A.clone() # 通过分配新内存,将A的一个副本分配给B
print('Original matrix')
print(A)
print(id(A))
print(id(B))
B+=1
print(A)
print(B)
B=A # 不分配
print('Original matrix')
print(A)
print(id(A))
print(id(B))
B+=1
print(A)
print(B)
'''
Original matrix
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]])
140399645950176
140399645950336
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]])
tensor([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[13., 14., 15., 16.],
[17., 18., 19., 20.]])
-------------------------------------
Original matrix
A
140608687278896
140608687278896
tensor([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[13., 14., 15., 16.],
[17., 18., 19., 20.]])
tensor([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[13., 14., 15., 16.],
[17., 18., 19., 20.]])
'''
print(A)
A_sum_axis0 = A.sum(axis=0) #纵轴求和
print(A_sum_axis0, ' \n ',A_sum_axis0.shape)
A_sum_axis1 = A.sum(axis=1) #横轴求和
print(A_sum_axis1, ' \n ',A_sum_axis1.shape)
'''
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]])
tensor([40., 45., 50., 55.])
torch.Size([4])
tensor([ 6., 22., 38., 54., 70.])
torch.Size([5])
'''
B = torch.ones(4, 3)
print(A)
print(B)
print(torch.mm(A, B))
print(torch.norm(B))#元素平方和开根号
'''
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]])
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
tensor([[ 6., 6., 6.],
[22., 22., 22.],
[38., 38., 38.],
[54., 54., 54.],
[70., 70., 70.]])
tensor(3.4641)
'''
B = torch.ones(4, 3)
print(B)
print(B.cumsum(axis=0)) #向下累加
print(B.cumsum(axis=1)) #向右累加
'''
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
tensor([[1., 1., 1.],
[2., 2., 2.],
[3., 3., 3.],
[4., 4., 4.]])
tensor([[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.]])
'''
A= torch.arange(5)
B = torch.arange(5)
print(torch.sum(A*B)==torch.dot(A, B))
# dot 只能做一维计算
'''
tensor(True)
'''
A= torch.arange(12).reshape(2,2,3)
print(A)
print(len(A)) #通道
print(A.shape) #size
print(A.mT) #transpose
'''
tensor([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]])
2
torch.Size([2, 2, 3])
tensor([[[ 0, 3],
[ 1, 4],
[ 2, 5]],
[[ 6, 9],
[ 7, 10],
[ 8, 11]]])
'''
(DL笔记)Dive into Deep Learning -- Linear Algebra
最新推荐文章于 2024-07-25 12:58:40 发布