广播机制

import torch
from torch import nn
import cv2
from torchvision.transforms import ToTensor, ToPILImage
import numpy as np


class Linear(nn.Module):
    def __init__(self, in_features, out_features):
        super(Linear, self).__init__()
        self.w = nn.Parameter(torch.randn(in_features, out_features))
        self.b = nn.Parameter(torch.randn(out_features))

    # x(batch, in_features) w(in_features, out_feature)
    # 注意shape不够的只能向前补
    def forward(self, x):
        x = x.mm(self.w)
        # expand_as 类似广播机制
        return x + self.b.expand_as(x)

layer = Linear(4, 3)
input = torch.rand(8, 4)
output = layer(input)
print(output)

class Perception(nn.Module):
    def __init__(self, in_features, hidden_features, out_features):
        super(Perception, self).__init__()
        self.layer1 = Linear(in_features, hidden_features)
        self.layer2 = Linear(hidden_features, out_features)

    # 前馈函数负责计算 不应包含定义额外的paramters
    def forward(self, x):
        x = self.layer1(x)
        x = torch.sigmoid(x)
        return self.layer2(x)


lena = cv2.imread("Lena.png", flags=0)

# 归一化到0-1之间 的tensor 利用unsqueeze 增加一个batchsize的维度
lena = lena[np.newaxis, np.newaxis, :, :]

print(lena.shape)

lena = torch.tensor(lena, dtype=torch.float)

kernel = torch.ones(3, 3)/-9
kernel[1, 1] = 1
conv = nn.Conv2d(1, 1, (3, 3), 1, padding=1, bias=False)
# tensor的data 是个numpy 修改其值可修改tensor的值
conv.weight.data = kernel.view(1, 1, 3, 3)
out = conv(lena).squeeze().detach().numpy()


class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.list = [nn.Linear(3, 4), nn.ReLU()]
        self.module_list = nn.ModuleList

注意 : (4, 2) 和(2)可以 但  (2, 4)和(2)不行  是逐个比较维数 维度不等时前面补1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NumPy广播机制是一种用于在不同形状的数组之间进行元素级操作的机制。它允许具有不同形状的数组进行算术运算,而无需显式地扩展数组的形状。广播机制通过在缺失或大小为1的维度上扩展数组来实现这一点,以使其具有兼容的形状。 广播机制遵循以下规则: 1. 如果两个数组的维度数量不同,则在维度较小的数组前面补1,直到两个数组的维度数量相同。 2. 如果两个数组在某个维度上的大小不同,并且其中一个数组在该维度上的大小为1,则可以沿着该维度进行广播。 3. 如果两个数组在某个维度上的大小不相等,并且两个数组在该维度上的大小都不为1,则无法进行广播,会引发错误。 以下是一个示例,展示了广播机制的应用: ```python import numpy as np a = np.array([[0, 0, 0], [10, 10, 10], [20, 20, 20], [30, 30, 30]]) b = np.array([1, 2, 3]) print(a * b) ``` 在这个例子中,数组`a`的形状是(4, 3),数组`b`的形状是(3,),但是它们可以进行乘法运算,因为在第二个维度上,数组`b`的大小为1,可以通过广播机制自动扩展为(4, 3)的形状,以与数组`a`相匹配。 输出结果为: ``` array([[ 0, 0, 0], [10, 20, 30], [20, 40, 60], [30, 60, 90]]) ``` 这是通过将数组`b`扩展为与数组`a`相同的形状,然后进行元素级乘法运算得到的结果。请注意,广播机制在进行运算时,并不实际复制数组的值,而是利用广播的原理进行计算,从而提高了效率。 总之,NumPy广播机制是一种非常强大的工具,可以方便地执行在不同形状的数组上进行元素级操作的任务。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值