<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 <div class="alert alert-block alert-info" style="margin-top
Step1:  Use the following function to visualize data
Step2:  <a id="ref1"></a>
<h2 align=center>Prepare Data </h2>
Load the training dataset by setting the parameters <code>train</code> to <code>True</code> and convert it to a tensor by placing a transform object in the argument <code>transform</code>.
Step3:  Load the testing dataset by setting the parameters train <code>False</code> and convert it to a tensor by placing a transform object in the argument <code>transform</code>.
Step4:  Note that the data type is long
Step5:  Data Visualization
Each element in the rectangular tensor corresponds to a number that represents a pixel intensity as demonstrated by the following image
Step6:  Plot the 3rd sample
Step7:  You see its a 1. Now, plot the second sample
Step8:  The Softmax function requires vector inputs. If you see the vector shape, you'll note it's 28x28.
Step9:  Flatten the tensor as shown in this image
Step10:  Double-click here for the solution.
<!-- 
model=nn.Sequential(nn.Linear(input_dim,output_dim))
-->
<a id="ref3"></a>
<h2>Define the Softmax Classifier, Criterion function, Optimizer, and Train the Model</h2>
View the size of the model parameters
Step11:  Cover the model parameters for each class to a rectangular grid
Step12:  Optimizer class
Step13:  Define the dataset loader
Step14:  Train the model and determine validation accuracy
Step15:  <a id="ref3"></a>
<h2 align=center>Analyze Results</h2>
Plot the loss and accuracy on the validation data
Step16:  Plot the first five misclassified samples
<ASSISTANT_TASK:>
Python Code:
!conda install -y torchvision
import torch 
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dsets
import matplotlib.pylab as plt
import numpy as np
Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px">
 <a href="http://cocl.us/pytorch_link_top"><img src = "http://cocl.us/Pytorch_top" width = 950, align = "center"></a>
<img src = "https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png" width = 200, align = "center">
<h1 align=center><font size = 5>Practice: Softmax Classifer Using Sequential  </font></h1> 
# Table of Contents
In this lab, you will use a single layer Softmax to classify handwritten digits from the MNIST database.
<div class="alert alert-block alert-info" style="margin-top: 20px">
<li><a href="#ref0">Helper Functions</a></li>
<li><a href="#ref1">Prepare Data</a></li>
<li><a href="#ref2">Create a Softmax classifier Using Sequential</a></li>
<li><a href="#ref3">Criterion function, Optimizer, and Train the Model</a></li>
<li><a href="#ref4">Analyze Results</a></li>
<br>
<p></p>
Estimated Time Needed: <strong>25 min</strong>
</div>
<hr>
<a id="ref0"></a>
<h2 align=center>Helper functions </h2>
End of explanation
def show_data(data_sample):
    plt.imshow(data_sample[0].numpy().reshape(28,28),cmap='gray')
    #print(data_sample[1].item())
    plt.title('y= '+ str(data_sample[1].item()))
