aa = A()
aa.eval()
print(aa.a.requires_grad)
aa.train()
print(aa.a.requires_grad)
import torch
import torch.nn as nn
from torch.nn import Parameter
class A(nn.Module):
def __init__(self):
nn.Module.__init__(self)
self.a = Parameter(torch.tensor(100.))
def forward(self,x):
ans = x*self.a
return ans
aa = A()
aa.eval()
b = aa(10)
print(aa.a.requires_grad)
b.backward()
print(aa.a.grad)
aa.zero_grad() //清空梯度!!!
aa.train()
b = aa(11)
print(aa.a.requires_grad)
b.backward()
print(aa.a.grad)
输出:
True
tensor(10.)
True
tensor(11.)
也就是说这两种状态都可以记录梯度,能进行反向传播!
但是两者的区别在于:
- model.eval(),不启用 BatchNormalization 和 Dropout。此时pytorch会自动把BN和DropOut固定住,不会取平均,而是用训练好的值
- model.train() :启用 BatchNormalization 和 Dropout。 在模型测试阶段使用model.train() 让model变成训练模式,此时 dropout和batch normalization的操作在训练起到防止网络过拟合的问题