1.张量的requires_grad属性
importtorch x=torch.randn(3,3,requires_grad=False)y=x*2# y = 2xy.requires_grad=Truez=y.mean()# z=(1/9)*(2x),微分是dz/dx = 2/9# z=(1/9)*y,微分是dz/dy = 1/9z.backward()print(x,x.requires_grad)print(y,y.requires_grad,y.grad)print(z.requires_grad)注意,python中万物都是对象(object),因此基本上都会有一些属性,类比C++中类和对象的关系。张量也是一种对象。
这里对张量的核心属性requires_grad功能进行演示。例子中,x不需要梯度,因此计算得到的y也是不需要梯度的张量,我们可以手动设置y需要梯度,因此影响到z,z变为需要梯度的。
运行结果:
tensor([[-0.2486,1.0678,0.6611],[0.3205, -0.4081, -0.5011],[-1.1482,1.5839, -0.3978]])False tensor([[-0.4972,2.1357,1.3223],[0.6411, -0.8162, -1.0023],[-2.2964,3.1677, -0.7956]],requires_grad=True)True tensor([[0.1111,0.1111,0.1111],[0.1111,0.1111,0.1111],[0.1111,0.1111,0.1111]])True2.model.train()和model.eval()对模型的行为影响
先搭建一个简单模型
importtorchimporttorch.nnasnn torch.random.manual_seed(42)classSimpleModel(nn.Module):def__init__(self):super(SimpleModel,self).__init__()self.fc=nn.Linear(10,2)# 一个简单的线性层self.bn=nn.BatchNorm1d(2)# 批量标准化self.dropout=nn.Dropout(0.5)# Dropout层,50%的丢弃概率defforward(self,x):x=self.fc(x)# 通过全连接层x=self.bn(x)# 进行批量标准化x=self.dropout(x)# 应用Dropoutreturnx# 创建模型model=SimpleModel()2.1 获取模型的全部参数
使用方法state_dict()
print(model.state_dict())返回一个字典
OrderedDict([('fc.weight', tensor([[-0.0290, -0.2516, -0.3142, -0.2079,0.2460, -0.1968, -0.1554, -0.2758,0.2958,0.3105],[0.2236, -0.0511,0.2169,0.2815,0.1189, -0.2317,0.1405,0.2883,0.2088, -0.2837]