ProfRod100 commited on
Commit
61ef6a8
·
verified ·
1 Parent(s): 81ea397

Upload 4 files

Browse files
Files changed (4) hide show
  1. Final_Project_ML_DL_Sentiment_Amazon.ipynb +522 -0
  2. README.md +53 -12
  3. app.py +33 -0
  4. requirements.txt +10 -0
Final_Project_ML_DL_Sentiment_Amazon.ipynb ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "48470cbd",
6
+ "metadata": {},
7
+ "source": [
8
+ "\n",
9
+ "# Projeto Final – Machine Learning e Deep Learning (PLN: Análise de Sentimentos)\n",
10
+ "\n",
11
+ "**Professor Rodrigo aqui!** \n",
12
+ "Este notebook é o guia didático para o **Projeto Final**. Vamos construir uma solução completa de **Classificação de Sentimentos** usando avaliações da Amazon (**dataset `amazon_polarity` do Hugging Face**), cobrindo todo o pipeline:\n",
13
+ "\n",
14
+ "1. Definição do problema e escolha do dataset \n",
15
+ "2. Coleta/limpeza, preparação e divisão do conjunto de dados \n",
16
+ "3. **Baseline** com *Machine Learning tradicional* (TF-IDF + Regressão Logística) \n",
17
+ "4. Modelo de *Deep Learning* com **LSTM (PyTorch)** \n",
18
+ "5. Avaliação com métricas adequadas (Accuracy, F1, Matriz de Confusão) \n",
19
+ "6. Exportação dos artefatos e **deploy** com **Gradio** (+ passo a passo para publicar no **Hugging Face Spaces**) \n",
20
+ "\n",
21
+ "> **Importante**: Execute célula por célula e leia as explicações. Onde houver blocos \"Experimente\", preencha as suas observações. Esse notebook pode ser entregue como parte dos **entregáveis** do projeto.\n",
22
+ "\n",
23
+ "---\n",
24
+ "\n",
25
+ "## Objetivo Geral\n",
26
+ "Desenvolver uma solução prática de **ML + DL** aplicada a um problema de **PLN** (classificação binária de sentimento), integrando desde a preparação até o deploy em ambiente público gratuito.\n",
27
+ "\n",
28
+ "## Entregáveis\n",
29
+ "- Notebook **.ipynb** com comentários e resultados \n",
30
+ "- **README.md** do projeto (modelo fornecido) \n",
31
+ "- Deploy funcional com **Gradio** (arquivos `app.py` e `requirements.txt` prontos) \n",
32
+ "- Relatório (5–8 páginas) — usar o modelo do README como base\n",
33
+ "\n",
34
+ "---\n",
35
+ "\n",
36
+ "> **Dica para execução no Google Colab**: ative GPU (Menu: Runtime → Change runtime type → **GPU**).\n"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "execution_count": null,
42
+ "id": "f8e7be1b",
43
+ "metadata": {},
44
+ "outputs": [],
45
+ "source": [
46
+ "\n",
47
+ "# @title Instalação de dependências (Colab)\n",
48
+ "# Se estiver no Colab, descomente as linhas abaixo para instalar.\n",
49
+ "# Em ambiente local com venv, rode `pip install -r requirements.txt`.\n",
50
+ "\n",
51
+ "# !pip install -q datasets==3.0.1 scikit-learn==1.5.2 matplotlib==3.9.2 torch==2.4.1 \\\n",
52
+ "# pandas==2.2.2 numpy==2.1.3 gradio==5.7.1 tqdm==4.66.5\n",
53
+ "\n",
54
+ "print(\"✅ Ambiente pronto (ajuste as instalações se necessário).\")\n"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": null,
60
+ "id": "99d5bff0",
61
+ "metadata": {},
62
+ "outputs": [],
63
+ "source": [
64
+ "\n",
65
+ "# @title Importações centrais\n",
66
+ "import pandas as pd\n",
67
+ "import numpy as np\n",
68
+ "import matplotlib.pyplot as plt\n",
69
+ "from tqdm import tqdm\n",
70
+ "from datasets import load_dataset\n",
71
+ "\n",
72
+ "from sklearn.model_selection import train_test_split\n",
73
+ "from sklearn.feature_extraction.text import TfidfVectorizer\n",
74
+ "from sklearn.linear_model import LogisticRegression\n",
75
+ "from sklearn.ensemble import RandomForestClassifier\n",
76
+ "from sklearn.pipeline import Pipeline\n",
77
+ "from sklearn.metrics import accuracy_score, f1_score, confusion_matrix, classification_report\n",
78
+ "import joblib\n",
79
+ "import os\n",
80
+ "import torch\n",
81
+ "import torch.nn as nn\n",
82
+ "from torch.utils.data import Dataset, DataLoader\n",
83
+ "\n",
84
+ "SEED = 42\n",
85
+ "np.random.seed(SEED)\n",
86
+ "torch.manual_seed(SEED)\n",
87
+ "print(\"✅ Imports OK\")\n"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "markdown",
92
+ "id": "dde7d907",
93
+ "metadata": {},
94
+ "source": [
95
+ "\n",
96
+ "## 1) Definição do Problema\n",
97
+ "\n",
98
+ "**Tarefa**: Classificar avaliações de produtos como **positivas (1)** ou **negativas (-1)**. \n",
99
+ "**Dataset**: `amazon_polarity` (Hugging Face Datasets). \n",
100
+ "**Justificativa**: análise de sentimentos é amplamente usada em e-commerce e suporte a decisões.\n",
101
+ "\n",
102
+ "> **Critérios de avaliação**: accuracy, F1, matriz de confusão; comparação entre baseline (ML) e LSTM (DL).\n"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": null,
108
+ "id": "4b875e79",
109
+ "metadata": {},
110
+ "outputs": [],
111
+ "source": [
112
+ "\n",
113
+ "# @title Coleta e preparação dos dados (amostragem para execução rápida)\n",
114
+ "# Carrega partições 'train' e 'test' do dataset amazon_polarity\n",
115
+ "ds_train = load_dataset(\"amazon_polarity\", split=\"train\")\n",
116
+ "ds_test = load_dataset(\"amazon_polarity\", split=\"test\")\n",
117
+ "\n",
118
+ "# Convertendo para DataFrame\n",
119
+ "df_train = pd.DataFrame({\"text\": ds_train[\"content\"], \"label\": ds_train[\"label\"]})\n",
120
+ "df_test = pd.DataFrame({\"text\": ds_test[\"content\"], \"label\": ds_test[\"label\"]})\n",
121
+ "\n",
122
+ "# O dataset possui rótulos {0,1}; vamos mapeá-los para {-1, +1} opcionalmente para leitura humana\n",
123
+ "label_map = {0:0, 1:1} # manter 0/1 para facilitar as métricas de sklearn\n",
124
+ "df_train[\"label\"] = df_train[\"label\"].map(label_map)\n",
125
+ "df_test[\"label\"] = df_test[\"label\"].map(label_map)\n",
126
+ "\n",
127
+ "# Amostragem para acelerar (ajuste conforme sua GPU/tempo):\n",
128
+ "N_TRAIN = 12000 # experimente 50k+ com GPU boa\n",
129
+ "N_TEST = 6000\n",
130
+ "df_train = df_train.sample(n=N_TRAIN, random_state=SEED).reset_index(drop=True)\n",
131
+ "df_test = df_test.sample(n=N_TEST, random_state=SEED).reset_index(drop=True)\n",
132
+ "\n",
133
+ "# Split treino/val\n",
134
+ "train_text, val_text, train_y, val_y = train_test_split(\n",
135
+ " df_train[\"text\"].values, df_train[\"label\"].values, test_size=0.2, random_state=SEED, stratify=df_train[\"label\"].values\n",
136
+ ")\n",
137
+ "\n",
138
+ "print(\"Tamanhos: \", len(train_text), len(val_text), len(df_test))\n",
139
+ "df_train.head()\n"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "markdown",
144
+ "id": "ed2e0c79",
145
+ "metadata": {},
146
+ "source": [
147
+ "\n",
148
+ "## 2) Baseline com Machine Learning Tradicional\n",
149
+ "\n",
150
+ "Vamos iniciar com um pipeline simples: **TF-IDF** para vetorização + **Regressão Logística**. \n",
151
+ "Depois, comparamos com um **Random Forest** para observar diferenças.\n"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "execution_count": null,
157
+ "id": "d5d7ba98",
158
+ "metadata": {},
159
+ "outputs": [],
160
+ "source": [
161
+ "\n",
162
+ "# @title Treino e avaliação: TF-IDF + Regressão Logística\n",
163
+ "baseline_pipe = Pipeline([\n",
164
+ " (\"tfidf\", TfidfVectorizer(max_features=40000, ngram_range=(1,2))),\n",
165
+ " (\"clf\", LogisticRegression(max_iter=1000, n_jobs=None))\n",
166
+ "])\n",
167
+ "\n",
168
+ "baseline_pipe.fit(train_text, train_y)\n",
169
+ "\n",
170
+ "val_pred = baseline_pipe.predict(val_text)\n",
171
+ "test_pred = baseline_pipe.predict(df_test[\"text\"].values)\n",
172
+ "\n",
173
+ "print(\"Val Accuracy:\", accuracy_score(val_y, val_pred))\n",
174
+ "print(\"Val F1:\", f1_score(val_y, val_pred, average=\"weighted\"))\n",
175
+ "print(\"\\nTest Accuracy:\", accuracy_score(df_test[\"label\"].values, test_pred))\n",
176
+ "print(\"Test F1:\", f1_score(df_test[\"label\"].values, test_pred, average=\"weighted\"))\n",
177
+ "\n",
178
+ "# Matriz de confusão (teste)\n",
179
+ "cm = confusion_matrix(df_test[\"label\"].values, test_pred)\n",
180
+ "plt.figure()\n",
181
+ "plt.imshow(cm, cmap='Blues')\n",
182
+ "plt.title(\"Matriz de Confusão - Baseline (Teste)\")\n",
183
+ "plt.xlabel(\"Predito\")\n",
184
+ "plt.ylabel(\"Verdadeiro\")\n",
185
+ "for i in range(cm.shape[0]):\n",
186
+ " for j in range(cm.shape[1]):\n",
187
+ " plt.text(j, i, cm[i, j], ha=\"center\", va=\"center\")\n",
188
+ "plt.show()\n",
189
+ "\n",
190
+ "print(\"\\nRelatório de Classificação (Teste):\\n\")\n",
191
+ "print(classification_report(df_test[\"label\"].values, test_pred))\n"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": null,
197
+ "id": "fbdd4c7a",
198
+ "metadata": {},
199
+ "outputs": [],
200
+ "source": [
201
+ "\n",
202
+ "# @title Comparativo rápido: TF-IDF + RandomForest\n",
203
+ "rf_pipe = Pipeline([\n",
204
+ " (\"tfidf\", TfidfVectorizer(max_features=30000, ngram_range=(1,1))),\n",
205
+ " (\"rf\", RandomForestClassifier(n_estimators=200, random_state=SEED, n_jobs=-1))\n",
206
+ "])\n",
207
+ "\n",
208
+ "rf_pipe.fit(train_text, train_y)\n",
209
+ "rf_val = rf_pipe.predict(val_text)\n",
210
+ "rf_test = rf_pipe.predict(df_test[\"text\"].values)\n",
211
+ "\n",
212
+ "print(\"RF Val Acc:\", accuracy_score(val_y, rf_val), \" | Val F1:\", f1_score(val_y, rf_val, average=\"weighted\"))\n",
213
+ "print(\"RF Test Acc:\", accuracy_score(df_test[\"label\"].values, rf_test), \" | Test F1:\", f1_score(df_test[\"label\"].values, rf_test, average=\"weighted\"))\n"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "id": "02952330",
219
+ "metadata": {},
220
+ "source": [
221
+ "\n",
222
+ "> **Experimente:** \n",
223
+ "> - Aumente/diminua `max_features` do TF-IDF. \n",
224
+ "> - Troque Regressão Logística por SVM (`LinearSVC`). \n",
225
+ "> - Compare overfitting entre ML tradicional e DL. \n",
226
+ ">\n",
227
+ "> **Suas observações:** *(escreva abaixo)*\n"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "markdown",
232
+ "id": "22ba8a44",
233
+ "metadata": {},
234
+ "source": [
235
+ "\n",
236
+ "## 3) Deep Learning com LSTM (PyTorch)\n",
237
+ "\n",
238
+ "Vamos construir um pipeline enxuto com **tokenização simples**, **vocab** baseado no treino e uma **LSTM** para classificação binária. \n",
239
+ "> Para resultados de SOTA, considere **transformers** (BERT, DistilBERT). Aqui focamos nos fundamentos.\n"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": null,
245
+ "id": "3b9994fb",
246
+ "metadata": {},
247
+ "outputs": [],
248
+ "source": [
249
+ "\n",
250
+ "# @title Tokenização simples + Dataset/Dataloader\n",
251
+ "import re\n",
252
+ "from collections import Counter\n",
253
+ "\n",
254
+ "def basic_tokenize(text):\n",
255
+ " # minuscula, remove caracteres não alfabéticos exceto apóstrofos básicos, separa por espaços\n",
256
+ " text = text.lower()\n",
257
+ " text = re.sub(r\"[^a-z0-9' ]+\", \" \", text)\n",
258
+ " return text.split()\n",
259
+ "\n",
260
+ "# constrói vocabulário a partir do treino\n",
261
+ "MAX_VOCAB = 30000\n",
262
+ "counter = Counter()\n",
263
+ "for t in train_text:\n",
264
+ " counter.update(basic_tokenize(t))\n",
265
+ "most_common = counter.most_common(MAX_VOCAB - 2) # reserva para PAD/UNK\n",
266
+ "itos = [\"<PAD>\", \"<UNK>\"] + [w for w,_ in most_common]\n",
267
+ "stoi = {w:i for i,w in enumerate(itos)}\n",
268
+ "\n",
269
+ "def encode(tokens, max_len=80):\n",
270
+ " ids = [stoi.get(tok, 1) for tok in tokens] # 1 = <UNK>\n",
271
+ " if len(ids) < max_len:\n",
272
+ " ids = ids + [0] * (max_len - len(ids)) # 0 = <PAD>\n",
273
+ " else:\n",
274
+ " ids = ids[:max_len]\n",
275
+ " return np.array(ids, dtype=np.int64)\n",
276
+ "\n",
277
+ "MAX_LEN = 80\n",
278
+ "\n",
279
+ "class SentimentDataset(Dataset):\n",
280
+ " def __init__(self, texts, labels):\n",
281
+ " self.texts = texts\n",
282
+ " self.labels = labels\n",
283
+ " def __len__(self):\n",
284
+ " return len(self.texts)\n",
285
+ " def __getitem__(self, idx):\n",
286
+ " x = encode(basic_tokenize(self.texts[idx]), MAX_LEN)\n",
287
+ " y = int(self.labels[idx])\n",
288
+ " return torch.tensor(x), torch.tensor(y)\n",
289
+ "\n",
290
+ "train_ds = SentimentDataset(train_text, train_y)\n",
291
+ "val_ds = SentimentDataset(val_text, val_y)\n",
292
+ "test_ds = SentimentDataset(df_test[\"text\"].values, df_test[\"label\"].values)\n",
293
+ "\n",
294
+ "BATCH_SIZE = 128\n",
295
+ "train_dl = DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True)\n",
296
+ "val_dl = DataLoader(val_ds, batch_size=BATCH_SIZE)\n",
297
+ "test_dl = DataLoader(test_ds, batch_size=BATCH_SIZE)\n",
298
+ "\n",
299
+ "len(itos), MAX_LEN, BATCH_SIZE\n"
300
+ ]
301
+ },
302
+ {
303
+ "cell_type": "code",
304
+ "execution_count": null,
305
+ "id": "71d27538",
306
+ "metadata": {},
307
+ "outputs": [],
308
+ "source": [
309
+ "\n",
310
+ "# @title Modelo LSTM\n",
311
+ "class LSTMClassifier(nn.Module):\n",
312
+ " def __init__(self, vocab_size, embed_dim=128, hidden_dim=128, num_classes=2, num_layers=1, dropout=0.2):\n",
313
+ " super().__init__()\n",
314
+ " self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)\n",
315
+ " self.lstm = nn.LSTM(embed_dim, hidden_dim, num_layers=num_layers, batch_first=True, dropout=dropout if num_layers>1 else 0.0)\n",
316
+ " self.dropout = nn.Dropout(dropout)\n",
317
+ " self.fc = nn.Linear(hidden_dim, num_classes)\n",
318
+ " def forward(self, x):\n",
319
+ " emb = self.embedding(x)\n",
320
+ " out, _ = self.lstm(emb)\n",
321
+ " h = out[:, -1, :]\n",
322
+ " h = self.dropout(h)\n",
323
+ " return self.fc(h)\n",
324
+ "\n",
325
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
326
+ "model = LSTMClassifier(vocab_size=len(itos)).to(device)\n",
327
+ "\n",
328
+ "criterion = nn.CrossEntropyLoss()\n",
329
+ "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n",
330
+ "\n",
331
+ "EPOCHS = 4 # aumente se tiver tempo/GPU\n"
332
+ ]
333
+ },
334
+ {
335
+ "cell_type": "code",
336
+ "execution_count": null,
337
+ "id": "c639c797",
338
+ "metadata": {},
339
+ "outputs": [],
340
+ "source": [
341
+ "\n",
342
+ "# @title Treino simples + validação\n",
343
+ "def evaluate(model, loader):\n",
344
+ " model.eval()\n",
345
+ " ys, ps = [], []\n",
346
+ " with torch.no_grad():\n",
347
+ " for xb, yb in loader:\n",
348
+ " xb, yb = xb.to(device), yb.to(device)\n",
349
+ " logits = model(xb)\n",
350
+ " pred = torch.argmax(logits, dim=1)\n",
351
+ " ys.append(yb.cpu().numpy())\n",
352
+ " ps.append(pred.cpu().numpy())\n",
353
+ " ys = np.concatenate(ys)\n",
354
+ " ps = np.concatenate(ps)\n",
355
+ " return accuracy_score(ys, ps), f1_score(ys, ps, average=\"weighted\")\n",
356
+ "\n",
357
+ "best_val = 0.0\n",
358
+ "for epoch in range(1, EPOCHS+1):\n",
359
+ " model.train()\n",
360
+ " total_loss = 0.0\n",
361
+ " for xb, yb in tqdm(train_dl, desc=f\"Epoch {epoch}/{EPOCHS}\"):\n",
362
+ " xb, yb = xb.to(device), yb.to(device)\n",
363
+ " optimizer.zero_grad()\n",
364
+ " logits = model(xb)\n",
365
+ " loss = criterion(logits, yb)\n",
366
+ " loss.backward()\n",
367
+ " optimizer.step()\n",
368
+ " total_loss += loss.item()\n",
369
+ " val_acc, val_f1 = evaluate(model, val_dl)\n",
370
+ " print(f\"Epoch {epoch} | Loss: {total_loss/len(train_dl):.4f} | Val Acc: {val_acc:.4f} | Val F1: {val_f1:.4f}\")\n",
371
+ " if val_acc > best_val:\n",
372
+ " best_val = val_acc\n",
373
+ " torch.save({\n",
374
+ " \"model_state\": model.state_dict(),\n",
375
+ " \"vocab\": itos,\n",
376
+ " \"max_len\": MAX_LEN\n",
377
+ " }, \"lstm_sentiment_best.pt\")\n",
378
+ " print(\"✅ Modelo LSTM salvo: lstm_sentiment_best.pt\")\n"
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "code",
383
+ "execution_count": null,
384
+ "id": "b44eb2e8",
385
+ "metadata": {},
386
+ "outputs": [],
387
+ "source": [
388
+ "\n",
389
+ "# @title Avaliação no conjunto de teste\n",
390
+ "# Carrega melhor checkpoint (se houver)\n",
391
+ "if os.path.exists(\"lstm_sentiment_best.pt\"):\n",
392
+ " ckpt = torch.load(\"lstm_sentiment_best.pt\", map_location=device)\n",
393
+ " model.load_state_dict(ckpt[\"model_state\"])\n",
394
+ "\n",
395
+ "test_acc, test_f1 = evaluate(model, test_dl)\n",
396
+ "print(\"LSTM Test Accuracy:\", test_acc)\n",
397
+ "print(\"LSTM Test F1:\", test_f1)\n"
398
+ ]
399
+ },
400
+ {
401
+ "cell_type": "markdown",
402
+ "id": "7b866b6f",
403
+ "metadata": {},
404
+ "source": [
405
+ "\n",
406
+ "## 4) Exportação de Artefatos\n",
407
+ "\n",
408
+ "Vamos salvar:\n",
409
+ "- Pipeline TF-IDF + Regressão Logística (`baseline_pipe.pkl`)\n",
410
+ "- Modelo LSTM (`lstm_sentiment_best.pt`) + vocabulário embutido no checkpoint\n",
411
+ "\n",
412
+ "Esses arquivos serão usados no **deploy** (Gradio + Hugging Face Spaces).\n"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "execution_count": null,
418
+ "id": "ccf5e781",
419
+ "metadata": {},
420
+ "outputs": [],
421
+ "source": [
422
+ "\n",
423
+ "# @title Salvar pipeline baseline\n",
424
+ "joblib.dump(baseline_pipe, \"baseline_pipe.pkl\")\n",
425
+ "print(\"✅ Pipeline baseline salvo como baseline_pipe.pkl\")\n",
426
+ "\n",
427
+ "# O LSTM já foi salvo como lstm_sentiment_best.pt durante o treino (melhor época).\n",
428
+ "print(\"✅ Verifique se lstm_sentiment_best.pt foi gerado na etapa anterior.\")\n"
429
+ ]
430
+ },
431
+ {
432
+ "cell_type": "markdown",
433
+ "id": "f5d63f93",
434
+ "metadata": {},
435
+ "source": [
436
+ "\n",
437
+ "## 5) Demonstração com Gradio (local)\n",
438
+ "\n",
439
+ "Abaixo, uma interface mínima com **Gradio**. Para publicar no **Hugging Face Spaces**, usaremos o arquivo `app.py` (já pronto e salvo ao lado deste notebook).\n"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "code",
444
+ "execution_count": null,
445
+ "id": "7efbc3cc",
446
+ "metadata": {},
447
+ "outputs": [],
448
+ "source": [
449
+ "\n",
450
+ "# @title Demo local (opcional)\n",
451
+ "# Para executar no notebook, descomente:\n",
452
+ "# import gradio as gr\n",
453
+ "# import torch\n",
454
+ "# import joblib\n",
455
+ "\n",
456
+ "# # Carregar baseline (mais leve para demo)\n",
457
+ "# baseline = joblib.load(\"baseline_pipe.pkl\")\n",
458
+ "\n",
459
+ "# def predict_sentiment(text):\n",
460
+ "# proba = baseline.predict_proba([text])[0]\n",
461
+ "# pred = int(np.argmax(proba))\n",
462
+ "# label = \"positivo\" if pred == 1 else \"negativo\"\n",
463
+ "# conf = float(np.max(proba))\n",
464
+ "# return {\"predição\": label, \"confiança\": conf}\n",
465
+ "\n",
466
+ "# demo = gr.Interface(fn=predict_sentiment,\n",
467
+ "# inputs=gr.Textbox(label=\"Digite uma avaliação\"),\n",
468
+ "# outputs=gr.JSON(label=\"Resultado\"),\n",
469
+ "# title=\"Análise de Sentimentos (Baseline)\")\n",
470
+ "# demo.launch()\n",
471
+ "print(\"ℹ️ Use o app.py para deploy no Hugging Face Spaces.\")\n"
472
+ ]
473
+ },
474
+ {
475
+ "cell_type": "markdown",
476
+ "id": "c8454fcd",
477
+ "metadata": {},
478
+ "source": [
479
+ "\n",
480
+ "## 6) Conclusões & Próximos Passos\n",
481
+ "\n",
482
+ "- Comparamos **ML tradicional** (TF-IDF + LR/RF) com uma **LSTM** simples. \n",
483
+ "- Para melhores resultados, considere **transformers** (ex.: `distilbert-base-uncased` com `transformers`). \n",
484
+ "- Faça *tuning* de hiperparâmetros (LR, batch size, epochs, max_features, max_len). \n",
485
+ "- Documente no **Relatório**: escolhas, resultados, limitações e próximos passos.\n",
486
+ "\n",
487
+ "> **Checklist para o Deploy** \n",
488
+ "> - `baseline_pipe.pkl` e/ou `lstm_sentiment_best.pt` gerados \n",
489
+ "> - `app.py` pronto (fornecido) \n",
490
+ "> - `requirements.txt` pronto (fornecido) \n",
491
+ "> - Criar o **Space** no Hugging Face (template Gradio/Python) e subir os arquivos \n",
492
+ "> - Preencher o `README.md` com prints e explicações\n"
493
+ ]
494
+ },
495
+ {
496
+ "cell_type": "markdown",
497
+ "id": "17df5370",
498
+ "metadata": {},
499
+ "source": [
500
+ "\n",
501
+ "---\n",
502
+ "\n",
503
+ "### 🧪 Experimente (preencha suas anotações abaixo)\n",
504
+ "\n",
505
+ "1. **TF-IDF**: Mude `ngram_range`, `max_features` e compare *accuracy* e *F1* no **val** e **test**. \n",
506
+ "2. **Classificador**: Troque para `LinearSVC` e compare com a Regressão Logística. \n",
507
+ "3. **LSTM**: Aumente `EPOCHS` e `embed_dim` (128→256) e anote mudanças. \n",
508
+ "4. **Limpeza**: Remova *stopwords* no TF-IDF e compare. \n",
509
+ "5. **Amostra**: Compare tempos e métricas usando `N_TRAIN`=12k vs. 50k+.\n",
510
+ "\n",
511
+ "**Observações do grupo:**\n",
512
+ "\n",
513
+ "- \n",
514
+ "- \n",
515
+ "- \n"
516
+ ]
517
+ }
518
+ ],
519
+ "metadata": {},
520
+ "nbformat": 4,
521
+ "nbformat_minor": 5
522
+ }
README.md CHANGED
@@ -1,14 +1,55 @@
1
- ---
2
- title: Amazon Classific Polarity
3
- emoji: 🌍
4
- colorFrom: purple
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- short_description: Classificar avaliações em P&N ( MODELO PROJETO FINAL )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+
2
+ # Projeto Final — Análise de Sentimentos (Amazon Polarity)
3
+
4
+ **Curso**: Machine Learning e Deep Learning
5
+ **Data**: 2025-11-12
6
+ **Grupo**: _(preencha com os integrantes)_
7
+
8
+ ## 1. Definição do Problema
9
+ Classificar avaliações de produtos (Amazon) como **positivas** ou **negativas**.
10
+
11
+ **Justificativa**: problema real de PLN, com alto valor prático em e-commerce e suporte a decisões.
12
+
13
+ ## 2. Dataset
14
+ - **Fonte**: [Hugging Face — `amazon_polarity`](https://huggingface.co/datasets/amazon_polarity)
15
+ - **Tamanho**: milhões de exemplos (usamos amostra para execução rápida)
16
+ - **Divisão**: treino/validação/teste
17
+
18
+ ## 3. Metodologia
19
+ - **Pré-processamento**: limpeza básica de texto; TF‑IDF (ML) e tokenização simples (DL)
20
+ - **Modelos**:
21
+ - Baseline: TF‑IDF + Regressão Logística
22
+ - Comparativo: Random Forest
23
+ - Deep Learning: LSTM (PyTorch)
24
+ - **Métricas**: Accuracy, F1 (macro/weighted), Matriz de Confusão
25
+
26
+ ## 4. Resultados (resumo)
27
+ > _Inclua as tabelas e gráficos principais. Compare ML vs. DL e explique as diferenças observadas._
28
+
29
+ ## 5. Deploy (Hugging Face Spaces)
30
+ **Arquivos necessários**:
31
+ - `app.py`
32
+ - `requirements.txt`
33
+ - `baseline_pipe.pkl` (gerado pelo notebook)
34
+
35
+ **Passo a passo**:
36
+ 1. Crie uma conta em https://huggingface.co (ou use a sua).
37
+ 2. Clique em **Create new Space** → **Gradio** → **Python**.
38
+ 3. Faça **Upload** de `app.py`, `requirements.txt` e `baseline_pipe.pkl`.
39
+ 4. Aguarde o build do Space e teste a interface.
40
+ 5. Edite este **README** com prints da interface funcionando e links.
41
+
42
+ ## 6. Conclusões
43
+ - _Resumo dos achados e justificativas técnicas._
44
+ - _Limitações e próximos passos (ex.: transformers, tuning avançado, dados balanceados)._
45
+
46
+ ## 7. Como reproduzir localmente
47
+ ```bash
48
+ python -m venv .venv && source .venv/bin/activate # (Windows: .venv\Scripts\activate)
49
+ pip install -r requirements.txt
50
+ python app.py
51
+ ```
52
+
53
  ---
54
 
55
+ > **Observação**: Este repositório/Space cumpre os **entregáveis**: notebook, deploy funcional e documentação.
app.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import joblib
4
+ import numpy as np
5
+ import os
6
+
7
+ # Carrega o pipeline baseline (TF-IDF + LogisticRegression)
8
+ MODEL_PATH = os.getenv("MODEL_PATH", "baseline_pipe.pkl")
9
+
10
+ if not os.path.exists(MODEL_PATH):
11
+ raise FileNotFoundError(f"Arquivo de modelo não encontrado: {MODEL_PATH}. Faça upload de baseline_pipe.pkl.")
12
+
13
+ baseline = joblib.load(MODEL_PATH)
14
+
15
+ def predict_sentiment(text: str):
16
+ if not text or text.strip() == "":
17
+ return {"predição": "n/a", "confiança": 0.0}
18
+ proba = baseline.predict_proba([text])[0]
19
+ pred = int(np.argmax(proba))
20
+ label = "positivo" if pred == 1 else "negativo"
21
+ conf = float(np.max(proba))
22
+ return {"predição": label, "confiança": conf}
23
+
24
+ demo = gr.Interface(
25
+ fn=predict_sentiment,
26
+ inputs=gr.Textbox(label="Digite uma avaliação de produto"),
27
+ outputs=gr.JSON(label="Resultado"),
28
+ title="Análise de Sentimentos (Amazon Polarity)",
29
+ description="Pipeline TF-IDF + Regressão Logística. Faça upload de baseline_pipe.pkl gerado no notebook."
30
+ )
31
+
32
+ if __name__ == "__main__":
33
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ datasets==3.0.1
3
+ pandas==2.2.2
4
+ numpy==2.1.3
5
+ scikit-learn==1.5.2
6
+ matplotlib==3.9.2
7
+ joblib==1.4.2
8
+ torch==2.4.1
9
+ tqdm==4.66.5
10
+ gradio==5.7.1