简单
```python
import torch
x = torch.tensor(3.0)
y = torch.tensor(2.0)
x + y, x * y, x / y, x**y
(tensor(5.), tensor(6.), tensor(1.5000), tensor(9.))
x = torch.arange(4)
x
tensor([0, 1, 2, 3])
# 创建一个3行4列的矩阵即其转置
x = torch.arange(12).reshape(3,4)
x
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
x.T
tensor([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
A = torch.arange(20, dtype = torch.float32).reshape(4, 5)
B = A.clone()
A+B, A*B
# 加法是按元素相加,乘法结果是Hadamard积
(tensor([[ 0., 2., 4., 6., 8.],
[10., 12., 14., 16., 18.],
[20., 22., 24., 26., 28.],
[30., 32., 34., 36., 38.]]),
tensor([[ 0., 1., 4., 9., 16.],
[ 25., 36., 49., 64., 81.],
[100., 121., 144., 169., 196.],
[225., 256., 289., 324., 361.]]))
A+1
tensor([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.],
[11., 12., 13., 14., 15.],
[16., 17., 18., 19., 20.]])
A*2
tensor([[ 0., 2., 4., 6., 8.],
[10., 12., 14., 16., 18.],
[20., 22., 24., 26., 28.],
[30., 32., 34., 36., 38.]])
A_sum = A.sum(axis = 0)
A_sum
# 求和函数可以用来降低tensor的维数,A.mean():求平均值,A.numel()是A元素的个数
tensor([30., 34., 38., 42., 46.])
A_sum_two = A.sum(axis = 0,keepdims = True )
A_sum_two
# 非降维求和,求和之后仍保持两个轴
tensor([[30., 34., 38., 42., 46.]])
A.cumsum(axis = 0)
# 这个是求累计和的,第一第二行的累计和赋给第二行,前三行的累计和赋给第三行
tensor([[ 0., 1., 2., 3., 4.],
[ 5., 7., 9., 11., 13.],
[15., 18., 21., 24., 27.],
[30., 34., 38., 42., 46.]])
A
tensor([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.],
[10., 11., 12., 13., 14.],
[15., 16., 17., 18., 19.]])
C = torch.arange(9).reshape(3,3)
D = C.clone()
E= torch.dot(C, D)
E
# 点积只计算向量之间的
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[25], line 3
1 C = torch.arange(9).reshape(3,3)
2 D = C.clone()
----> 3 E = torch.dot(C, D)
4 E
RuntimeError: 1D tensors expected, but got 2D and 2D tensors
C = torch.arange(9).reshape(3,3)
D = torch.arange(3)
E= torch.mv(C, D)
E # mv是矩阵乘向量, mm是矩阵乘矩阵
tensor([ 5, 14, 23])
# 2范数
u = torch.tensor([3.0, -4.0])
uf1 = torch.norm(u) # 这个函数要求数据必须是float的
# 1范数
uf2 = u.abs().sum()
uf1, uf2
(tensor(5.), tensor(7.))