Homework 1

In this homework we will get started with PyTorch and build our first PyTorch Module.

Refer Section 1 slides for installation instructions and starter code

Estimating PI

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:

circle
credit: www.stealthcopter.com

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 .

Input

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.

Output

The output of the forward() should be a single value float tensor that contains the estimate of .

Sample input

To see some sample inputs run

import torch
n = 1000
torch.rand([n,2], dtype=torch.float32))

and enjoy.

Desired output

Relevant operations

Explicitly prohibited operations

Extra credit

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, mean, 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 x into float data type, you need to write x.float().

Submission

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.