为Pythorch输入形状推断和SOTA自定义层。

torchlayers的Python项目详细描述


torchlayers Logo


VersionDocsTestsCoverageStylePyPIPythonPyTorchDocker
VersionDocumentationTestscodecovcodebeat badgePyPIPythonPyTorchDocker

torchlayers是基于PyTorch的库 提供自动形状和尺寸推断torch.nn+附加 当前SOTA架构中的构建块(例如Efficient-Net)。在

以上不需要用户干预(除了对torchlayers.build的单个调用) 与Keras中看到的类似。在

主要功能:

  • 形状推理适用于torch.nn模块(卷积层、递归层、变换层、注意层和线性层
  • Dimensionality推断(例如torchlayers.Conv基于input shape作为torch.nn.Conv1d/2d/3d
  • 自定义模块的形状推理(参见示例部分)
  • 附加Keras-like(例如torchlayers.Reshape或{})
  • 额外的SOTA层大部分来自ImageNet竞赛 (例如PolyNetSqueeze-And-ExcitationStochasticDepth
  • 有用的默认值"same"填充和默认值{}用于{},辍学率等)
  • Zero开销和torchscript支持

示例

有关完整功能,请检查torchlayers documentation。 下面的例子应该介绍你应该知道的所有必要的概念。在

简单卷积图文分类器

  • 我们将对这两个任务使用单一的“模型”。 首先让我们用torch.nntorchlayers来定义它:
importtorchimporttorchlayers# torch.nn and torchlayers can be mixed easilymodel=torch.nn.Sequential(torchlayers.Conv(64),# specify ONLY out_channelstorch.nn.ReLU(),# use torch.nn wherever you wishtorchlayers.BatchNorm(),# BatchNormNd inferred from inputtorchlayers.Conv(128),# Default kernel_size equal to 3torchlayers.ReLU(),torchlayers.Conv(256,kernel_size=11),# "same" padding as defaulttorchlayers.GlobalMaxPool(),# Known from Kerastorchlayers.Linear(10),# Output for 10 classes)print(model)

上面给出的模型总结如下(注意尚未推断出的值的问号):

^{pr2}$
  • 现在您可以使用示例输入build/实例化模型(在本例中是MNIST-like):
mnist_model=torchlayers.build(model,torch.randn(1,3,28,28))
  • 或者,如果你想要的是文本分类,同样的模型可以用不同的方法构建 input shape(例如,对于使用300维预训练嵌入的文本分类):
# [batch, embedding, timesteps], first dimension > 1 for BatchNorm1d to worktext_model=torchlayers.build(model,torch.randn(2,300,1))
  • 最后,您可以在实例化之后print两个模型,如下所示 旁边的可读性(注意不同的维度,例如Conv2dtorchlayers.build之后的Conv1d):
# MNIST CLASSIFIER                TEXT CLASSIFIERSequential(Sequential((0):Conv1d(300,64)(0):Conv2d(3,64)(1):ReLU()(1):ReLU()(2):BatchNorm1d(64)(2):BatchNorm2d(64)(3):Conv1d(64,128)(3):Conv2d(64,128)(4):ReLU()(4):ReLU()(5):Conv1d(128,256)(5):Conv2d(128,256)(6):GlobalMaxPool()(6):GlobalMaxPool()(7):Linear(256,10)(7):Linear(256,10)))

如您所见,这两个模块“编译”到原始的pytorch层中。在

具有形状推理功能的自定义模块

用户可以定义任何模块并使用torchlayers.infer使其形状可推断 功能:

# Class defined with in_features# It might be a good practice to use _ prefix and Impl as postfix# to differentiate from shape inferable versionclass_MyLinearImpl(torch.nn.Module):def__init__(self,in_features:int,out_features:int):super().__init__()self.weight=torch.nn.Parameter(torch.randn(out_features,in_features))self.bias=torch.nn.Parameter(torch.randn(out_features))defforward(self,inputs):returntorch.nn.functional.linear(inputs,self.weight,self.bias)MyLinear=torchlayers.infer(_MyLinearImpl)# Build and use just like any other layer in this librarylayer=torchlayers.build(MyLinear(out_features=32),torch.randn(1,64))layer(torch.randn(1,64))

默认情况下,inputs.shape[1]将用作in_features值 在初始forward过程中。如果您希望使用不同的index(例如,推断使用 inputs.shape[3])使用MyLayer = torchlayers.infer(_MyLayerImpl, index=3)作为装饰。在

具有反向剩余瓶颈和像素混洗的自动编码器

请检查代码注释和documentation 如果需要的话。如果你不确定什么是自动编码器,你可以看到 this example blog post。在

下面是ImageNet类图像的卷积去噪自动编码器示例。 可以把它看作是不同层的功能演示 以及由torchlayers提供的构建块。在

# Input - 3 x 256 x 256 for ImageNet reconstructionclassAutoEncoder(torch.nn.Module):def__init__(self):super().__init__()self.encoder=torchlayers.Sequential(torchlayers.StandardNormalNoise(),# Apply noise to input imagestorchlayers.Conv(64,kernel_size=7),torchlayers.activations.Swish(),# Direct access to module .activationstorchlayers.InvertedResidualBottleneck(squeeze_excitation=False),torchlayers.AvgPool(),# shape 64 x 128 x 128, kernel_size=2 by defaulttorchlayers.HardSwish(),# Access simply through torchlayerstorchlayers.SeparableConv(128),# Up number of channels to 128torchlayers.InvertedResidualBottleneck(),# Default with squeeze excitationtorch.nn.ReLU(),torchlayers.AvgPool(),# shape 128 x 64 x 64, kernel_size=2 by defaulttorchlayers.DepthwiseConv(256),# DepthwiseConv easier to use# Pass input thrice through the same weights like in PolyNettorchlayers.Poly(torchlayers.InvertedResidualBottleneck(),order=3),torchlayers.ReLU(),# all torch.nn can be accessed via torchlayerstorchlayers.MaxPool(),# shape 256 x 32 x 32torchlayers.Fire(out_channels=512),# shape 512 x 32 x 32torchlayers.SqueezeExcitation(hidden=64),torchlayers.InvertedResidualBottleneck(),torchlayers.MaxPool(),# shape 512 x 16 x 16torchlayers.InvertedResidualBottleneck(squeeze_excitation=False),# Randomly switch off the last two layers with 0.5 probabilitytorchlayers.StochasticDepth(torch.nn.Sequential(torchlayers.InvertedResidualBottleneck(squeeze_excitation=False),torchlayers.InvertedResidualBottleneck(squeeze_excitation=False),),p=0.5,),torchlayers.AvgPool(),# shape 512 x 8 x 8)# This one is more "standard"self.decoder=torchlayers.Sequential(torchlayers.Poly(torchlayers.InvertedResidualBottleneck(),order=2),# Has ICNR initialization by default after calling `build`torchlayers.ConvPixelShuffle(out_channels=512,upscale_factor=2),# Shape 512 x 16 x 16 after PixelShuffletorchlayers.Poly(torchlayers.InvertedResidualBottleneck(),order=3),torchlayers.ConvPixelShuffle(out_channels=256,upscale_factor=2),# Shape 256 x 32 x 32torchlayers.Poly(torchlayers.InvertedResidualBottleneck(),order=3),torchlayers.ConvPixelShuffle(out_channels=128,upscale_factor=2),# Shape 128 x 64 x 64torchlayers.Poly(torchlayers.InvertedResidualBottleneck(),order=4),torchlayers.ConvPixelShuffle(out_channels=64,upscale_factor=2),# Shape 64 x 128 x 128torchlayers.InvertedResidualBottleneck(),torchlayers.Conv(256),torchlayers.Dropout(),# Defaults to 0.5 and Dropout2d for imagestorchlayers.Swish(),torchlayers.InstanceNorm(),torchlayers.ConvPixelShuffle(out_channels=32,upscale_factor=2),# Shape 32 x 256 x 256torchlayers.Conv(16),torchlayers.Swish(),torchlayers.Conv(3),# Shape 3 x 256 x 256)defforward(self,inputs):returnself.decoder(self.encoder(inputs))

现在可以实例化该模块,并像往常一样与torch.nn.MSELoss一起使用。在

autoencoder=torchlayers.build(AutoEncoder(),torch.randn(1,3,256,256))

安装

pip

最新版本:

pip install --user torchlayers

每晚:

pip install --user torchlayers-nightly

Docker

CPU standalone和启用了GPU的各种版本的映像可用 在dockerhub。在

对于CPU快速启动,问题:

docker pull szymonmaszke/torchlayers:18.04

夜间构建也可用,只需在标记前面加上nightly_。如果您要使用GPU图像,请确保 nvidia/docker已安装并已设置运行时。在

贡献

如果您发现问题或希望看到一些功能(或实现一个),请open new Issuecreate Pull Request。在

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
构造函数的java条件调用   类Dog中的java构造函数Dog不能应用于给定类型   java jsch和运行“sudo su”   java将队列和堆栈相互复制   java如何在netbeans项目的文件夹中添加库   java While循环在我的代码中不存在   如何在XML中使用java方法的返回值   java是否可以在不写入文件的情况下将字符串/字节数组作为文件发布?   java为什么这些字符串不相等?   sockets客户机-服务器java编程,用户可选择   java如何在SpringMVC和hibernate中保存模型返回视图的列表   java如何修复组织。openqa。硒。WebDriverException:未知错误   Java,Ant错误:编码Cp1252的不可映射字符   JAVAlang.ClassCastException:[Ljava.lang.String;与java.lang.String不兼容   java如何使用JDK8(可选)为空字段创建自定义IntelliJ getter模板   java Tomcat6响应。sendRedirect()404错误