承接上文,有提到前向传播时的代码:
def forward(self,x):
x = self.linear1(x)
x = self.linear2(x)
return x
我没有使用激活函数。若使用的话可以是这样:
def forward(self,x):
x = sigmoid(self.linear1(x))
x = sigmoid(self.linear2(x))
return x#我就用逻辑斯蒂,因为我只认得这个
当然,为了调用,修改方便,实际使用时常常是这样:
(整个网络都在下面)
class LM(torch.nn.Module):
def __init__(self):
super(LM,self).__init__()#继承父类的属性
self.linear1 = torch.nn.Linear(3,2)#建立一个对象。
#(3,2)代表输入,输出的维度
#linear 是一个可以进行y=w*x+b式计算的类,x,y,w,b都可以是向量
self.linear2 = torch.nn.Linear(2,1)
self.acv = torch.nn.Sigmoid()#典中典之callable的类
def forward(self,x):
x = self.acv(self.linear1(x))
x = self.acv(self.linear2(x))
return x
这样就可以轻松修改激活函数,尤其是层数多的时候。
由此可以见到,激活函数就是再每一层前向传播后再对结果处理一下(不用也可以运行)