1

I would like to add an else statement to this comprehension but I am not having much luck placing it around different areas in the code below. I like the format of the below as I find it fairly readable given the length and activity.

This is not a duplicate of: if/else in a list comprehension as the guidance is seemingly not a solution for this form.

I am taking the guidance from this thread but still not finding that it works. Notice that I want an if and an else so this means that, following the thread:

['b' if isinstance(el, str) else el for el in X]  # When using 'if' and 'else', put 'for' in the end

So I have an if and and else and so they come in order and for is at the end.

import torch
import numpy as np
class mlp1(torch.nn.Module):
    def __init__(self, num_features, num_hidden, num_classes):
        super(mlp1, self).__init__()
        self.num_classes = num_classes
        self.input_layer = torch.nn.Linear(num_features, num_hidden)
        self.out_layer = torch.nn.Linear(num_hidden, num_classes)
    def forward(self, x):
        x = self.input_layer(x)
        x = torch.sigmoid(x)
        logits = self.out_layer(x)
        probas = torch.softmax(logits, dim=1)
        return logits, probas

model = mlp1(num_features=28*28, num_hidden=100, num_classes=10)

freeze = ['input_layer']
# randomly select weights
locked_masks = {
                name: torch.tensor(np.random.choice([False, True],
                                              size=torch.numel(weight),
                                              # freeze 90% of the weights
                                              p=[0.0, 1.0]).reshape(weight.shape))

                if any(weight in name for weight in freeze)
                else
                name: torch.tensor(np.random.choice([False, True],
                                              size=torch.numel(weight),
                                              # freeze 90% of the weights
                                              p=[0.0, 1.0]).reshape(weight.shape))
                for name, weight in model.named_parameters()

                }
John Stud
  • 1,506
  • 23
  • 46
  • 1
    Did I miss something because I didn't have a coffee yet, or are for expressions the same? – Klaus D. Mar 02 '21 at 05:17
  • I'm a bit confused. I don't see the `named_parameter` method defined in your `m1p1` class. As far as a list comprehension if if/else that looks right in your first block. Your second block should trigger an error. – astrochun Mar 02 '21 at 06:21
  • @astrochun `named_parameters` is inherited from the `nn.Module` class. – Nerveless_child Mar 02 '21 at 10:55

2 Answers2

2

The if else is not part of the dictionary comprehension but rather it is a ternary operator in python as mentioned in the post you linked.

What you're doing is wrong and would generate a SyntaxError.

This should give you an idea of what to do.

keys = range(6)
values = range(6)

print({(k if k%2==0 else k**2) : (v if v%2==1 else v**2) for k, v in zip(keys, values)})

What this does is for the keys, square the number if it is even and for the values, square the number if it is odd. This would output:

{0: 0, 1: 1, 2: 4, 9: 3, 4: 16, 25: 5}
Nerveless_child
  • 1,366
  • 2
  • 15
  • 19
1
 print({1 if 1==1 else 0 :'a'})

 output: (the value will always be 'a'

  {1: 'a'}
Golden Lion
  • 3,840
  • 2
  • 26
  • 35