RuntimeError: view size is not compatible with input tensor's size

I tried to concatenate two models using the following code but got
RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
the code is

class MyEnsemble(nn.Module):
    def __init__(self, modelA, modelB):
        super(MyEnsemble, self).__init__()
        self.modelA = modelA
        self.modelB = modelB
        self.modelA.head = nn.Identity()
        self.modelB.head = nn.Identity()        
    def forward(self, x):
        x1 = self.modelA(x.clone()) 
        x1 = x1.view(x1.size(0), -1)
        x2 = self.modelB(x)
        x2 = x2.view(x2.size(0), -1)
        x = torch.cat((x1, x2), dim=1)
        gc.collect()
        x=torch.cuda.empty_cache()           
        return x

i tried to replace view with reshape but got another error in the method i created to extract the features in

    vec1=vec.detach().cpu().numpy()
AttributeError: 'NoneType' object has no attribute 'detach'

the code is

 image= load_img(filename, target_size=(224, 224,3))
 vec=model(preprocess(image).unsqueeze(0).cuda())
 vec1=vec.detach().cpu().numpy()

I think the issue is that x should be the output of the model in the forward method rather than the return value of torch.cuda.empty_cache() (which isn’t expected to return anything).

1 Like