demo1
import torch
from torch import nn
# 全连接类
class Linear(nn.Module):
def __init__(self, in_dim, out_dim):
super(Linear, self).__init__()
# Parameter 为Tensor的构造方法,默认求导
# w b 为网络需要学习的参数
self.w = nn.Parameter(torch.randn(in_dim, out_dim))
self.b = nn.Parameter(torch.randn(out_dim))
# 前向传播的实现
def forward(self, x):
x = x.matmul(self.w) # x*w .matmul实现矩阵相乘
y = x + self.b.expand_as(x) # y = wx + b .expand_as 保证b和x的矩阵形状一致
return y
# 一
#两层感知机类
#nn.Module(自动学习参数)与nn.functional(不自动学习参数)都提供了很多网络层和函数功能。
# class Perception(nn.Module):
# def __init__(self, in_dim, hid_dim, out_dim):
# super(Perception, self).__init__()
# # 定义了两层全连接层 调用了上个函数Linear的子module
# self.layer1 = Linear(in_dim, hid_dim)
# self.layer2 = Linear(hid_dim, out_dim)
# def forward(