栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python深度学习基于pytorch——广播机制

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python深度学习基于pytorch——广播机制

注意广播的计算:

#coco
#广播机制
import torch
import numpy as np

A = np.arange(0, 40, 10).reshape(4, 1)
print(A)
# [[ 0]
#  [10]
#  [20]
#  [30]]
B = np.arange(0, 3)
print(B)
# [0 1 2]

# 把ndarray转换为Tensor
A1 = torch.from_numpy(A)  # 形状为4x1
print(A1)
# tensor([[ 0],
#         [10],
#         [20],
#         [30]], dtype=torch.int32)

B1 = torch.from_numpy(B)  # 形状为3
print(B1)
# tensor([0, 1, 2], dtype=torch.int32)
# Tensor自动实现广播
C = A1 + B1
print(C)
# tensor([[ 0,  1,  2],
#         [10, 11, 12],
#         [20, 21, 22],
#         [30, 31, 32]], dtype=torch.int32)
# 我们可以根据广播机制,手工进行配置
# 根据规则1,B1需要向A1看齐,把B变为(1,3)
B2 = B1.unsqueeze(0)  # B2的形状为1x3
print(B2)
# tensor([[0, 1, 2]], dtype=torch.int32)
# 使用expand函数重复数组,分别的4x3的矩阵
A2 = A1.expand(4, 3)
print(A2)
# tensor([[ 0,  0,  0],
#         [10, 10, 10],
#         [20, 20, 20],
#         [30, 30, 30]], dtype=torch.int32)
B3 = B2.expand(4, 3)
print(B3)
# tensor([[0, 1, 2],
#         [0, 1, 2],
#         [0, 1, 2],
#         [0, 1, 2]], dtype=torch.int32)
# 然后进行相加,C1与C结果一致
C1 = A2 + B3

        做不到的话,就做到能做到为止;做到后,就继续做到完美为 止;做到完美之后,就继续做到无论做几次都能完美为止。

——羽生结弦

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/893508.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号