1. import torch
    2. import torch.nn.functional as F
    3. from torch import nn
    4. class Center_Layer(nn.Module): # 无参数
    5. def __init__(self):
    6. super(Center_Layer, self).__init__()
    7. def forward(self,x):
    8. return x-x.mean()
    9. x = torch.FloatTensor([1,2,3,4,5])
    10. layer = Center_Layer()
    11. print(layer(x))
    12. """将自定义层放在更复杂的模型"""
    13. net = nn.Sequential(nn.Linear(8,16),Center_Layer()) # 这里没有实例化
    14. y = torch.randn(4,8)
    15. print(net(y).mean())
    1. class MyLinear(nn.Module):
    2. def __init__(self,in_units,units):
    3. super(MyLinear, self).__init__()
    4. self.weight= nn.Parameter(torch.randn(in_units,units))
    5. self.bias = nn.Parameter(torch.randn(units,))# 写法疑问
    6. def forward(self,x):
    7. linear = torch.matmul(x,self.weight.data)+self.bias.data # 这里一定是要.data 否则其是一个类
    8. return F.relu(linear)
    9. dense =MyLinear(5,3) # 输入5个神经元 ,输出3个
    10. print(dense.weight)
    11. """
    12. Parameter containing:
    13. tensor([[-0.3572, -1.9288, -3.7428],
    14. [-1.4446, 0.3748, -0.7603],
    15. [-1.8752, 0.0835, -0.0824],
    16. [ 0.4117, -0.2987, 1.0108],
    17. [ 0.0120, 2.2607, -0.3163]], requires_grad=True)