It is best to read the model definitions first, otherwise you wont know what’s wrong.
Densenet has average pooling before the classifier stage:

  
      github.com
  
  
    pytorch/vision/blob/master/torchvision/models/densenet.py#L158-L159 98

if isinstance(m, nn.Conv2d):
    nn.init.kaiming_normal(m.weight.data)



  
  
    
    
  
  


Here’s a corrected version:
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.models as models
import torch.nn.functional as F

class Densenet161(nn.Module):
    def __init__(self, num_classes = 2):
        super(Densenet161,self).__init__()
        original_model = models.densenet161()
        self.features = nn.Sequential(*list(original_model.children())[:-1])
        self.classifier = (nn.Linear(2208, num_classes))

    def forward(self, x):
        f = self.features(x)
        f = F.relu(f, inplace=True)
        f = F.avg_pool2d(f, kernel_size=7).view(f.size(0), -1)
        y = self.classifier(f)
        return f,y


x = Densenet161()

inp = Variable(torch.randn(4, 3, 224, 224))

out = x(inp)