关于Pytorch的MLP模块实现方式

yipeiwu_com5年前Python基础

MLP分类效果一般好于线性分类器,即将特征输入MLP中再经过softmax来进行分类。

具体实现为将原先线性分类模块:

self.classifier = nn.Linear(config.hidden_size, num_labels)

替换为:

self.classifier = MLP(config.hidden_size, num_labels)

并且添加MLP模块:

  class MLP(nn.Module):
    def __init__(self, input_size, common_size):
      super(MLP, self).__init__()
      self.linear = nn.Sequential(
        nn.Linear(input_size, input_size // 2),
        nn.ReLU(inplace=True),
        nn.Linear(input_size // 2, input_size // 4),
        nn.ReLU(inplace=True),
        nn.Linear(input_size // 4, common_size)
      )
 
    def forward(self, x):
      out = self.linear(x)
      return out

看一下模块结构:

mlp = MLP(1000,3)
print(mlp)

以上这篇关于Pytorch的MLP模块实现方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python 网络编程之TCP客户端/服务端功能示例【基于socket套接字】

本文实例讲述了Python 网络编程之TCP客户端/服务端功能。分享给大家供大家参考,具体如下: demo.py(TCP客户端): import socket def main():...

Python中使用异常处理来判断运行的操作系统平台方法

代码实例: 复制代码 代码如下: try:     import termios, TERMIOS               1 except Impor...

Python实现的从右到左字符串替换方法示例

本文实例讲述了Python实现的从右到左字符串替换方法。分享给大家供大家参考,具体如下: 一 . 前言 需要用到,但是发现python没有从右边开始替换的内置方法,默认的replace只...

详解python字节码

Python对不可变序列进行重复拼接操作效率会很低,因为每次都会生成一个新的对象,解释器需要把原来对象中的元素先复制到新的对象里,然后再追加新的元素。 但是CPython对字符串操作进行...

Tensorflow 自定义loss的情况下初始化部分变量方式

一般情况下,tensorflow里面变量初始化过程为: #variables ........... #..................... init = tf....