CMSC 510 HW2 – The goal of the homework is

CMSC 510 HW2 –

The goal of the homework is to gain familiarity with PyTorch (to install it, see:
https://pytorch.org/get-started/locally/ ), a machine learning library for python that allows for
defining the machine learning model and performing gradient descent for it in an automated
way.

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 pytorch_linear_Iris_MSE.py 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:  
torch.tensor

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
torch.matmul
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:
torch.pow
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
size.

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 = full_train_dataset.data.numpy().reshape(-1,n_features).astype(dtype=np.float)/255.0;
x_test = full_test_dataset.data.numpy().reshape(-1,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).  

 

Share This Post

Email
WhatsApp
Facebook
Twitter
LinkedIn
Pinterest
Reddit

Order a Similar Paper and get 15% Discount on your First Order

Related Questions

Describe the cardiovascular system and explain how both the pulmonary

Question 4  Describe the cardiovascular system and explain how both the pulmonary and systemic circuits will be affected by both arrows.  Include the effect on the Hematocrit and Hemoglobin values. Question 5  Identify the possible neuromuscular effects of the second arrow and explain your reasoning.  Describe

Please use template provided. You have been hired by the

Please use template provided. You have been hired by the D. M. Pan National Real Estate Company to develop a model to predict housing prices for homes sold in 2019. The CEO of D. M. Pan wants to use this information to help their real estate agents better determine the

Using voice-over PowerPoint or YouTube, present and discuss the type

Using voice-over PowerPoint or YouTube, present and discuss the type of organization you selected in Week 1, the chart of accounts you plan to use in your company and the internal controls you would set up for your company. Writing and interpreting results is a large part of your learning

Hello I need assistance with the attached assignment. The assignment

 Hello I need assistance with the attached assignment. The assignment has a lot of details so please read each and everyone of them carefully. If you are confused about any portion of the assignment please alert me right away. I will include all material that will help you with the

Please research and answer the following questions. Question #1 How

   Please research and answer the following questions. Question #1  How and why did Dr. Yunus gain international recognition?  Question # 2 What is Dr. Yunus ultimate goal?  Question #3 What can we learn from Dr. Yunus’ leadership style?  Question #4  Should future social entrepreneur follow Dr. Yunus’ leadership blueprint? 

Philosophy of education

 The book for this assignment is Philosophy of education before the twentieth Century chapter 1 by Nel Nodding. The questions for this assignment are: 1) what is the author position, what are the author reasons (at least 2) 2) the use of vouchers as a method of School reform what

M3.4 Evaluate is due at the end of Module 3 by Sunday at 11:59 PM EST.Introduction to the Activity This Evaluate writing assignment addresses Course Outcome 2. You have read and viewed the assigned ma Nursing Assignment Help

M3.4 Evaluate is due at the end of Module 3 by Sunday at 11:59 PM EST. Introduction to the Activity This Evaluate writing assignment addresses Course Outcome 2. You have read and viewed the assigned materials discussing how foods high in fat and sugar affect the brain. You have learned

Annotations: Use annotations APA format. There are three basic sections

Annotations: Use annotations APA format.  There are three basic sections in an annotation: 1) Summary, 2) source quality and justification, 3) Usefulness for the reader and application to the sports management field.  Be thorough, you will be graded on the thoroughness of the information, not on length. turn it in

Scenario Assume the role of the chief operations strategist for

  Scenario Assume the role of the chief operations strategist for a multi-specialty health care organization. You have determined that the organization could benefit from creating a workforce management strategy for the purpose of optimizing staffing levels. With worsening staffing shortages in critical areas such as nursing and primary care

ATA Box Binding Protein (TBP) – DNA

Background Science is a process of applying and building on the findings of others, so one of the major tasks of any scientist is to communicate their work to their colleagues. Scientific research in medicine, nutrition, agriculture and many other related fields relies on the sharing of new discoveries and

Link for Chapter 12 Content: https://opentextbook.site/informationsystems2019/chapter/chapter-12-the-ethical-and-legal-implications-of-information-systems-information-systems-introduction/ Chapter 12 questions, please

 Link for Chapter 12 Content: https://opentextbook.site/informationsystems2019/chapter/chapter-12-the-ethical-and-legal-implications-of-information-systems-information-systems-introduction/ Chapter 12 questions, please answer these in a sentence or two in a separate lines for each answers: What does the term information systems ethics mean? What is a code of ethics? What is one advantage and one disadvantage of a code of ethics? What does the term intellectual

One expert said that public health efforts to limit adolescent

  One expert said that public health efforts to limit adolescent smoking, substance abuse, early sexual behavior, and automobile accidents should focus less on educating the adolescent to be wiser, more informed, and less impulsive and more on limiting opportunities to engage in risky behavior (Steinberg, 2007). Examples of opportunity-limiting

Please ensure that your discussion is well formulated correctly with

Please ensure that your discussion is well formulated correctly with proper grammar. Please check spell and grammar check your post before submission.  All discussion posts should be no less than 500 words.  Although your opinion is valuable, your response should include factual information supported by the literature in academic writing.

Backward Design Job Aid

 Create a job aid about using backward design in lesson planning that you could use as a future reference. You could develop a flowchart, reference sheet, checklist, or any combination of these. Include the following in your job aid: Purpose of backward design Stages of backward design How backward design

Based on the videos in week one and additional research,

  Based on the videos in week one and additional research,  that describes 10 developmental and behavioral needs unique to individuals on the autism spectrum. 750-1000 Include on how teachers, families, and colleagues collaborate to identify the needs of individuals on the autism spectrum. at Reference  three scholarly sources to support your