项目场景:
在ssd.pytorch-master测试时会出现问题:
RuntimeError: Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method.
参考链接saya
问题描述:
@RuntimeError: Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method
原因分析:
由于当前的pytorch版本过高,而原代码的版本较低。当前版本要求forward过程是静态的,所以需要将原代码进行修改。
解决方案:
一、修改ssd.pytorch-master/layers/functions/detection.py
1、注释掉13-22行的def _ init _()函数。
2、修改def forward()函数
把第24-33行
def forward(self, loc_data, conf_data, prior_data):
"""
Args:
loc_data: (tensor) Loc preds from loc layers
Shape: [batch,num_priors*4]
conf_data: (tensor) Shape: Conf preds from conf layers
Shape: [batch*num_priors,num_classes]
prior_data: (tensor) Prior boxes and variances from priorbox layers
Shape: [1,num_priors,4]
"""
改为如下:
@staticmethod
def forward(self, num_classes, bkg_label, top_k, conf_thresh, nms_thresh, loc_data, conf_data, prior_data):
"""
Args:
loc_data: (tensor) Loc preds from loc layers
Shape: [batch,num_priors*4]
conf_data: (tensor) Shape: Conf preds from conf layers
Shape: [batch*num_priors,num_classes]
prior_data: (tensor) Prior boxes and variances from priorbox layers
Shape: [1,num_priors,4]
"""
self.num_classes = num_classes
self.background_label = bkg_label
self.top_k = top_k
# Parameters used in nms.
self.nms_thresh = nms_thresh
if nms_thresh <= 0:
raise ValueError('nms_threshold must be non negative.')
self.conf_thresh = conf_thresh
self.variance = cfg['variance']
二、修改ssd.py 文件
第46-48行
if phase == 'test':
self.softmax = nn.Softmax(dim=-1)
self.detect = Detect(num_classes, 0, 200, 0.01, 0.45)
改为
if phase == 'test':
self.softmax = nn.Softmax()
self.detect = Detect()
把第98-104
if self.phase == "test":
output = self.detect(
loc.view(loc.size(0), -1, 4), # loc preds
self.softmax(conf.view(conf.size(0), -1,
self.num_classes)), # conf preds
self.priors.type(type(x.data)) # default boxes
)
改为
if self.phase == "test":
output = self.detect.apply(21, 0, 200, 0.01, 0.45,
loc.view(loc.size(0), -1, 4), # loc preds
self.softmax(conf.view(-1,
21)), # conf preds
self.priors.type(type(x.data)) # default boxes
)
```