lucabadiali commited on
Commit
f97ec54
·
1 Parent(s): 8604850

first commit

Browse files
Files changed (4) hide show
  1. nb.ipynb +380 -0
  2. requirements.txt +103 -0
  3. train_labels.txt +0 -0
  4. train_text.txt +0 -0
nb.ipynb ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 3,
6
+ "id": "3a03d7b9",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "data": {
11
+ "text/plain": [
12
+ "device(type='cpu')"
13
+ ]
14
+ },
15
+ "execution_count": 3,
16
+ "metadata": {},
17
+ "output_type": "execute_result"
18
+ }
19
+ ],
20
+ "source": [
21
+ "from transformers import AutoModelForSequenceClassification\n",
22
+ "from transformers import TFAutoModelForSequenceClassification\n",
23
+ "from transformers import AutoTokenizer, RobertaForSequenceClassification\n",
24
+ "import numpy as np\n",
25
+ "from scipy.special import softmax\n",
26
+ "import csv\n",
27
+ "import urllib.request\n",
28
+ "import torch.utils.data as data_utils\n",
29
+ "import torch\n",
30
+ "\n",
31
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
32
+ "device\n"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "execution_count": 2,
38
+ "id": "e50cfece",
39
+ "metadata": {},
40
+ "outputs": [],
41
+ "source": [
42
+ "def preprocess(text):\n",
43
+ " new_text = []\n",
44
+ " for t in text.split(\" \"):\n",
45
+ " t = '@user' if t.startswith('@') and len(t) > 1 else t\n",
46
+ " t = 'http' if t.startswith('http') else t\n",
47
+ " new_text.append(t)\n",
48
+ " return \" \".join(new_text)"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": 4,
54
+ "id": "0b451180",
55
+ "metadata": {},
56
+ "outputs": [
57
+ {
58
+ "data": {
59
+ "text/plain": [
60
+ "['negative', 'neutral', 'positive']"
61
+ ]
62
+ },
63
+ "execution_count": 4,
64
+ "metadata": {},
65
+ "output_type": "execute_result"
66
+ }
67
+ ],
68
+ "source": [
69
+ "task='sentiment'\n",
70
+ "MODEL = f\"cardiffnlp/twitter-roberta-base-{task}\"\n",
71
+ "# download label mapping\n",
72
+ "mapping_link = f\"https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/{task}/mapping.txt\"\n",
73
+ "with urllib.request.urlopen(mapping_link) as f:\n",
74
+ " html = f.read().decode('utf-8').split(\"\\n\")\n",
75
+ " csvreader = csv.reader(html, delimiter='\\t')\n",
76
+ "labels = [row[1] for row in csvreader if len(row) > 1]\n",
77
+ "labels"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "execution_count": 66,
83
+ "id": "ede5d09e",
84
+ "metadata": {},
85
+ "outputs": [
86
+ {
87
+ "name": "stderr",
88
+ "output_type": "stream",
89
+ "text": [
90
+ "Some weights of RobertaForSequenceClassification were not initialized from the model checkpoint at FacebookAI/roberta-base and are newly initialized: ['classifier.dense.bias', 'classifier.dense.weight', 'classifier.out_proj.bias', 'classifier.out_proj.weight']\n",
91
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
92
+ ]
93
+ }
94
+ ],
95
+ "source": [
96
+ "MODEL = \"FacebookAI/roberta-base\"\n",
97
+ "model = RobertaForSequenceClassification.from_pretrained(\n",
98
+ " MODEL, num_labels=3, problem_type=\"multi_label_classification\")\n",
99
+ "tokenizer = AutoTokenizer.from_pretrained(MODEL)"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 92,
105
+ "id": "c4bafe30",
106
+ "metadata": {},
107
+ "outputs": [],
108
+ "source": [
109
+ "train_text_file = \"train_text.txt\"\n",
110
+ "with open(train_text_file, \"r\") as f:\n",
111
+ " texts = f.readlines()\n",
112
+ "\n",
113
+ "train_label_file = \"train_labels.txt\"\n",
114
+ "with open(train_label_file, \"r\") as f:\n",
115
+ " labels = f.readlines()\n",
116
+ "\n",
117
+ "len(texts), len(labels)\n",
118
+ "\n",
119
+ "texts, labels = texts[:100], labels[:100]\n",
120
+ "\n"
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "execution_count": null,
126
+ "id": "87030ba1",
127
+ "metadata": {},
128
+ "outputs": [
129
+ {
130
+ "data": {
131
+ "text/plain": [
132
+ "(2, 100)"
133
+ ]
134
+ },
135
+ "execution_count": 93,
136
+ "metadata": {},
137
+ "output_type": "execute_result"
138
+ }
139
+ ],
140
+ "source": [
141
+ "encoded_inputs = tokenizer([ preprocess(t.strip()) for t in texts], return_tensors='pt', padding=True,\n",
142
+ " truncation=True)\n",
143
+ "labels = [int(labels[i].strip()) for i in range(len(labels))]\n",
144
+ "labels = torch.tensor(labels, dtype=torch.int)\n",
145
+ "len(encoded_inputs), len(labels)"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "execution_count": 94,
151
+ "id": "e9548356",
152
+ "metadata": {},
153
+ "outputs": [],
154
+ "source": [
155
+ "dataset = data_utils.TensorDataset(encoded_inputs[\"input_ids\"], encoded_inputs[\"attention_mask\"], labels)\n",
156
+ "test_dataloader = data_utils.DataLoader(dataset, batch_size=10, shuffle=True)\n",
157
+ "\n"
158
+ ]
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "execution_count": null,
163
+ "id": "2f40f7fd",
164
+ "metadata": {},
165
+ "outputs": [],
166
+ "source": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "execution_count": null,
171
+ "id": "08435697",
172
+ "metadata": {},
173
+ "outputs": [],
174
+ "source": [
175
+ "\n",
176
+ "model = AutoModelForSequenceClassification.from_pretrained(MODEL)\n",
177
+ "tokenizer = AutoTokenizer.from_pretrained(MODEL)\n",
178
+ "text = \"Good night 😊\"\n",
179
+ "text = preprocess(text)\n",
180
+ "encoded_input = tokenizer(text, return_tensors='pt')\n",
181
+ "output = model(**encoded_input)\n",
182
+ "scores = output[0][0].detach().numpy()\n",
183
+ "scores = softmax(scores)\n"
184
+ ]
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "execution_count": 10,
189
+ "id": "cf6dfc8f",
190
+ "metadata": {},
191
+ "outputs": [
192
+ {
193
+ "name": "stdout",
194
+ "output_type": "stream",
195
+ "text": [
196
+ "1) positive 0.8466\n",
197
+ "2) neutral 0.1458\n",
198
+ "3) negative 0.0076\n"
199
+ ]
200
+ }
201
+ ],
202
+ "source": [
203
+ "ranking = np.argsort(scores)\n",
204
+ "ranking = ranking[::-1]\n",
205
+ "for i in range(scores.shape[0]):\n",
206
+ " l = labels[ranking[i]]\n",
207
+ " s = scores[ranking[i]]\n",
208
+ " print(f\"{i+1}) {l} {np.round(float(s), 4)}\")"
209
+ ]
210
+ },
211
+ {
212
+ "cell_type": "markdown",
213
+ "id": "0f25d8f1",
214
+ "metadata": {},
215
+ "source": [
216
+ "### Tentativo di training"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "execution_count": 3,
222
+ "id": "0a6382f4",
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "import numpy as np\n",
227
+ "import evaluate\n",
228
+ "\n",
229
+ "from transformers import AutoTokenizer\n",
230
+ "from transformers import AutoModelForSequenceClassification\n",
231
+ "from transformers import TrainingArguments, Trainer\n",
232
+ "from datasets import load_dataset, concatenate_datasets\n",
233
+ "\n",
234
+ "def tokenize_function(examples):\n",
235
+ " return tokenizer(examples[\"text\"], padding=\"max_length\", truncation=True)\n",
236
+ "\n",
237
+ "def compute_metrics(eval_pred):\n",
238
+ " logits, labels = eval_pred\n",
239
+ " predictions = np.argmax(logits, axis=-1)\n",
240
+ " return metric.compute(predictions=predictions, references=labels, average='macro')\n",
241
+ "\n",
242
+ "\n",
243
+ "dataset = load_dataset('tweet_eval', 'sentiment')\n",
244
+ "\n",
245
+ "\n"
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "execution_count": 5,
251
+ "id": "dafaf26d",
252
+ "metadata": {},
253
+ "outputs": [
254
+ {
255
+ "name": "stderr",
256
+ "output_type": "stream",
257
+ "text": [
258
+ "Map: 100%|██████████| 45615/45615 [00:10<00:00, 4346.61 examples/s]\n",
259
+ "Map: 100%|██████████| 12284/12284 [00:03<00:00, 3758.76 examples/s]\n",
260
+ "Map: 100%|██████████| 2000/2000 [00:00<00:00, 4820.04 examples/s]\n",
261
+ "Some weights of RobertaForSequenceClassification were not initialized from the model checkpoint at cardiffnlp/twitter-roberta-base-sep2022 and are newly initialized: ['classifier.dense.bias', 'classifier.dense.weight', 'classifier.out_proj.bias', 'classifier.out_proj.weight']\n",
262
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
263
+ "/workspaces/MLOPS_Project/Env/lib/python3.12/site-packages/torch/utils/data/dataloader.py:668: UserWarning: 'pin_memory' argument is set as true but no accelerator is found, then device pinned memory won't be used.\n",
264
+ " warnings.warn(warn_msg)\n"
265
+ ]
266
+ },
267
+ {
268
+ "ename": "",
269
+ "evalue": "",
270
+ "output_type": "error",
271
+ "traceback": [
272
+ "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n",
273
+ "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n",
274
+ "\u001b[1;31mClick <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. \n",
275
+ "\u001b[1;31mView Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details."
276
+ ]
277
+ }
278
+ ],
279
+ "source": [
280
+ "MODEL_NAME = 'cardiffnlp/twitter-roberta-base-sep2022' # change to desired model from the hub\n",
281
+ "tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)\n",
282
+ "tokenized_datasets = dataset.map(tokenize_function, batched=True)\n",
283
+ "\n",
284
+ "# augment train set with test set, for downstream apps only - DO NOT EVALUATE ON TEST\n",
285
+ "# tokenized_datasets['train+test'] = concatenate_datasets([tokenized_datasets['train'],\n",
286
+ "# tokenized_datasets['test']])\n",
287
+ "\n",
288
+ "model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3)\n",
289
+ "\n",
290
+ "\n",
291
+ "training_args = TrainingArguments(\n",
292
+ " output_dir=\"test_trainer\",\n",
293
+ " learning_rate=1e-5,\n",
294
+ " per_device_train_batch_size=16, # modern name\n",
295
+ " per_device_eval_batch_size=16, # modern name\n",
296
+ " num_train_epochs=10,\n",
297
+ " weight_decay=0.01,\n",
298
+ " warmup_ratio=0.1,\n",
299
+ "\n",
300
+ " eval_strategy=\"epoch\",\n",
301
+ " logging_strategy=\"epoch\",\n",
302
+ " save_strategy=\"epoch\",\n",
303
+ "\n",
304
+ " load_best_model_at_end=True,\n",
305
+ " metric_for_best_model=\"recall\",\n",
306
+ " greater_is_better=True,\n",
307
+ " report_to=\"none\",\n",
308
+ ")\n",
309
+ "\n",
310
+ "metric = evaluate.load('recall') # default metric for sentiment dataset is recall (macro)\n",
311
+ "\n",
312
+ "trainer = Trainer(\n",
313
+ " model=model,\n",
314
+ " args=training_args,\n",
315
+ " train_dataset=tokenized_datasets['train'],\n",
316
+ " eval_dataset=tokenized_datasets['validation'],\n",
317
+ " compute_metrics=compute_metrics,\n",
318
+ ")\n",
319
+ "\n",
320
+ "trainer.train()\n",
321
+ "\n",
322
+ "trainer.create_model_card()\n",
323
+ "trainer.save_model('saved_model')\n",
324
+ "\n",
325
+ "\n"
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "execution_count": 1,
331
+ "id": "183032a5",
332
+ "metadata": {},
333
+ "outputs": [
334
+ {
335
+ "ename": "NameError",
336
+ "evalue": "name 'torch' is not defined",
337
+ "output_type": "error",
338
+ "traceback": [
339
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
340
+ "\u001b[31mNameError\u001b[39m Traceback (most recent call last)",
341
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[1]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mtorch\u001b[49m.cuda.is_available()\n",
342
+ "\u001b[31mNameError\u001b[39m: name 'torch' is not defined"
343
+ ]
344
+ }
345
+ ],
346
+ "source": [
347
+ "torch.cuda.is_available()\n"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "code",
352
+ "execution_count": null,
353
+ "id": "1246f9c6",
354
+ "metadata": {},
355
+ "outputs": [],
356
+ "source": []
357
+ }
358
+ ],
359
+ "metadata": {
360
+ "kernelspec": {
361
+ "display_name": "Env",
362
+ "language": "python",
363
+ "name": "python3"
364
+ },
365
+ "language_info": {
366
+ "codemirror_mode": {
367
+ "name": "ipython",
368
+ "version": 3
369
+ },
370
+ "file_extension": ".py",
371
+ "mimetype": "text/x-python",
372
+ "name": "python",
373
+ "nbconvert_exporter": "python",
374
+ "pygments_lexer": "ipython3",
375
+ "version": "3.12.1"
376
+ }
377
+ },
378
+ "nbformat": 4,
379
+ "nbformat_minor": 5
380
+ }
requirements.txt ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==1.11.0
2
+ aiohappyeyeballs==2.6.1
3
+ aiohttp==3.13.2
4
+ aiosignal==1.4.0
5
+ anyio==4.11.0
6
+ asttokens==3.0.0
7
+ attrs==25.4.0
8
+ certifi==2025.10.5
9
+ charset-normalizer==3.4.4
10
+ comm==0.2.3
11
+ contourpy==1.3.3
12
+ cycler==0.12.1
13
+ datasets==4.4.1
14
+ debugpy==1.8.17
15
+ decorator==5.2.1
16
+ dill==0.4.0
17
+ evaluate==0.4.6
18
+ executing==2.2.1
19
+ filelock==3.20.0
20
+ fonttools==4.60.1
21
+ frozenlist==1.8.0
22
+ fsspec==2025.10.0
23
+ gluonnlp==0.8.3
24
+ graphviz==0.8.4
25
+ h11==0.16.0
26
+ hf-xet==1.2.0
27
+ httpcore==1.0.9
28
+ httpx==0.28.1
29
+ huggingface-hub==0.36.0
30
+ idna==3.11
31
+ ipykernel==7.1.0
32
+ ipython==9.7.0
33
+ ipython_pygments_lexers==1.1.1
34
+ jedi==0.19.2
35
+ Jinja2==3.1.6
36
+ jupyter_client==8.6.3
37
+ jupyter_core==5.9.1
38
+ kiwisolver==1.4.9
39
+ MarkupSafe==3.0.3
40
+ matplotlib==3.10.7
41
+ matplotlib-inline==0.2.1
42
+ mpmath==1.3.0
43
+ multidict==6.7.0
44
+ multiprocess==0.70.18
45
+ mxnet==1.6.0
46
+ nest-asyncio==1.6.0
47
+ networkx==3.5
48
+ numpy==1.26.4
49
+ nvidia-cublas-cu12==12.8.4.1
50
+ nvidia-cuda-cupti-cu12==12.8.90
51
+ nvidia-cuda-nvrtc-cu12==12.8.93
52
+ nvidia-cuda-runtime-cu12==12.8.90
53
+ nvidia-cudnn-cu12==9.10.2.21
54
+ nvidia-cufft-cu12==11.3.3.83
55
+ nvidia-cufile-cu12==1.13.1.3
56
+ nvidia-curand-cu12==10.3.9.90
57
+ nvidia-cusolver-cu12==11.7.3.90
58
+ nvidia-cusparse-cu12==12.5.8.93
59
+ nvidia-cusparselt-cu12==0.7.1
60
+ nvidia-nccl-cu12==2.27.5
61
+ nvidia-nvjitlink-cu12==12.8.93
62
+ nvidia-nvshmem-cu12==3.3.20
63
+ nvidia-nvtx-cu12==12.8.90
64
+ packaging==25.0
65
+ pandas==2.3.3
66
+ parso==0.8.5
67
+ pexpect==4.9.0
68
+ pillow==12.0.0
69
+ platformdirs==4.5.0
70
+ prompt_toolkit==3.0.52
71
+ propcache==0.4.1
72
+ psutil==7.1.3
73
+ ptyprocess==0.7.0
74
+ pure_eval==0.2.3
75
+ pyarrow==22.0.0
76
+ Pygments==2.19.2
77
+ pyparsing==3.2.5
78
+ python-dateutil==2.9.0.post0
79
+ pytz==2025.2
80
+ PyYAML==6.0.3
81
+ pyzmq==27.1.0
82
+ regex==2025.11.3
83
+ requests==2.32.5
84
+ safetensors==0.6.2
85
+ scipy==1.16.3
86
+ setuptools==80.9.0
87
+ six==1.17.0
88
+ sniffio==1.3.1
89
+ stack-data==0.6.3
90
+ sympy==1.14.0
91
+ tokenizers==0.22.1
92
+ torch==2.9.0
93
+ tornado==6.5.2
94
+ tqdm==4.67.1
95
+ traitlets==5.14.3
96
+ transformers==4.57.1
97
+ triton==3.5.0
98
+ typing_extensions==4.15.0
99
+ tzdata==2025.2
100
+ urllib3==2.5.0
101
+ wcwidth==0.2.14
102
+ xxhash==3.6.0
103
+ yarl==1.22.0
train_labels.txt ADDED
The diff for this file is too large to render. See raw diff
 
train_text.txt ADDED
The diff for this file is too large to render. See raw diff