-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmnist.py
112 lines (93 loc) · 3.23 KB
/
mnist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
####################BOT SETUP##########################
from pytorch_bot import bot
token = "YOUR TOKEN HERE" # replace TOKEN with your bot's token it must be string
# user id is optional, however highly recommended as it limits the access to you alone.
uid = None # replace None with your telegram user id (integer):
bot = bot(token=token, user_id=uid)
bot.activate_bot()
#########################PYTORCH########################
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("Using device:- ",device,end='\n')
# Hyper-parameters
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 10
batch_size = 64
learning_rate = 0.001
# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='../../data',
train=True, transform=transforms.ToTensor(), download=True)
test_dataset = torchvision.datasets.MNIST(root='../../data',
train=False, transform=transforms.ToTensor(), download=True)
# Data Loaders
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size, shuffle=False)
# Neural Network Class
class NeuralNet(nn.Module):
"""FeedForward Neural Network with one hidden layer
"""
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
model = NeuralNet(input_size, hidden_size, num_classes).to(device)
# Loss
loss_func = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
def test(message):
global status_message
with torch.no_grad():
correct = total = 0
for images, labels in test_loader:
images = images.reshape(-1,28*28).to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = loss_func(outputs, labels)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
message += '\nTest: Loss: {:.4f} Accuracy: {:.2f}'.format(loss, (100*correct)/total)
return message
# Training
print("Training Started....!!")
print()
for epoch in range(num_epochs):
cumulative_loss = 0.0
total = correct = 0
for i, (images, labels) in enumerate(train_loader):
images = images.reshape(-1,28*28).to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = loss_func(outputs, labels)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
cumulative_loss += loss.item()
# Backprop and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
message = 'Train: Epoch [{}/{}], Loss: {:.4f} Accuracy: {:.2f}'.format(epoch+1, num_epochs, cumulative_loss/total, (100*correct)/total)
message = test(message)
print(message)
bot.send_message(message)
bot.set_status(message)
print("Training finished...!!")
bot.send_message('Training finished..!!')
bot.stop_bot()