关于Pytorch的MLP模块实现方式

yipeiwu_com6年前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中range和xrange的区别

【听图阁-专注于Python设计】已经给大家介绍过range和xrange的区别的基础知识,有兴趣的朋友可以参阅:  python中xrange和range的区别 python...

python解析yaml文件过程详解

YAML语法规则: http://www.ibm.com/developerworks/cn/xml/x-cn-yamlintro/ 下载PyYAML: http://www.yaml....

举例讲解Django中数据模型访问外键值的方法

先设置一个关于书本(book)的数据模型: from django.db import models class Publisher(models.Model): name...

python删除指定类型(或非指定)的文件实例详解

本文实例分析了python删除指定类型(或非指定)的文件用法。分享给大家供大家参考。具体如下: 如下,删除目录下非源码文件 import os import string de...

Python中垃圾回收和del语句详解

Python中的垃圾回收算法是采用引用计数, 当一个对象的引用计数为0时, Python的垃圾回收机制就会将对象回收 a = "larry" b = a larry这个字符串对象,...