动手深度学习V2

chapter2-3

import torch
import os
import numpy as np
import pandas as pd

# 0维是最外面的括号 1维是次左边的括号 从左到右维度升高
x = torch.arange(12, dtype=torch.float32).reshape(3, 4)
print(x)

# 0维求和 1维求和 轴0全部元素求和 12 15 18 211全部元素求和 6 22 38 
sum0 = torch.sum(x, dim=0)
sum1 = torch.sum(x, dim=1)
print(sum0)
print(sum1)

# 多维张量汇总轴的总值
x = torch.arange(24, dtype=torch.float32).reshape(2, 3, 4)
print(x)
sum0 = torch.sum(x, dim = 0)
print(sum0)

a = torch.tensor([[1, 2, 3], 
                  [4, 5, 6],
                  [7, 8, 9]])
a1 =  torch.sum(a)
a2 =  torch.sum(a, dim=0)# dim是被坍缩的维度
a3 =  torch.sum(a, dim=1)
a4 =  torch.sum(a, dim = [0, 1]) # 这个是全部元素进行求和等价于a1
a5 =  torch.sum(a, dim=(0, ), keepdim=True) # keepdim保持维度不变 不会坍缩
print(a)
print(a1)
print(a2)
print(a3)
print(a4)
print(a5)

# 张量的点积dot product 相同位置的按照元素乘积
x = torch.arange(4, dtype=torch.float32)
y = torch.ones(4, dtype=torch.float32)
print(x)
print(y)
ans = torch.dot(x, y) # 0 * 1 + 1 * 1 + 2 * 1 + 3 * 1 
print(ans)

# 矩阵向量积
# 调用mv函数 矩阵A*向量X 遵循的是A的列数和X的行数一样 这点和矩阵的乘法规则是一样的
A = torch.tensor([[1, 2, 3], 
                  [4, 5, 6]], dtype = torch.float32)
x = torch.arange(3, dtype = torch.float32)
print(x)
A.shape
x.shape
torch.mv(A, x) # [0 * 1 + 1 * 2 + 2 * 3, 4 * 0 + 1 * 5 + 2 * 6]

# 矩阵乘法
# mm函数  matmul
A = torch.tensor([[1, 2, 3], 
                  [4, 5, 6]], dtype = torch.float32)
B = torch.ones(3, 2)
torch.mm(A, B)

# 范数
# L1范数是向量元素的绝对值之和
# L2范数是向量元素平方和的平方根
u = torch.tensor([3.0, 0.0, 4.0])
print(torch.abs(u).sum()) # L1范数
print(torch.norm(u)) # L2范数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值