Spaces:
Sleeping
Sleeping
Commit ·
5965706
1
Parent(s): 05048a9
ASDFGH
Browse files
app.py
CHANGED
|
@@ -9,6 +9,9 @@ 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"
|
|
@@ -38,22 +41,51 @@ class TextNet(nn.Module):
|
|
| 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 |
try:
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
dataset = load_dataset("ag_news", revision="main")
|
| 51 |
except Exception as e:
|
| 52 |
return f"Error loading dataset: {e}"
|
| 53 |
|
| 54 |
-
texts =
|
| 55 |
-
labels =
|
| 56 |
|
|
|
|
| 57 |
if vectorizer is None or not continual:
|
| 58 |
vectorizer = TfidfVectorizer(max_features=8000, stop_words="english")
|
| 59 |
X = vectorizer.fit_transform(texts)
|
|
@@ -62,6 +94,7 @@ def train_model(epochs=5, continual=False, progress=gr.Progress()):
|
|
| 62 |
|
| 63 |
y = torch.tensor(labels)
|
| 64 |
|
|
|
|
| 65 |
X_train, X_val, y_train, y_val = train_test_split(
|
| 66 |
X, y, test_size=0.2, random_state=42
|
| 67 |
)
|
|
@@ -71,6 +104,7 @@ def train_model(epochs=5, continual=False, progress=gr.Progress()):
|
|
| 71 |
y_train = y_train.to(device)
|
| 72 |
y_val = y_val.to(device)
|
| 73 |
|
|
|
|
| 74 |
if model is None or not continual:
|
| 75 |
model = TextNet(X_train.shape[1]).to(device)
|
| 76 |
|
|
@@ -79,6 +113,7 @@ def train_model(epochs=5, continual=False, progress=gr.Progress()):
|
|
| 79 |
|
| 80 |
history = []
|
| 81 |
|
|
|
|
| 82 |
for epoch in range(epochs):
|
| 83 |
model.train()
|
| 84 |
optimizer.zero_grad()
|
|
@@ -91,6 +126,7 @@ def train_model(epochs=5, continual=False, progress=gr.Progress()):
|
|
| 91 |
preds = outputs.argmax(dim=1)
|
| 92 |
acc = (preds == y_train).float().mean().item()
|
| 93 |
|
|
|
|
| 94 |
model.eval()
|
| 95 |
with torch.no_grad():
|
| 96 |
val_out = model(X_val)
|
|
@@ -105,6 +141,7 @@ def train_model(epochs=5, continual=False, progress=gr.Progress()):
|
|
| 105 |
|
| 106 |
progress((epoch + 1) / epochs, desc=f"Epoch {epoch+1}")
|
| 107 |
|
|
|
|
| 108 |
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 109 |
torch.save(model.state_dict(), MODEL_PATH)
|
| 110 |
joblib.dump(vectorizer, VEC_PATH)
|
|
@@ -150,8 +187,8 @@ def predict(text):
|
|
| 150 |
# Gradio UI
|
| 151 |
# -------------------------
|
| 152 |
with gr.Blocks() as demo:
|
| 153 |
-
gr.Markdown("# 🧠 Neural Network AI (
|
| 154 |
-
gr.Markdown("
|
| 155 |
|
| 156 |
with gr.Row():
|
| 157 |
epochs = gr.Slider(1, 10, value=5, step=1, label="Epochs")
|
|
|
|
| 9 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 10 |
from sklearn.model_selection import train_test_split
|
| 11 |
|
| 12 |
+
# -------------------------
|
| 13 |
+
# Config
|
| 14 |
+
# -------------------------
|
| 15 |
MODEL_DIR = "model"
|
| 16 |
MODEL_PATH = f"{MODEL_DIR}/net.pt"
|
| 17 |
VEC_PATH = f"{MODEL_DIR}/vectorizer.joblib"
|
|
|
|
| 41 |
return self.out(x)
|
| 42 |
|
| 43 |
|
| 44 |
+
# -------------------------
|
| 45 |
+
# Safe Dataset Loader
|
| 46 |
+
# -------------------------
|
| 47 |
+
def load_agnews_safe():
|
| 48 |
+
"""
|
| 49 |
+
Hugging Face Spaces sometimes caches a deleted commit of ag_news.
|
| 50 |
+
This loader forces a fresh revision and retries if needed.
|
| 51 |
+
"""
|
| 52 |
+
try:
|
| 53 |
+
return load_dataset("ag_news", split="train", revision="main")
|
| 54 |
+
except Exception:
|
| 55 |
+
try:
|
| 56 |
+
return load_dataset("ag_news", split="train")
|
| 57 |
+
except Exception as e:
|
| 58 |
+
raise RuntimeError(f"Dataset failed to load: {e}")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_agnews_safe_test():
|
| 62 |
+
try:
|
| 63 |
+
return load_dataset("ag_news", split="test", revision="main")
|
| 64 |
+
except Exception:
|
| 65 |
+
try:
|
| 66 |
+
return load_dataset("ag_news", split="test")
|
| 67 |
+
except Exception as e:
|
| 68 |
+
raise RuntimeError(f"Dataset failed to load: {e}")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
# -------------------------
|
| 72 |
# Train / Continual Train
|
| 73 |
# -------------------------
|
| 74 |
def train_model(epochs=5, continual=False, progress=gr.Progress()):
|
| 75 |
global model, vectorizer
|
| 76 |
|
| 77 |
+
progress(0.05, desc="Loading dataset...")
|
| 78 |
+
|
| 79 |
try:
|
| 80 |
+
train_data = load_agnews_safe()
|
| 81 |
+
test_data = load_agnews_safe_test()
|
|
|
|
| 82 |
except Exception as e:
|
| 83 |
return f"Error loading dataset: {e}"
|
| 84 |
|
| 85 |
+
texts = train_data["text"][:6000]
|
| 86 |
+
labels = train_data["label"][:6000]
|
| 87 |
|
| 88 |
+
# Vectorizer
|
| 89 |
if vectorizer is None or not continual:
|
| 90 |
vectorizer = TfidfVectorizer(max_features=8000, stop_words="english")
|
| 91 |
X = vectorizer.fit_transform(texts)
|
|
|
|
| 94 |
|
| 95 |
y = torch.tensor(labels)
|
| 96 |
|
| 97 |
+
# Split
|
| 98 |
X_train, X_val, y_train, y_val = train_test_split(
|
| 99 |
X, y, test_size=0.2, random_state=42
|
| 100 |
)
|
|
|
|
| 104 |
y_train = y_train.to(device)
|
| 105 |
y_val = y_val.to(device)
|
| 106 |
|
| 107 |
+
# Model
|
| 108 |
if model is None or not continual:
|
| 109 |
model = TextNet(X_train.shape[1]).to(device)
|
| 110 |
|
|
|
|
| 113 |
|
| 114 |
history = []
|
| 115 |
|
| 116 |
+
# Training Loop
|
| 117 |
for epoch in range(epochs):
|
| 118 |
model.train()
|
| 119 |
optimizer.zero_grad()
|
|
|
|
| 126 |
preds = outputs.argmax(dim=1)
|
| 127 |
acc = (preds == y_train).float().mean().item()
|
| 128 |
|
| 129 |
+
# Validation
|
| 130 |
model.eval()
|
| 131 |
with torch.no_grad():
|
| 132 |
val_out = model(X_val)
|
|
|
|
| 141 |
|
| 142 |
progress((epoch + 1) / epochs, desc=f"Epoch {epoch+1}")
|
| 143 |
|
| 144 |
+
# Save
|
| 145 |
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 146 |
torch.save(model.state_dict(), MODEL_PATH)
|
| 147 |
joblib.dump(vectorizer, VEC_PATH)
|
|
|
|
| 187 |
# Gradio UI
|
| 188 |
# -------------------------
|
| 189 |
with gr.Blocks() as demo:
|
| 190 |
+
gr.Markdown("# 🧠 Neural Network AI (From Scratch)")
|
| 191 |
+
gr.Markdown("Fully custom neural network with continual learning and safe dataset loading.")
|
| 192 |
|
| 193 |
with gr.Row():
|
| 194 |
epochs = gr.Slider(1, 10, value=5, step=1, label="Epochs")
|