How do I average photo feature outputs for later concatenation?

Jordan_Howell: <p>Hello.</p>
<p>I have the following model schema where one set of photos go through an encoder, another set of photos go through an encoder and both get concatenated with a tabular data set for a final model to predict a binary target.</p>
<p>How do I average the features of the image encoders? I want to average by ID within each model.  See schema below.</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/1/3/1381378a2b36a41e62460cba23be74aadeaf0431.png" data-download-href="https://discuss.pytorch.org/uploads/default/1381378a2b36a41e62460cba23be74aadeaf0431" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/1/3/1381378a2b36a41e62460cba23be74aadeaf0431.png" alt="image" data-base62-sha1="2MxUUIGHWqEiaMQqVeOwyPr9Jgl" width="690" height="404" data-dominant-color="BDC8DF"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1274×746 47.9 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>There are 1 to 5 photos per ID.  There is an ID in each image model and tabular data set.</p>
<p>My data class returns the image, label and ID (called policy)…see below code for that class:</p>
<pre data-code-wrap="python"><code class="lang-python">class image_Dataset(Dataset):
    '''
    roof data class    
    
    '''
    def __init__(self, csv_file, transform = None):
        '''
        Args:
            csv_file (string): Path to the csv file with annotations.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        '''
        self.roof_frame = pd.read_csv(csv_file)
        self.transform = transform
        
    def __len__(self):
        return len(self.roof_frame)
    
    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()
         
        root_dir = self.roof_frame.iloc[idx,4]
        pic = self.roof_frame.iloc[idx, 1]
        label = self.roof_frame.iloc[idx, 3]
        img_name = os.path.join(root_dir, pic)
        image = Image.open(img_name)
        policy = self.roof_frame.iloc[idx, 0]
        sample = {'image': image, 'policy': policy, 'label':label}

        if self.transform:
            image = self.transform(image)

        return image, label, policy
