microquantum1 commited on
Commit
b5df1b7
·
1 Parent(s): eecf70c
Files changed (2) hide show
  1. app.py +168 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
+ import joblib
5
+ import torch.nn as nn
6
+ import torch.optim as optim
7
+
8
+ from datasets import load_dataset
9
+ from sklearn.feature_extraction.text import TfidfVectorizer
10
+ from sklearn.model_selection import train_test_split
11
+
12
+ MODEL_DIR = "model"
13
+ MODEL_PATH = f"{MODEL_DIR}/net.pt"
14
+ VEC_PATH = f"{MODEL_DIR}/vectorizer.joblib"
15
+
16
+ LABELS = ["World", "Sports", "Business", "Sci/Tech"]
17
+ NUM_CLASSES = 4
18
+
19
+ device = "cuda" if torch.cuda.is_available() else "cpu"
20
+
21
+ vectorizer = None
22
+ model = None
23
+
24
+
25
+ # -------------------------
26
+ # Neural Network (from scratch)
27
+ # -------------------------
28
+ class TextNet(nn.Module):
29
+ def __init__(self, input_dim):
30
+ super().__init__()
31
+ self.fc1 = nn.Linear(input_dim, 256)
32
+ self.fc2 = nn.Linear(256, 128)
33
+ self.out = nn.Linear(128, NUM_CLASSES)
34
+
35
+ def forward(self, x):
36
+ x = torch.relu(self.fc1(x))
37
+ x = torch.relu(self.fc2(x))
38
+ return self.out(x)
39
+
40
+
41
+ # -------------------------
42
+ # Train / Continual Train
43
+ # -------------------------
44
+ def train_model(epochs=5, continual=False, progress=gr.Progress()):
45
+ global model, vectorizer
46
+
47
+ progress(0.05, desc="Loading dataset...")
48
+ dataset = load_dataset("ag_news")
49
+ texts = dataset["train"]["text"][:6000]
50
+ labels = dataset["train"]["label"][:6000]
51
+
52
+ if vectorizer is None or not continual:
53
+ vectorizer = TfidfVectorizer(max_features=8000, stop_words="english")
54
+ X = vectorizer.fit_transform(texts)
55
+ else:
56
+ X = vectorizer.transform(texts)
57
+
58
+ y = torch.tensor(labels)
59
+
60
+ X_train, X_val, y_train, y_val = train_test_split(
61
+ X, y, test_size=0.2
62
+ )
63
+
64
+ X_train = torch.tensor(X_train.toarray(), dtype=torch.float32).to(device)
65
+ X_val = torch.tensor(X_val.toarray(), dtype=torch.float32).to(device)
66
+ y_train = y_train.to(device)
67
+ y_val = y_val.to(device)
68
+
69
+ if model is None or not continual:
70
+ model = TextNet(X_train.shape[1]).to(device)
71
+
72
+ criterion = nn.CrossEntropyLoss()
73
+ optimizer = optim.Adam(model.parameters(), lr=0.001)
74
+
75
+ history = []
76
+
77
+ for epoch in range(epochs):
78
+ model.train()
79
+ optimizer.zero_grad()
80
+
81
+ outputs = model(X_train)
82
+ loss = criterion(outputs, y_train)
83
+ loss.backward()
84
+ optimizer.step()
85
+
86
+ # Accuracy
87
+ preds = outputs.argmax(dim=1)
88
+ acc = (preds == y_train).float().mean().item()
89
+
90
+ # Validation
91
+ model.eval()
92
+ with torch.no_grad():
93
+ val_out = model(X_val)
94
+ val_loss = criterion(val_out, y_val).item()
95
+ val_acc = (val_out.argmax(dim=1) == y_val).float().mean().item()
96
+
97
+ history.append(
98
+ f"Epoch {epoch+1}/{epochs} | "
99
+ f"Loss: {loss.item():.4f} | Acc: {acc:.4f} | "
100
+ f"Val Loss: {val_loss:.4f} | Val Acc: {val_acc:.4f}"
101
+ )
102
+
103
+ progress((epoch + 1) / epochs, desc=f"Epoch {epoch+1}")
104
+
105
+ os.makedirs(MODEL_DIR, exist_ok=True)
106
+ torch.save(model.state_dict(), MODEL_PATH)
107
+ joblib.dump(vectorizer, VEC_PATH)
108
+
109
+ return "\n".join(history)
110
+
111
+
112
+ # -------------------------
113
+ # Load model
114
+ # -------------------------
115
+ def load_model():
116
+ global model, vectorizer
117
+
118
+ if not os.path.exists(MODEL_PATH):
119
+ return "No saved model found."
120
+
121
+ vectorizer = joblib.load(VEC_PATH)
122
+ model = TextNet(vectorizer.max_features).to(device)
123
+ model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
124
+ model.eval()
125
+
126
+ return "Model loaded successfully."
127
+
128
+
129
+ # -------------------------
130
+ # Predict
131
+ # -------------------------
132
+ def predict(text):
133
+ if model is None or vectorizer is None:
134
+ return "Train or load a model first."
135
+
136
+ vec = vectorizer.transform([text]).toarray()
137
+ x = torch.tensor(vec, dtype=torch.float32).to(device)
138
+
139
+ with torch.no_grad():
140
+ logits = model(x)
141
+ pred = logits.argmax(dim=1).item()
142
+
143
+ return LABELS[pred]
144
+
145
+
146
+ # -------------------------
147
+ # Gradio UI
148
+ # -------------------------
149
+ with gr.Blocks() as demo:
150
+ gr.Markdown("# 🧠 Neural Network AI (Gradio Blank)")
151
+ gr.Markdown("From-scratch neural network with continual learning.")
152
+
153
+ with gr.Row():
154
+ epochs = gr.Slider(1, 10, value=5, step=1, label="Epochs")
155
+ continual = gr.Checkbox(label="Continual Learning")
156
+
157
+ train_btn = gr.Button("Train / Continue Training")
158
+ load_btn = gr.Button("Load Saved Model")
159
+
160
+ log = gr.Textbox(lines=10, label="Training Log")
161
+ text_input = gr.Textbox(lines=4, placeholder="Enter news text...")
162
+ output = gr.Textbox(label="Prediction")
163
+
164
+ train_btn.click(train_model, inputs=[epochs, continual], outputs=log)
165
+ load_btn.click(load_model, outputs=log)
166
+ text_input.submit(predict, inputs=text_input, outputs=output)
167
+
168
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ datasets
3
+ torch
4
+ scikit-learn
5
+ joblib