Answered step by step
Verified Expert Solution
Question
1 Approved Answer
This challenge task is quite difficult and will really test your mastery of PyTorch and nn . Linear layers. We can manually assign weights to
This challenge task is quite difficult and will really test your mastery of PyTorch and nnLinear layers.
We can manually assign weights to an nnLinear like this:
import torch
import torch.nn as nn
lin nnLinear
manualweights torch.arangereshapelinweight.shape
lin.weight.data: manualweights
lin.bias.data:
But this does not calculate anything useful. A Linear layer simply performs a weighted sum plus bias We can choose weightsbiases to perform known operations.
INSTRUCTIONS:
Given an nnLinear layer, set the weights such that the layer adds to it's input.
Given an nnLinear layer, set the weights such that the layer calculates y x
Given an nnLinear layer, set the weights such that the layer calculates the average of it's inputs.
Given an nnLinear layer, set the weights such that the layer calculates both the average of it's inputs and the sum of the inputs.
Given an nnLinear layer, set the weights such that the layer returns the inputs, but in reverse order.
Given an nnLinear layer, set the weights such that the layer always returns
Note: We would never use this in a deep learning model; this challenge is to prove that you understand the mathematics and coding mechanics of the nnLinear layer.
import sc
sctestscmodifylin
sctestscmodifylin
sctestscmodifylin
sctestscmodifylin
sctestscmodifylin
sctestscmodifylin
scpy script:
import torch
import torch.nn as nn
# Put your solutions here
# Each function receives an nnLinear.
# Hint #: Make sure you print out the shape of the weights
# Hint #: You can fill multiple weights at once by assigning
# the weights to a tensor. eg
# lin.weight.data: torch.tensor
#
#
# dtypelin.weight.dtype, devicelin.weight.device
# Testing code: Tests your solutions
def testfnc:
inp torch.tensorreshape
tar torch.tensorreshape
layer nnLinear
fnclayer
out layerinp
torch.allcloseout tar
def testfnc:
inp torch.tensorreshape
tar torch.tensorreshape
layer nnLinear
fnclayer
out layerinp
torch.allcloseout tar
def testfnc:
inp torch.tensor
tar inp.meandim keepdimTrue
layer nnLinear
fnclayer
out layerinp
torch.allcloseout tar
def testfnc:
inp torch.tensor
tar torch.stack
inp.meandim
inp.sumdim
dim
layer nnLinear
fnclayer
out layerinp
torch.allcloseout tar
def testfnc:
inp torch.tensor
tar torch.tensor
layer nnLinear
fnclayer
out layerinp
torch.allcloseout tar
def testfnc:
inp torch.tensor
eeeee
tar torch.tensor
layer nnLinear
fnclayer
out layerinp
torch.allcloseout tar
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started