</code></pre>
<p>I took the following code snipped off of this forum but I’m not sure how to get the mean of each feature set per ID.  Could anyone help with that code assuming the below snippet as an example? (note: I did not add anything from the tabular dataset yet to the below)</p>
<pre data-code-wrap="python"><code class="lang-python">class SuperEncoder(nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.roofEncoder = nn.Sequential(
            nn.Conv2d(3, 6, 3, 1, 1),
            nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Conv2d(6, 12, 3, 1, 1),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        
        self.dwellingEconder = nn.Sequential(
            nn.Conv2d(1, 6, 3, 1, 1),
            nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Conv2d(6, 12, 3, 1, 1),
            nn.ReLU(),
            nn.MaxPool2d(2)
        )
        
        self.fc1 = nn.Linear(54*54*16, 1000)
        
        self.fc2 = nn.Linear(54*54*16, 1000)
        
        self.fc_out(x)
            
        
    def forward(self, x1, x2):
        x1 = self.roofEncoder(x1)
        x1 = x1.view(x1.size(0), -1)
        x1 = F.relu(self.fc1(x1))
        
        x2 = self.dwellingEncoder(x2)
        x2 = x2.view(x2.size(0), -1)
        x2 = F.relu(self.fc2(x2))

        # Concatenate in dim1 (feature dimension)
        X = torch.concat((x1, x2), 1)
        x = self.fc_out(x)
        return self.log_softmax(X, dim=1)
</code></pre>

albanD: <p>Hi,</p>
<p>I’m not sure what you want to do here.<br>
Do you have a pseudo code that shows what you want to do?<br>
What is the link between the diagram and the code you posted?</p>

Jordan_Howell: <p>Sorry for the confusion.   The diagram is a concept of what I’m trying to do.  The code is the custom data class that returns the transformed image, target label and the policy (which is the ID).  I need to average a feature set when there are more than one image per ID to the ID, then join that with the tabular dataset to predict a binary outcome.</p>
<p>Does that make sense?  Let me know if it doesn’t.  I’m newish to Pytorch.</p>

albanD: <p>Just for me to understand better, you want to do something like that?</p>
<pre><code class="lang-auto">for input, target, ID in dataloader:
  # Assume batch_size == input.size(0)
  features = SuperEncoder()(input) # Is that right? You encode enverything here?
  # We have features.size(0) == batch_size
  avg_features = # Some ops that average all the features with the same ID?
  # But now avg_features.size(0) == ??
  # What shall we do with the targets? Should they be averaged as well?

  # More code
</code></pre>

Jordan_Howell: <p>Yes but the targets do not necessarily need anything done with them here.  I just want to join the features to the tabular dataset later.</p>

Jordan_Howell: <p>I was hoping to get a feature size of 1000 out.</p>

albanD: <p>You want <code>avg_features.size(0) == batch_size</code> ?<br>
But what should each of these contain? For each sample, its feature should be the average of all the features with this ID? That would mean that many samples will have the same features right?</p>

Jordan_Howell: <p>I don’t think so.  The IDs with many images are very different between each  image though maybe I’m thinking about this wrong?</p>

Jordan_Howell: <p>I think my confusion maybe coming from the novice skill set I have.  I’m trying to predict a binary outcome per ID, where I have a tabular dataset with one observation per ID, and two sets of images with a relationship of 1 ID to N amount of photos.  I was thinking this concept maybe like Uber’s Ludwig model but now I think I’m way off.  Any guidance at this point will be greatly appreciated.  Thank you for sticking with me.</p>

albanD: <p>Hi,</p>
<p>I’m not sure to understand what is the task you’re trying to accomplish. Whether your IDs are labels or not? What is the link between IDs and labels?</p>

Jordan_Howell: <p>Labels are the target labels. Ids are the level I ultimately want to predict at. Which is why I’m wanting to average by ID.</p>
<p>Jordan</p>

Jordan_Howell: <p>So I’ve made headway, I think.  Starting with my test loop:</p>
<blockquote>
<h1>Run the testing batches</h1>
<pre><code>with torch.no_grad(): # do not update weights and bias
    for b, (X_test, y_test, policy) in enumerate(test_loader):
        policy_list.append(policy)
        X_test = X_test.to(device)
        y_test = y_test.to(device)
        if b == max_tst_batch:
            break

        # Apply the model
        y_val = AlexNetmodel(X_test)
        y_val_list.append(y_val.data)
        # Tally the number of correct predictions
        predicted = torch.max(y_val.data, 1)[1] 
        tst_corr += (predicted == y_test).sum()

loss = criterion(y_val, y_test)
test_losses.append(loss)
test_correct.append(tst_corr)
</code></pre>
</blockquote>
<p>My batch size is 100 for 15600 so I get a list of 156 tensors consisting of 100 policies each and another list of 156 tensors consisting of predictions.   Here is a print out:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/c/f/cff3300816f577c2030f1f6e9c0a0a6e6fee36c5.png" data-download-href="https://discuss.pytorch.org/uploads/default/cff3300816f577c2030f1f6e9c0a0a6e6fee36c5" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/c/f/cff3300816f577c2030f1f6e9c0a0a6e6fee36c5.png" alt="image" data-base62-sha1="tFBRx9sFqw0FqnyWLCJKyrhRAQl" width="690" height="254" data-dominant-color="F8F8F8"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">766×282 8.31 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>I’m guessing I would need to unpack this list and the policy list and join them in a dataframe.  Then average the predictions by policy?</p>

albanD: <p>I guess you can compute these averages on the fly.<br>
Accumulate the values for each policy and the number of samples per policy. At the end just divide the accumulated value by the number of samples for each policy.</p>

Jordan_Howell: <p>Yep!  Is there some syntax to change these from a tensor?  The policies are coming back a tensor as well.</p>
<p>I’m using this to unpack the policy and prediction list.</p>
<blockquote>
<p>policies = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
while policy_list:<br>
policies.extend(policy_list.pop(0))</p>
<p>policies</p>
</blockquote>
<p>This is what I get back…each policy still a tensor.</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/1/7/1769a65a8088cfddf45a0106e76f2e44c38c0cc4.png" data-download-href="https://discuss.pytorch.org/uploads/default/1769a65a8088cfddf45a0106e76f2e44c38c0cc4" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/1/7/1769a65a8088cfddf45a0106e76f2e44c38c0cc4.png" alt="image" data-base62-sha1="3l7kNI0oOQD5XTWWka0eIaybGPW" width="690" height="186" data-dominant-color="F0F0F0"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">830×224 7.67 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

albanD: <p>Hi,<br>
You have a <a href="https://pytorch.org/docs/stable/tensors.html?highlight=tolist#torch.Tensor.tolist" rel="nofollow noopener"><code>tolist()</code></a> method on tensors to do that</p>