In this homework we will get started with PyTorch and build our first PyTorch Module.
You task is to estimate given a bunch of uniform random numbers in the interval . Recall that the area of a circle is see. The area of a unit circle () is thus just . Consider a unit circle centered at chances that a random point lies inside that circle is proportional the the area of the circle in , the positive quadrant 1. The figure below nicely visualizes this:
One way to estimate is to draw random samples and see what fraction lies within the unit circle.
In this assignment you will write a PyTorch program that takes a set of random numbers as input and outputs a single value, which is an estimate of .
The input to the network should be passed to the
forward() function of the module class that inherits the torch.nn.Module. The input should be a tensor of where denotes the number of random samples.
The output of the
forward() should be a single value float tensor that contains the estimate of .
To see some sample inputs run
import torch n = 1000 torch.rand([n,2], dtype=torch.float32))
Explicitly prohibited operations
- constants (other than 0, 1, 2, 4)
The estimator for pi above has a fairly high variance, meaning it needs a lot of random numbers to accurately estimate pi. Can you estimate pi more accurately using fewer random numbers?
I’m sure the internet holds the answer to this somewhere, but try to figure this out yourself first.
Hint: You don’t need any operations other than elementary mathematical operations,
sqrt and the constant 1 and 4. You might also need to cast your tensor into another data type. This is quite straightforward in Pytorch, for example to cast a tensor
float data type, you need to write
Step 1: Write all your logic in the
forward() function of the
homework/main.py file provided in the starter code.
Step 2: To test the
forward() function call, execute the following command
python3 -m homework.test
Step 3: Run the grader to test your model.
python3 -m grader homework
Step 4: Create a submission file
python3 -m homework.bundle
Note that the grader you have access to is a weaker version of our final grader. Test your program extensively before submission.