chapter4

博客介绍了建立全连接层的步骤,包括类继承、调用父类构造函数、处理学习参数、定义实例方法等。还阐述了激活函数为sigmoid的多层感知机搭建,涉及建立全连接类和多层感知机类,以及在特定方法中实现计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立全连接层

1)类继承nn.Module

2)  调用父类构造函数nn.Module.__init(self)

3)学习参数放在nn.Paramter()

 4)  定义实例方法forward

5)初始值为Variable类型

import torch as t
import torch.nn as nn
from torch.autograd import Variable as V

class Linear(nn.Module):
    def __init__(self,in_feature,out_feature):
        nn.Module.__init__(self)
        self.w=nn.Parameter(t.randn(in_feature,out_feature))
        self.b=nn.Parameter(t.randn(out_feature))

    def forward(self,x):
        x=x.mm(self.w)
        return x+self.b.expand_as(x)
input=V(t.randn(2,4))
layer=Linear(4,3)
output=layer(input)

for name, parameter in layer.named_parameters():
    print(name, parameter) # w and b

多层感知机,激活函数为sigmoid函数

1)建立全连接类如上

2)建立多层感知机类

3)__init__中调用nn.Module.__init__(self)

4)  成员方法forword中实现计算

import torch as t
import torch.nn as nn
from torch.autograd import Variable as V

class Linear(nn.Module):
    def __init__(self,in_feature,out_feature):
        nn.Module.__init__(self)
        self.w=nn.Parameter(t.randn(in_feature,out_feature))
        self.b=nn.Parameter(t.randn(out_feature))

    def forward(self,x):
        x=x.mm(self.w)
        return x+self.b.expand_as(x)

#多层感知机
class Perceptron(nn.Module):
    def __init__(self,in_feature,hide_feature,out_feature):
        nn.Module.__init__(self)
        self.layer1=Linear(in_feature,hide_feature)
        self.layer2=Linear(hide_feature,out_feature)
    def forward(self,x):
        x=self.layer1(x)
        x=t.sigmoid(x)
        x=self.layer2(x)
        return x

Percet=Perceptron(4,3,1)
input=V(t.linspace(1,4,4).resize(1,4))
output=Percet(input)
print(output)

for name,parameter in Percet.named_parameters():
    print(name,parameter)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值