Machine Learning Pytorch

CMSC 510 HW2 –

The goal of the homework is to gain familiarity with PyTorch (to install it, see: ), a machine learning library for python that allows for
defining the machine learning model and performing gradient descent for it in an automated

Don't use plagiarized sources. Get Your Custom Essay on
Machine Learning Pytorch
Just from $13/Page
Order Essay

Complete 4 exercises described below, and submit via Canvas a zip file with four Jupyter
Notebook files, one per each exercise. Each notebook should contain the code, as well as short
reports on the results of experiments.

Exercise 1.

Train a linear classifier for the Iris dataset (a 3-class classification problem, file iris.csv in
Canvas), using Mean Squared Error as loss (see file on Canvas).
Perform an analysis of the behavior of training risk and accuracy for different learning rates.

Detailed steps:
a) Use pandas to load the iris dataset. Create dummy variables for the classes

b) Define pytorch tensors for the dataset using:

c) Define pytorch tensors (with gradient) for weights and biases (W & b). W should be
n_features x n_classes, b should be 1 x n_classes. Initialize b to zeros (torch.zeros), and W to
random values sampled from a normal distribution with null mean – try different values for the
standard deviation and observe changes in the training behavior.

d) Define pytorch optimizer over variables W & b
torch.optim.SGD or torch.optim.Adam

e) Create the main loop that goes over the dataset in multiple epochs. In each epoch
e1) clear gradients (using optimizer.zero_grad)
e2) calculate linear predictions: pred=X W + b using
e3) pass the linear predictions through the unipolar sigmoid: sigmoid(pred)=1/(1+exp(-
pred)). Use these functions:
torch.log, torch.exp
e4) calculate the squared difference between the predictions (after sigmoid) and the
true classes, for all three output neurons. Use:
e5) calculate risk = average the squared difference over the training samples. Use:
torch.mean e6) calculate gradients of risk with respect to W & b (call risk.backwards)
e7) make optimizer step (using optimizer.step)
e8) calculate accuracy

Experiment with different learning rates for the two optimizers and report the behavior of the
training loss and accuracy.

Exercise 2.

Train a linear classifier for the Iris dataset, using CrossEntropy as loss. Perform an analysis of the
behavior of training risk and accuracy for different learning rates.

Detailed steps – follow Exercise 1, but replace MSE with CrossEntropy:

e3) pass the linear predictions through softmax (i.e., normalize the unipolar sigmoids for classes
i=1,…,3 to sum up to 1 for each sample)

e4) calculate the cross entropy after softmax (sum_{i=1}^3 y_i ln(softmax_i)).
torch.multiply, torch.log, torch.sum

e5) calculate risk = average the cross entropy over the training samples

Experiment and report results as in Exercise 1.

Exercise 3.

Starting from Exercise 2, add a split of the Iris dataset into a training set and a test set. Also, in
the training loop, go over small batches of samples (e.g. 20 samples) instead of always over the
whole training set. Experiment with batch size and learning rate.

Exercise 4:

Linear classifier for MNIST Digits dataset. Explore the behavior of the code from Exercise 3 on a
larger, more complicated dataset and report the results.
The number of training samples is 50,000 – analyze training behavior if a random subset of 100,
500, 1000, 2000 samples is used instead. Also, experiment with the learning rate and the batch

For loading the dataset, use: import torchvision.datasets as datasets
full_train_dataset = datasets.MNIST(root=’./data’, train=True, download=True, transform=None)
full_test_dataset = datasets.MNIST(root=’./data’, train=False, download=True, transform=None)
x_train =,n_features).astype(dtype=np.float)/255.0;
x_test =,n_features).astype(dtype=np.float)/255.0;
y_train_cat = full_train_dataset.targets.numpy()
y_test_cat = full_test_dataset.targets.numpy()
Note that the download of the dataset may take long time. As with Iris, convert categorical
variables for classes into dummy variables (there are 10 classes).


Calculate The Price Of Your Paper

{{total || ""}}

Why Choose Us

Top Quality and Well-Researched Papers

We always make sure that writers follow all your instructions precisely. You can choose your academic level: high school, college/university or professional, and we will assign a writer who has a respective degree.

Professional and Experienced Academic Writers

We have a team of professional writers with experience in academic and business writing. Many are native speakers and able to perform any task for which you need help.

Free Unlimited Revisions

If you think we missed something, send your order for a free revision. You have 10 days to submit the order for review after you have received the final document. You can do this yourself after logging into your personal account or by contacting our support.

Prompt Delivery and 100% Money-Back-Guarantee

All papers are always delivered on time. In case we need more time to master your paper, we may contact you regarding the deadline extension. In case you cannot provide us with more time, a 100% refund is guaranteed.

Original & Confidential

We use several writing tools checks to ensure that all documents you receive are free from plagiarism. Our editors carefully review all quotations in the text. We also promise maximum confidentiality in all of our services.

Customer Support 24/7

Our support agents are available 24 hours a day 7 days a week and committed to providing you with the best customer experience. Get in touch whenever you need any assistance.

Our FREE services
Every order comes with these awesome features.
Order Now
Money Back Guarantee
FREE Best essay writer across your subject
FREE Cover page and bibliography
FREE APA/MLA/Chicago formatting
FREE Free Revisions
FREE 24/7 customer support hotline and chat


Essay Writing Services

No matter what kind of academic paper you need and how urgent you need it, you are welcome to choose your academic level and the type of your paper at an affordable price. We take care of all your paper needs and give a 24/7 customer care support system.


Admission and Business Papers

An admission essay is an essay or other written statement by a candidate, often a potential student enrolling in a college, university, or graduate school. You can be rest assurred that through our service we will write the best admission essay for you.


Editing and Proofreading

Our academic writers and editors make the necessary changes to your paper so that it is polished. We also format your document by correctly quoting the sources and creating reference lists in the formats APA, Harvard, MLA, Chicago / Turabian.


Revision Support

If you think your paper could be improved, you can request a review. In this case, your paper will be checked by the writer or assigned to an editor. You can use this option as many times as you see fit. This is free because we want you to be completely satisfied with the service offered.