Explanation: Use the following function to visualize data:
End of explanation
train_dataset=dsets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor())
train_dataset
Explanation: <a id="ref1"></a>
<h2 align=center>Prepare Data </h2>
Load the training dataset by setting the parameters <code>train</code> to <code>True</code> and convert it to a tensor by placing a transform object in the argument <code>transform</code>.
End of explanation
validation_dataset=dsets.MNIST(root='./data', train=False, download=True, transform=transforms.ToTensor())
validation_dataset
Explanation: Load the testing dataset by setting the parameters train <code>False</code> and convert it to a tensor by placing a transform object in the argument <code>transform</code>.
End of explanation
train_dataset[0][1].type()
Explanation: Note that the data type is long:
End of explanation
train_dataset[3][1]
Explanation: Data Visualization
Each element in the rectangular tensor corresponds to a number that represents a pixel intensity as demonstrated by the following image:
<img src = "https://ibm.box.com/shared/static/7024mnculm8w2oh0080y71cpa48cib2k.png" width = 550, align = "center"></a>
Print out the third label:
End of explanation
show_data(train_dataset[3])
Explanation: Plot the 3rd sample:
End of explanation
show_data(train_dataset[2])
Explanation: You see its a 1. Now, plot the second sample:
End of explanation
train_dataset[0][0].shape
Explanation: The Softmax function requires vector inputs. If you see the vector shape, you'll note it's 28x28.
End of explanation
input_dim=28*28
output_dim=10
input_dim
Explanation: Flatten the tensor as shown in this image:
<img src = "https://ibm.box.com/shared/static/0cjl5inks3d8ay0sckgywowc3hw2j1sa.gif" width = 550, align = "center"></a> 
The size of the tensor is now 784.
<img src = "https://ibm.box.com/shared/static/lhezcvgm82gtdewooueopxp98ztq2pbv.png" width = 550, align = "center"></a>
Set the input size and output size. 
<a id="ref3"></a>
Create a Softmax Classifier by Using Sequential
End of explanation
print('W:',list(model.parameters())[0].size())
print('b',list(model.parameters())[1].size())
Explanation: Double-click here for the solution.
<!-- 
model=nn.Sequential(nn.Linear(input_dim,output_dim))
-->
<a id="ref3"></a>
<h2>Define the Softmax Classifier, Criterion function, Optimizer, and Train the Model</h2>
View the size of the model parameters:
End of explanation
criterion=nn.CrossEntropyLoss()
Explanation: Cover the model parameters for each class to a rectangular grid:  
<a>     <img src = "https://ibm.box.com/shared/static/9cuuwsvhwygbgoogmg464oht1o8ubkg2.gif" width = 550, align = "center"></a> 
Plot the model parameters for each class: 
Loss function:
End of explanation
learning_rate=0.1
optimizer=torch.optim.SGD(model.parameters(), lr=learning_rate)
Explanation: Optimizer class:
End of explanation
train_loader=torch.utils.data.DataLoader(dataset=train_dataset,batch_size=100)
validation_loader=torch.utils.data.DataLoader(dataset=validation_dataset,batch_size=5000)
Explanation: Define the dataset loader:
End of explanation
n_epochs=10
loss_list=[]
accuracy_list=[]
N_test=len(validation_dataset)
#n_epochs
for epoch in range(n_epochs):
    for x, y in train_loader:
      
        #clear gradient 
        optimizer.zero_grad()
        #make a prediction 
        z=model(x.view(-1,28*28))
        # calculate loss 
        loss=criterion(z,y)
        # calculate gradients of parameters 
        loss.backward()
        # update parameters 
        optimizer.step()
        
        
        
    correct=0
    #perform a prediction on the validation  data  
    for x_test, y_test in validation_loader:
        z=model(x_test.view(-1,28*28))
        _,yhat=torch.max(z.data,1)
        correct+=(yhat==y_test).sum().item()
        
   
    accuracy=correct/N_test
    accuracy_list.append(accuracy)
    
    loss_list.append(loss.data)
    accuracy_list.append(accuracy)
Explanation: Train the model and determine validation accuracy:
End of explanation
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.plot(loss_list,color=color)
ax1.set_xlabel('epoch',color=color)
ax1.set_ylabel('total loss',color=color)
ax1.tick_params(axis='y', color=color)
    
ax2 = ax1.twinx()  
color = 'tab:blue'
ax2.set_ylabel('accuracy', color=color)  
ax2.plot( accuracy_list, color=color)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout()
Explanation: <a id="ref3"></a>
<h2 align=center>Analyze Results</h2>
Plot the loss and accuracy on the validation data:
End of explanation
count=0
for x,y in validation_dataset:
    z=model(x.reshape(-1,28*28))
    _,yhat=torch.max(z,1)
    if yhat!=y:
        show_data((x,y))
        plt.show()
        print("yhat:",yhat)
        count+=1
    if count>=5:
        break 
        
Explanation: Plot the first five misclassified samples:
End of explanation
<END_TASK>