Spaces:
Sleeping
Sleeping
File size: 5,852 Bytes
778a398 5965706 778a398 5965706 778a398 5965706 05048a9 5965706 05048a9 5965706 778a398 5965706 778a398 5965706 778a398 05048a9 778a398 5965706 778a398 5965706 778a398 5965706 778a398 5965706 778a398 05048a9 778a398 5965706 778a398 | 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | import os
import torch
import gradio as gr
import joblib
import torch.nn as nn
import torch.optim as optim
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
# -------------------------
# Config
# -------------------------
MODEL_DIR = "model"
MODEL_PATH = f"{MODEL_DIR}/net.pt"
VEC_PATH = f"{MODEL_DIR}/vectorizer.joblib"
LABELS = ["World", "Sports", "Business", "Sci/Tech"]
NUM_CLASSES = 4
device = "cuda" if torch.cuda.is_available() else "cpu"
vectorizer = None
model = None
# -------------------------
# Neural Network (from scratch)
# -------------------------
class TextNet(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.fc1 = nn.Linear(input_dim, 256)
self.fc2 = nn.Linear(256, 128)
self.out = nn.Linear(128, NUM_CLASSES)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
return self.out(x)
# -------------------------
# Safe Dataset Loader
# -------------------------
def load_agnews_safe():
"""
Hugging Face Spaces sometimes caches a deleted commit of ag_news.
This loader forces a fresh revision and retries if needed.
"""
try:
return load_dataset("ag_news", split="train", revision="main")
except Exception:
try:
return load_dataset("ag_news", split="train")
except Exception as e:
raise RuntimeError(f"Dataset failed to load: {e}")
def load_agnews_safe_test():
try:
return load_dataset("ag_news", split="test", revision="main")
except Exception:
try:
return load_dataset("ag_news", split="test")
except Exception as e:
raise RuntimeError(f"Dataset failed to load: {e}")
# -------------------------
# Train / Continual Train
# -------------------------
def train_model(epochs=5, continual=False, progress=gr.Progress()):
global model, vectorizer
progress(0.05, desc="Loading dataset...")
try:
train_data = load_agnews_safe()
test_data = load_agnews_safe_test()
except Exception as e:
return f"Error loading dataset: {e}"
texts = train_data["text"][:6000]
labels = train_data["label"][:6000]
# Vectorizer
if vectorizer is None or not continual:
vectorizer = TfidfVectorizer(max_features=8000, stop_words="english")
X = vectorizer.fit_transform(texts)
else:
X = vectorizer.transform(texts)
y = torch.tensor(labels)
# Split
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=42
)
X_train = torch.tensor(X_train.toarray(), dtype=torch.float32).to(device)
X_val = torch.tensor(X_val.toarray(), dtype=torch.float32).to(device)
y_train = y_train.to(device)
y_val = y_val.to(device)
# Model
if model is None or not continual:
model = TextNet(X_train.shape[1]).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
history = []
# Training Loop
for epoch in range(epochs):
model.train()
optimizer.zero_grad()
outputs = model(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
preds = outputs.argmax(dim=1)
acc = (preds == y_train).float().mean().item()
# Validation
model.eval()
with torch.no_grad():
val_out = model(X_val)
val_loss = criterion(val_out, y_val).item()
val_acc = (val_out.argmax(dim=1) == y_val).float().mean().item()
history.append(
f"Epoch {epoch+1}/{epochs} | "
f"Loss: {loss.item():.4f} | Acc: {acc:.4f} | "
f"Val Loss: {val_loss:.4f} | Val Acc: {val_acc:.4f}"
)
progress((epoch + 1) / epochs, desc=f"Epoch {epoch+1}")
# Save
os.makedirs(MODEL_DIR, exist_ok=True)
torch.save(model.state_dict(), MODEL_PATH)
joblib.dump(vectorizer, VEC_PATH)
return "\n".join(history)
# -------------------------
# Load model
# -------------------------
def load_model():
global model, vectorizer
if not os.path.exists(MODEL_PATH) or not os.path.exists(VEC_PATH):
return "No saved model found."
vectorizer = joblib.load(VEC_PATH)
model = TextNet(vectorizer.max_features).to(device)
model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
model.eval()
return "Model loaded successfully."
# -------------------------
# Predict
# -------------------------
def predict(text):
if model is None or vectorizer is None:
return "Train or load a model first."
vec = vectorizer.transform([text]).toarray()
x = torch.tensor(vec, dtype=torch.float32).to(device)
with torch.no_grad():
logits = model(x)
pred = logits.argmax(dim=1).item()
return LABELS[pred]
# -------------------------
# Gradio UI
# -------------------------
with gr.Blocks() as demo:
gr.Markdown("# 🧠 Neural Network AI (From Scratch)")
gr.Markdown("Fully custom neural network with continual learning and safe dataset loading.")
with gr.Row():
epochs = gr.Slider(1, 10, value=5, step=1, label="Epochs")
continual = gr.Checkbox(label="Continual Learning")
train_btn = gr.Button("Train / Continue Training")
load_btn = gr.Button("Load Saved Model")
log = gr.Textbox(lines=10, label="Training Log")
text_input = gr.Textbox(lines=4, placeholder="Enter news text...")
output = gr.Textbox(label="Prediction")
train_btn.click(train_model, inputs=[epochs, continual], outputs=log)
load_btn.click(load_model, outputs=log)
text_input.submit(predict, inputs=text_input, outputs=output)
demo.launch()
|