深度学习3 线性代数

简单

```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.))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rookiexxj01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值