C1M4_Assignment, part 2(exercise 2)

Hi all, I have a problem in doing exercise 2 - CNNBlock.
when I use the following code:
self.block = nn.Sequential(

nn.Conv2d(in_channels, out_channels, kernel_size, padding),

)
It shows error when tested in unittests.exercise_2(CNNBlock):

However, if I change it to the following, it passes the test
self.block = nn.Sequential(

nn.Conv2d(in_channels, out_channels, kernel_size**=kernel_size**, padding**=padding**),

)

Could someone explains? Thank you!

In python, when passing parameters to functions, there is a key distinction that you need to know whether a given parameter is “positional” or a “keyword” parameter. The keyword parameters (also sometimes called “named parameters”) are optional and have default values that are declared in definition of the function. Check the definition of the torch.nn.Conv2d function and you’ll see that it has 3 positional parameters: in_channels, out_channels and kernel_size. All the rest are keyword parameters and note that padding is not the first of the keyword parameters: stride is.

If you use your first version of the code, then I believe what that will do is set stride to the padding value.

If you are relatively new to python, it would be a good idea to google “python keyword parameters” and spend half an hour reading some tutorials or documentation about how they work.

1 Like

Hi @mt73564

Basically you passed the value instead of assigned local arguments in the given def init statment causing incorrect passing of values when the class CNN block was used to create the Simple CNN Block as in when python libraries are used they are created in a way where parameters are passed through keyword arguments as @paulinpaloalto explained what it cost when using the CNNBlock with positional passing of information.

By using the param_name=variable_name syntax (known as a keyword argument), you explicitly tell Python:Use the value of my local/outer variable named variable_name and assign it to the parameter named param_name. This bypasses the variable shadowing issue because you are making a clear assigning of parameters and not just trying to read an unassigned local variable.

Regards

DP

Thank you @paulinpaloalto and @Deepti_Prasad .

1 Like