pytorch使用(二)自定义网络

pytorch使用:目录


pytorch使用(二)自定义网络

首先参考pytorch的官方手册中关于torch.nn的说明。

1. 定义网络结构

搭建自己的网路使用class torch.nn.Module,在官方手册中有一个非常简单的例子:

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
       x = F.relu(self.conv1(x))
       return F.relu(self.conv2(x))

这个例子定义了一个只有两层的网络Model。其中两个函数:
- 初始化函数 __init__(self)定义了具体网络有什么层,这里实际上没有决定网络的结构,也就是说将上面的例子中的self.conv1self.conv2定义的前后顺序调换是完全没有影响的。
- forward函数定义了网络的前向传播的顺序。

pytorch中具体支持的不同的层请参考官方手册torch.nn

2. 网络参数初始化

pytorch官方提供了多种初始化函数,具体参考官方手册:
- torch.nn.init.uniform(tensor, a=0, b=1)
- torch.nn.init.normal(tensor, mean=0, std=1)
- torch.nn.init.constant(tensor, val)
- torch.nn.init.xavier_uniform(tensor, gain=1)

初始化函数可以直接作用于神经网络参数

  1. 对网络的某一层参数进行初始化
import torch.nn as nn
import torch.nn.init as init

conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
init.xavier_uniform(conv1.weight)#卷积参数
init.constant(conv1.bias, 0.1)#偏重
  1. 对整个网络的参数进行初始化
def weights_init(m):
    if isinstance(m, nn.Conv2d):
        xavier(m.weight.data)
        xavier(m.bias.data)  

下面举一个例子,定义一个网络MyNet,网络由6层的卷积构成:

import torch
import torch.nn as nn
import torch.nn.init as init

class MyNet(nn.Module):

    def __init__(self):
        super(MyNet, self).__init__()
        self.conv1 = nn.Conv2d(22, 64, 7, padding=3)
        self.relu1 = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(64, 128, 7, padding=3)
        self.relu2 = nn.ReLU(inplace=True)
        self.conv3 = nn.Conv2d(128, 256, 5, padding=2)
        self.relu3 = nn.ReLU(inplace=True)
        self.conv4 = nn.Conv2d(256, 128, 5, padding=2)
        self.relu4 = nn.ReLU(inplace=True)
        self.conv5= nn.Conv2d(128, 64, 3, padding=1)
        self.relu5 = nn.ReLU(inplace=True)
        self.conv6 = nn.Conv2d(64, 6, 3, padding=1)
        self.relu6 = nn.ReLU(inplace=True)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                init.xavier_uniform(m.weight.data)
                init.constant(m.bias.data,0.1)

    def forward(self, x):
        x = self.relu1(self.conv1(x))
        x = self.relu2(self.conv2(x))
        x = self.relu3(self.conv3(x))
        x = self.relu4(self.conv4(x))
        x = self.relu5(self.conv5(x))
        f = self.relu6(self.conv6(x))
        return f

可以使用pytorch提供的hook函数来获取任意层的特征,并使用sklearn提供的TSNE函数进行降维可视化。以下是一个简单的示例代码: ```python import torch from sklearn.manifold import TSNE import matplotlib.pyplot as plt # 自定义网络 class MyNet(torch.nn.Module): def __init__(self): super().__init__() self.conv1 = torch.nn.Conv2d(3, 16, kernel_size=3) self.conv2 = torch.nn.Conv2d(16, 32, kernel_size=3) self.fc1 = torch.nn.Linear(32 * 6 * 6, 128) self.fc2 = torch.nn.Linear(128, 10) def forward(self, x): x = torch.nn.functional.relu(self.conv1(x)) x = torch.nn.functional.relu(self.conv2(x)) x = x.view(-1, 32 * 6 * 6) x = torch.nn.functional.relu(self.fc1(x)) x = self.fc2(x) return x # 定义hook函数获取特征 features = [] def get_features_hook(module, input, output): features.append(output.flatten(start_dim=1)) # 构建网络,注册hook函数 net = MyNet() net.conv1.register_forward_hook(get_features_hook) net.conv2.register_forward_hook(get_features_hook) # 加载数据,获取特征 data = torch.randn(100, 3, 32, 32) target = torch.randint(0, 10, (100,)) output = net(data) features = torch.cat(features, dim=1).detach().numpy() # 使用TSNE进行可视化 tsne = TSNE(n_components=2, perplexity=30, learning_rate=200, n_jobs=-1) features_tsne = tsne.fit_transform(features) # 绘制散点图 plt.scatter(features_tsne[:, 0], features_tsne[:, 1], c=target.numpy()) plt.colorbar() plt.show() ``` 在这个示例,我们定义了一个自定义网络`MyNet`,并使用hook函数获取了其第一层和第层的特征。然后,我们使用TSNE对这些特征进行了降维,最后绘制了一个散点图,其不同的颜色表示不同的类别。当然,你可以根据需要修改代码来适应你的网络和数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值