Spaces:
Sleeping
Sleeping
deploy to huggingface
Browse files- .gitignore +2 -0
- NeuralNet.py +14 -0
- app.py +55 -0
- train.py +80 -0
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
data/*
|
2 |
+
model/*
|
NeuralNet.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
class NeuralNet(nn.Module):
|
4 |
+
def __init__(self, input_size, hidden_size, num_classes):
|
5 |
+
super(NeuralNet, self).__init__()
|
6 |
+
self.l1 = nn.Linear(input_size, hidden_size)
|
7 |
+
self.relu = nn.ReLU()
|
8 |
+
self.l2 = nn.Linear(hidden_size, num_classes)
|
9 |
+
|
10 |
+
def forward(self, x):
|
11 |
+
out = self.l1(x)
|
12 |
+
out = self.relu(out)
|
13 |
+
out = self.l2(out)
|
14 |
+
return out
|
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torchvision.transforms as transforms
|
4 |
+
from PIL import Image
|
5 |
+
import gradio as gr
|
6 |
+
from NeuralNet import NeuralNet
|
7 |
+
|
8 |
+
# Device Config
|
9 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
10 |
+
|
11 |
+
# Model Configurations
|
12 |
+
input_size = 784 # 28x28
|
13 |
+
hidden_size = 100
|
14 |
+
num_classes = 10
|
15 |
+
|
16 |
+
# Load the trained model (Assuming you have a trained model saved as 'model.pth')
|
17 |
+
model = NeuralNet(input_size, hidden_size, num_classes)
|
18 |
+
model.load_state_dict(torch.load('model/model.pt', map_location=device))
|
19 |
+
model.to(device)
|
20 |
+
model.eval()
|
21 |
+
|
22 |
+
# Define the transform
|
23 |
+
transform = transforms.Compose([
|
24 |
+
transforms.Grayscale(num_output_channels=1),
|
25 |
+
transforms.Resize((28, 28)),
|
26 |
+
transforms.ToTensor(),
|
27 |
+
transforms.Normalize((0.1307,), (0.3081,))
|
28 |
+
])
|
29 |
+
|
30 |
+
# Gradio function to process the image and make predictions
|
31 |
+
def predict(image):
|
32 |
+
# Load the image
|
33 |
+
image = Image.fromarray(image)
|
34 |
+
|
35 |
+
# Preprocess the image
|
36 |
+
image = transform(image).unsqueeze(0).to(device)
|
37 |
+
image = image.view(-1, 28*28) # Flatten the image
|
38 |
+
|
39 |
+
# Make prediction
|
40 |
+
with torch.no_grad():
|
41 |
+
outputs = model(image)
|
42 |
+
_, predicted = torch.max(outputs.data, 1)
|
43 |
+
return int(predicted.item())
|
44 |
+
|
45 |
+
# Create a Gradio interface
|
46 |
+
interface = gr.Interface(fn=predict,
|
47 |
+
inputs=gr.Image(),
|
48 |
+
outputs="label",
|
49 |
+
live=False,
|
50 |
+
title="Digit Recognizer using Feed-Forward Nueral Network",
|
51 |
+
description="Upload a digit image to recognize it")
|
52 |
+
|
53 |
+
# Launch the interface
|
54 |
+
if __name__ == "__main__":
|
55 |
+
interface.launch()
|
train.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torchvision
|
4 |
+
import torchvision.transforms as transforms
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from NeuralNet import NeuralNet
|
7 |
+
|
8 |
+
# Device Config
|
9 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
10 |
+
|
11 |
+
# hyper parameters
|
12 |
+
input_size = 784 # 28*28
|
13 |
+
hidden_size = 100
|
14 |
+
num_classes = 10
|
15 |
+
num_epochs = 20
|
16 |
+
batch_size = 500
|
17 |
+
learning_rate = 0.001
|
18 |
+
|
19 |
+
# MNIST
|
20 |
+
training_dataset = torchvision.datasets.MNIST(root='./data', train=True,
|
21 |
+
transform=transforms.ToTensor(), download=True)
|
22 |
+
test_dataset = torchvision.datasets.MNIST(root='./data', train=False,
|
23 |
+
transform=transforms.ToTensor())
|
24 |
+
train_loader = torch.utils.data.DataLoader(dataset=training_dataset, batch_size=batch_size, shuffle=True)
|
25 |
+
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
|
26 |
+
|
27 |
+
example = iter(train_loader)
|
28 |
+
samples, labels = next(example)
|
29 |
+
print(samples.shape, labels.shape)
|
30 |
+
|
31 |
+
# for i in range(6):
|
32 |
+
# plt.subplot(2, 3, i+1)
|
33 |
+
# plt.imshow(samples[i][0], cmap='gray')
|
34 |
+
# plt.show()
|
35 |
+
|
36 |
+
model = NeuralNet(input_size, hidden_size, num_classes)
|
37 |
+
|
38 |
+
#loss and optimizer
|
39 |
+
criterion = nn.CrossEntropyLoss()
|
40 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
|
41 |
+
|
42 |
+
#training loop
|
43 |
+
n_total_steps = len(train_loader)
|
44 |
+
for epoch in range(num_epochs):
|
45 |
+
for i, (images, labels) in enumerate(train_loader):
|
46 |
+
# 100, 1, 28, 28
|
47 |
+
# n, c, h, w
|
48 |
+
images = images.reshape(-1, 28*28).to(device)
|
49 |
+
labels = labels.to(device)
|
50 |
+
|
51 |
+
#forward
|
52 |
+
outputs = model(images)
|
53 |
+
loss = criterion(outputs, labels)
|
54 |
+
|
55 |
+
#backward
|
56 |
+
optimizer.zero_grad()
|
57 |
+
loss.backward()
|
58 |
+
optimizer.step()
|
59 |
+
|
60 |
+
if (i+1) % 100 == 0:
|
61 |
+
print(f'epoch {epoch+1}/{num_epochs}, step {i+1}/{n_total_steps}, loss = {loss.item():.4f}')
|
62 |
+
|
63 |
+
# test
|
64 |
+
with torch.no_grad():
|
65 |
+
n_correct = 0
|
66 |
+
n_samples = 0
|
67 |
+
for images , labels in test_loader:
|
68 |
+
images = images.reshape(-1, 28*28).to(device)
|
69 |
+
labels = labels.to(device)
|
70 |
+
|
71 |
+
outputs = model(images)
|
72 |
+
|
73 |
+
# value, index
|
74 |
+
_, predictions = torch.max(outputs, 1)
|
75 |
+
n_samples += labels.shape[0]
|
76 |
+
n_correct += (predictions == labels).sum().item()
|
77 |
+
|
78 |
+
acc = 100.0 * n_correct / n_samples
|
79 |
+
print(f'accuracy = {acc}')
|
80 |
+
torch.save(model.state_dict(), 'model/model.pt')
|