pytorch:在网络中添加可训练参数,修改预训练权重文件
2018-01-29 16:26
831 查看
实践中,针对不同的任务需求,我们经常会在现成的网络结构上做一定的修改来实现特定的目的。
假如我们现在有一个简单的两层感知机网络:
# -*- coding: utf-8 -*-
import torch
from torch.autograd import Variable
import torch.optim as optim
x = Variable(torch.FloatTensor([1, 2, 3])).cuda()
y = Variable(torch.FloatTensor([4, 5])).cuda()
class MLP(torch.nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.linear1 = torch.nn.Linear(3, 5)
self.relu = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(5, 2)
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.linear2(x)
return x
model = MLP().cuda()
loss_fn = torch.nn.MSELoss(size_average=False)
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
for t in range(500):
y_pred = model(x)
loss = loss_fn(y_pred, y)
print(t, loss.data[0])
model.zero_grad()
loss.backward()
optimizer.step()
print(model(x))现在想在前向传播时,在relu之后给x乘以一个可训练的系数,只需要在__init__函数中添加一个nn.Parameter类型变量,并在forward函数中乘以该变量即可:
class MLP(torch.nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.linear1 = torch.nn.Linear(3, 5)
self.relu = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(5, 2)
# the para to be added and updated in train phase, note that NO cuda() at last
self.coefficient = torch.nn.Parameter(torch.Tensor([1.55]))
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.coefficient * x
x = self.linear2(x)
return x注意,Parameter变量和Variable变量的操作大致相同,但是不能手动调用.cuda()方法将其加载在GPU上,事实上它会自动在GPU上加载,可以通过model.state_dict()或者model.named_parameters()函数查看现在的全部可训练参数(包括通过继承得到的父类中的参数):
print(model.state_dict().keys())
for i, j in model.named_parameters():
print(i)
print(j)输出如下:
如果我们有原先网络的预训练权重,现在添加了一个新的参数,原有的权重文件自然就不能加载了,我们需要修改原权重文件,在其中添加我们的新变量的初始值。
调用model.state_dict查看我们添加的参数在参数字典中的完整名称,然后打开原先的权重文件:
a = torch.load("OldWeights.pth")
a是一个collecitons.OrderedDict类型变量,也就是一个有序字典,直接将新参数名称和初始值作为键值对插入,然后保存即可。
假如我们现在有一个简单的两层感知机网络:
# -*- coding: utf-8 -*-
import torch
from torch.autograd import Variable
import torch.optim as optim
x = Variable(torch.FloatTensor([1, 2, 3])).cuda()
y = Variable(torch.FloatTensor([4, 5])).cuda()
class MLP(torch.nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.linear1 = torch.nn.Linear(3, 5)
self.relu = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(5, 2)
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.linear2(x)
return x
model = MLP().cuda()
loss_fn = torch.nn.MSELoss(size_average=False)
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
for t in range(500):
y_pred = model(x)
loss = loss_fn(y_pred, y)
print(t, loss.data[0])
model.zero_grad()
loss.backward()
optimizer.step()
print(model(x))现在想在前向传播时,在relu之后给x乘以一个可训练的系数,只需要在__init__函数中添加一个nn.Parameter类型变量,并在forward函数中乘以该变量即可:
class MLP(torch.nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.linear1 = torch.nn.Linear(3, 5)
self.relu = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(5, 2)
# the para to be added and updated in train phase, note that NO cuda() at last
self.coefficient = torch.nn.Parameter(torch.Tensor([1.55]))
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.coefficient * x
x = self.linear2(x)
return x注意,Parameter变量和Variable变量的操作大致相同,但是不能手动调用.cuda()方法将其加载在GPU上,事实上它会自动在GPU上加载,可以通过model.state_dict()或者model.named_parameters()函数查看现在的全部可训练参数(包括通过继承得到的父类中的参数):
print(model.state_dict().keys())
for i, j in model.named_parameters():
print(i)
print(j)输出如下:
odict_keys(['linear1.weight', 'linear1.bias', 'linear2.weight', 'linear2.bias']) linear1.weight Parameter containing: -0.3582 -0.0283 0.2607 0.5190 -0.2221 0.0665 -0.2586 -0.3311 0.1927 -0.2765 0.5590 -0.2598 0.4679 -0.2923 -0.3379 [torch.cuda.FloatTensor of size 5x3 (GPU 0)] linear1.bias Parameter containing: -0.2549 -0.5246 -0.1109 0.5237 -0.1362 [torch.cuda.FloatTensor of size 5 (GPU 0)] linear2.weight Parameter containing: -0.0286 -0.3045 0.1928 -0.2323 0.2966 0.2601 0.1441 -0.2159 0.2484 0.0544 [torch.cuda.FloatTensor of size 2x5 (GPU 0)] linear2.bias Parameter containing: -0.4038 0.3129 [torch.cuda.FloatTensor of size 2 (GPU 0)]这个参数会在反向传播时与原有变量同时参与更新,这就达到了添加可训练参数的目的。
如果我们有原先网络的预训练权重,现在添加了一个新的参数,原有的权重文件自然就不能加载了,我们需要修改原权重文件,在其中添加我们的新变量的初始值。
调用model.state_dict查看我们添加的参数在参数字典中的完整名称,然后打开原先的权重文件:
a = torch.load("OldWeights.pth")
a是一个collecitons.OrderedDict类型变量,也就是一个有序字典,直接将新参数名称和初始值作为键值对插入,然后保存即可。
a = torch.load("OldWeights.pth") a["layer1.0.coefficient"] = torch.FloatTensor([1.2]) a["layer1.1.coefficient"] = torch.FloatTensor([1.5]) torch.save(a, "Weights.pth")现在权重就可以加载在修改后的模型上了。
相关文章推荐
- pytorch中的pre-train函数模型或者旧的模型的引用及修改(增减网络层,修改某层参数等) finetune微调等
- PyTorch中使用预训练的模型初始化网络的一部分参数
- 【py-faster-rcnn】【训练自己数据】需要修改的参数小记
- (继)pytorch中的pretrain模型网络结构修改
- TensorFlow中对训练后的神经网络参数(权重、偏置)提取
- 给测试报告添加饼图之修改HTMLTestRunner.py文件
- React-Native 在iOS9之后,网络请求默认为Https请求,如需支持Http,修改info.plist文件添加键值对设置允许http访问。
- 读取修改caffemodel文件里的网络模型参数
- py-faster-rcnn+VGG_CNN_M_1024训练自己数据需要修改的参数小记
- 修改配置文件的方法配置网络参数
- 深度学习-CAFFE利用CIFAR10网络模型训练自己的图像数据获得模型-3结合caffe中的CIFAR10修改相关配置文件并训练
- py-faster-rcnn训练自己数据集需要修改的参数
- py-faster-rcnn 训练参数修改(转)
- sharepoint 2007 “文件为网络下载文件,请存储到硬盘之后再修改文件。”
- linux下修改IP、netmask、gateway等网络参数的方法
- 修改二进制参数文件(SPFILE)的方法之一
- java 对 xxx.properties资源文件属性的修改,添加
- ADO.NET使用带参数方法实现添加、删除和修改数据
- undo表空间管理测试2-----修改参数文件initORCL.ora配置,查看undo状态
- CS231n 卷积神经网络与计算机视觉 7 神经网络训练技巧汇总 梯度检验 参数更新 超参数优化 模型融合 等