File size: 25,817 Bytes
e847a58
 
 
 
 
 
 
 
 
 
 
a5b84dd
e847a58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b84dd
e847a58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b84dd
e847a58
a5b84dd
cb3e43c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e847a58
 
 
 
 
 
 
 
 
 
 
 
cb3e43c
 
 
e847a58
 
cb3e43c
a5b84dd
 
e847a58
cb3e43c
 
e847a58
a5b84dd
 
 
 
cb3e43c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b84dd
 
 
 
 
 
 
 
 
cb3e43c
a5b84dd
 
 
 
 
 
cb3e43c
 
a5b84dd
 
 
 
cb3e43c
 
 
 
 
e847a58
 
 
cb3e43c
e847a58
 
 
 
a5b84dd
cb3e43c
 
e847a58
 
 
a5b84dd
e847a58
 
a5b84dd
 
 
 
cb3e43c
a5b84dd
 
cb3e43c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e847a58
 
a5b84dd
e847a58
 
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
cb3e43c
 
 
 
 
 
 
a5b84dd
 
cb3e43c
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb3e43c
 
 
 
 
 
 
a5b84dd
 
bd9a05a
a5b84dd
bd9a05a
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb3e43c
a5b84dd
 
 
cb3e43c
a5b84dd
 
cb3e43c
a5b84dd
 
 
 
bd9a05a
a5b84dd
bd9a05a
a5b84dd
cb3e43c
a5b84dd
cb3e43c
 
a5b84dd
cb3e43c
 
a5b84dd
cb3e43c
 
a5b84dd
 
 
 
 
 
cb3e43c
a5b84dd
 
 
cb3e43c
a5b84dd
 
cb3e43c
a5b84dd
 
 
 
cb3e43c
a5b84dd
cb3e43c
a5b84dd
cb3e43c
 
a5b84dd
cb3e43c
a5b84dd
 
 
 
cb3e43c
a5b84dd
cb3e43c
a5b84dd
cb3e43c
 
a5b84dd
cb3e43c
a5b84dd
 
 
 
cb3e43c
a5b84dd
cb3e43c
a5b84dd
cb3e43c
 
 
a5b84dd
 
 
 
 
 
cb3e43c
a5b84dd
cb3e43c
 
a5b84dd
cb3e43c
 
 
e847a58
cb3e43c
e847a58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ISCO-08 hierarchical accuracy measure"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ISCO CSV file downloaded\n",
      "Weighted ISCO hierarchy dictionary created as isco_hierarchy\n",
      "\n",
      "The ISCO-08 Hierarchical Accuracy Measure is an implementation of the measure described in [Functional Annotation of Genes Using Hierarchical Text Categorization](https://www.researchgate.net/publication/44046343_Functional_Annotation_of_Genes_Using_Hierarchical_Text_Categorization) (Kiritchenko, Svetlana and Famili, Fazel. 2005) and adapted for the ISCO-08 classification scheme by the International Labour Organization.\n",
      "\n",
      "The measure rewards more precise classifications that correctly identify an occupation's placement down to the specific Unit group level and applies penalties for misclassifications based on the hierarchical distance between the correct and assigned categories.\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import evaluate\n",
    "\n",
    "ham = evaluate.load(\"/home/dux/workspace/1-IEA_RnD/isco_hierarchical_accuracy\")\n",
    "print(ham.description)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "References: ['1111', '1112', '1113', '1114', '1120']\n",
      "Predictions: ['1111', '1113', '1120', '1211', '2111']\n",
      "Accuracy: 0.2, Hierarchical Precision: 0.5, Hierarchical Recall: 0.7777777777777778, Hierarchical F-measure: 0.6086956521739131\n",
      "{'accuracy': 0.2, 'hierarchical_precision': 0.5, 'hierarchical_recall': 0.7777777777777778, 'hierarchical_fmeasure': 0.6086956521739131}\n"
     ]
    }
   ],
   "source": [
    "references = [\"1111\", \"1112\", \"1113\", \"1114\", \"1120\"]\n",
    "predictions = [\"1111\", \"1113\", \"1120\", \"1211\", \"2111\"]\n",
    "\n",
    "print(f\"References: {references}\")\n",
    "print(f\"Predictions: {predictions}\")\n",
    "print(ham.compute(references=references, predictions=predictions))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TEST CASE #1\n",
      "References: ['1111', '1111', '1111', '1111', '1111', '1111', '1111', '1111', '1111', '1111']\n",
      "Predictions: ['1111', '1112', '1120', '1211', '1311', '2111', '111', '11', '1', '9999']\n",
      "Accuracy: 0.1, Hierarchical Precision: 0.2222222222222222, Hierarchical Recall: 1.0, Hierarchical F-measure: 0.3636363636363636\n",
      "{'accuracy': 0.1, 'hierarchical_precision': 0.2222222222222222, 'hierarchical_recall': 1.0, 'hierarchical_fmeasure': 0.3636363636363636}\n",
      "\n",
      "TEST CASE #2\n",
      "References: ['1111']\n",
      "Predictions: ['1111']\n",
      "Accuracy: 1.0, Hierarchical Precision: 1.0, Hierarchical Recall: 1.0, Hierarchical F-measure: 1.0\n",
      "{'accuracy': 1.0, 'hierarchical_precision': 1.0, 'hierarchical_recall': 1.0, 'hierarchical_fmeasure': 1.0}\n",
      "\n",
      "TEST CASE #3\n",
      "References: ['1111']\n",
      "Predictions: ['1112']\n",
      "Accuracy: 0.0, Hierarchical Precision: 0.75, Hierarchical Recall: 0.75, Hierarchical F-measure: 0.75\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 0.75, 'hierarchical_recall': 0.75, 'hierarchical_fmeasure': 0.75}\n",
      "\n",
      "TEST CASE #4\n",
      "References: ['1111']\n",
      "Predictions: ['1120']\n",
      "Accuracy: 0.0, Hierarchical Precision: 0.5, Hierarchical Recall: 0.5, Hierarchical F-measure: 0.5\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 0.5, 'hierarchical_recall': 0.5, 'hierarchical_fmeasure': 0.5}\n",
      "\n",
      "TEST CASE #5\n",
      "References: ['1111']\n",
      "Predictions: ['1211']\n",
      "Accuracy: 0.0, Hierarchical Precision: 0.25, Hierarchical Recall: 0.25, Hierarchical F-measure: 0.25\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 0.25, 'hierarchical_recall': 0.25, 'hierarchical_fmeasure': 0.25}\n",
      "\n",
      "TEST CASE #6\n",
      "References: ['1111']\n",
      "Predictions: ['1311']\n",
      "Accuracy: 0.0, Hierarchical Precision: 0.25, Hierarchical Recall: 0.25, Hierarchical F-measure: 0.25\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 0.25, 'hierarchical_recall': 0.25, 'hierarchical_fmeasure': 0.25}\n",
      "\n",
      "TEST CASE #7\n",
      "References: ['1111']\n",
      "Predictions: ['2111']\n",
      "Accuracy: 0.0, Hierarchical Precision: 0.0, Hierarchical Recall: 0.0, Hierarchical F-measure: 0\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 0.0, 'hierarchical_recall': 0.0, 'hierarchical_fmeasure': 0}\n",
      "\n",
      "TEST CASE #8\n",
      "References: ['1111']\n",
      "Predictions: ['111']\n",
      "Accuracy: 0.0, Hierarchical Precision: 1.0, Hierarchical Recall: 0.25, Hierarchical F-measure: 0.4\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 1.0, 'hierarchical_recall': 0.25, 'hierarchical_fmeasure': 0.4}\n",
      "\n",
      "TEST CASE #9\n",
      "References: ['1111']\n",
      "Predictions: ['11']\n",
      "Accuracy: 0.0, Hierarchical Precision: 1.0, Hierarchical Recall: 0.25, Hierarchical F-measure: 0.4\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 1.0, 'hierarchical_recall': 0.25, 'hierarchical_fmeasure': 0.4}\n",
      "\n",
      "TEST CASE #10\n",
      "References: ['1111']\n",
      "Predictions: ['1']\n",
      "Accuracy: 0.0, Hierarchical Precision: 1.0, Hierarchical Recall: 0.25, Hierarchical F-measure: 0.4\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 1.0, 'hierarchical_recall': 0.25, 'hierarchical_fmeasure': 0.4}\n",
      "\n",
      "TEST CASE #11\n",
      "References: ['1111']\n",
      "Predictions: ['9999']\n",
      "Accuracy: 0.0, Hierarchical Precision: 0.0, Hierarchical Recall: 0.0, Hierarchical F-measure: 0\n",
      "{'accuracy': 0.0, 'hierarchical_precision': 0.0, 'hierarchical_recall': 0.0, 'hierarchical_fmeasure': 0}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Compute all test cases and print the results\n",
    "from tests import test_cases\n",
    "\n",
    "test_number = 1\n",
    "\n",
    "for test_case in test_cases:\n",
    "    references = test_case[\"references\"]\n",
    "    predictions = test_case[\"predictions\"]\n",
    "    print(f\"TEST CASE #{test_number}\")\n",
    "    print(f\"References: {references}\")\n",
    "    print(f\"Predictions: {predictions}\")\n",
    "    print(ham.compute(references=references, predictions=predictions))\n",
    "    print()\n",
    "    test_number += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Model evaluation using the test split of the dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datasets import load_dataset, get_dataset_config_names, get_dataset_infos, get_dataset_split_names\n",
    "\n",
    "dataset = load_dataset(\"ICILS/multilingual_parental_occupations\", \"ilo\")\n",
    "dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4634a4a344384ef28d182adeea1f5afc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading builder script:   0%|          | 0.00/13.4k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ISCO CSV file downloaded\n",
      "Weighted ISCO hierarchy dictionary created as isco_hierarchy\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from datasets import load_dataset\n",
    "from transformers import pipeline\n",
    "import evaluate\n",
    "import json\n",
    "\n",
    "# Ensure that the HF_TOKEN environment variable is set\n",
    "hf_token = os.getenv(\"HF_TOKEN\")\n",
    "if hf_token is None:\n",
    "    raise ValueError(\"HF_TOKEN environment variable is not set.\")\n",
    "\n",
    "test_split = load_dataset(\"ICILS/multilingual_parental_occupations\", \"icils\", split=\"test\", token=hf_token)\n",
    "validation_split = load_dataset(\"ICILS/multilingual_parental_occupations\", \"icils\", split=\"validation\", token=hf_token)\n",
    "\n",
    "# Load the dataset\n",
    "test_data_subset = (\n",
    "   test_split.shuffle(seed=42).select(range(100))\n",
    ")\n",
    "\n",
    "# Initialize the pipeline\n",
    "model = \"danieldux/XLM-R-ISCO-v2\" # ICILS/XLM-R-ISCO\n",
    "pipe = pipeline(\"text-classification\", model=model, token=hf_token)\n",
    "\n",
    "# Initialize the hierarchical accuracy measure\n",
    "hierarchical_accuracy = evaluate.load(\"danieldux/isco_hierarchical_accuracy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['IDSTUD', 'JOB_DUTIES', 'ISCO', 'ISCO_REL', 'ISCO_TITLE', 'ISCO_CODE_TITLE', 'COUNTRY', 'LANGUAGE'],\n",
       "    num_rows: 100\n",
       "})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_data_subset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-03-31--01:29\n",
      "Evaluation results saved to test_split_results-2024-03-31--01:29.json\n"
     ]
    }
   ],
   "source": [
    "import datetime\n",
    "\n",
    "stamp = datetime.datetime.now().strftime(\"%Y-%m-%d--%H:%M\")\n",
    "print(stamp)\n",
    "\n",
    "# Evaluate the model\n",
    "predictions = []\n",
    "references = []\n",
    "for example in test_data_subset:\n",
    "\n",
    "    # Predict\n",
    "    prediction = pipe(\n",
    "        example[\"JOB_DUTIES\"]\n",
    "    )  # Use the key \"JOB_DUTIES\" for the text data\n",
    "    # predicted_label = extract_isco_code(prediction[0][\"label\"])\n",
    "    predicted_label = prediction[0][\"label\"]\n",
    "    predictions.append(predicted_label)\n",
    "\n",
    "    # Reference\n",
    "    reference_label = example[\"ISCO\"]  # Use the key \"ISCO\" for the ISCO code\n",
    "    references.append(reference_label)\n",
    "\n",
    "# Compute the hierarchical accuracy\n",
    "test_results = hierarchical_accuracy.compute(predictions=predictions, references=references)\n",
    "\n",
    "# Save the results to a JSON file\n",
    "with open(f\"test_split_results-{stamp}.json\", \"w\") as f:\n",
    "    json.dump(test_results, f)\n",
    "\n",
    "print(f\"Evaluation results saved to test_split_results-{stamp}.json\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'accuracy': 0.82,\n",
       " 'hierarchical_precision': 0.9090909090909091,\n",
       " 'hierarchical_recall': 0.8839779005524862,\n",
       " 'hierarchical_fmeasure': 0.8963585434173669}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.8523316062176166, Hierarchical Precision: 0.9711751662971175, Hierarchical Recall: 0.9733333333333334, Hierarchical F-measure: 0.9722530521642619\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_376175/1380879571.py:30: FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.\n",
      "  results_df = pd.concat(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.8549323017408124, Hierarchical Precision: 0.9425981873111783, Hierarchical Recall: 0.96, Hierarchical F-measure: 0.9512195121951218\n",
      "Accuracy: 0.817351598173516, Hierarchical Precision: 0.9076305220883534, Hierarchical Recall: 0.9377593360995851, Hierarchical F-measure: 0.9224489795918367\n",
      "Accuracy: 0.8160919540229885, Hierarchical Precision: 0.9140893470790378, Hierarchical Recall: 0.9204152249134948, Hierarchical F-measure: 0.9172413793103448\n",
      "Accuracy: 0.7801724137931034, Hierarchical Precision: 0.8776978417266187, Hierarchical Recall: 0.9207547169811321, Hierarchical F-measure: 0.8987108655616942\n",
      "Accuracy: 0.8200836820083682, Hierarchical Precision: 0.9007352941176471, Hierarchical Recall: 0.9176029962546817, Hierarchical F-measure: 0.9090909090909092\n",
      "Accuracy: 0.5149253731343284, Hierarchical Precision: 0.7487684729064039, Hierarchical Recall: 0.8, Hierarchical F-measure: 0.7735368956743003\n",
      "Accuracy: 0.9, Hierarchical Precision: 0.9244444444444444, Hierarchical Recall: 0.9285714285714286, Hierarchical F-measure: 0.9265033407572383\n",
      "Accuracy: 0.9030612244897959, Hierarchical Precision: 0.9509803921568627, Hierarchical Recall: 0.9603960396039604, Hierarchical F-measure: 0.9556650246305418\n",
      "Accuracy: 0.7836538461538461, Hierarchical Precision: 0.9047619047619048, Hierarchical Recall: 0.8916967509025271, Hierarchical F-measure: 0.8981818181818182\n",
      "Accuracy: 0.8707865168539326, Hierarchical Precision: 0.9269406392694064, Hierarchical Recall: 0.9441860465116279, Hierarchical F-measure: 0.9354838709677419\n",
      "Accuracy: 0.9230769230769231, Hierarchical Precision: 0.9, Hierarchical Recall: 0.9473684210526315, Hierarchical F-measure: 0.9230769230769231\n",
      "   Language  Accuracy  Hierarchical Precision  Hierarchical Recall  \\\n",
      "0        sv  0.923077                0.900000             0.947368   \n",
      "1        ko  0.870787                0.926941             0.944186   \n",
      "2        pt  0.783654                0.904762             0.891697   \n",
      "3        kk  0.903061                0.950980             0.960396   \n",
      "4        ru  0.900000                0.924444             0.928571   \n",
      "5        de  0.514925                0.748768             0.800000   \n",
      "6        fi  0.820084                0.900735             0.917603   \n",
      "7        da  0.780172                0.877698             0.920755   \n",
      "8        fr  0.816092                0.914089             0.920415   \n",
      "9        it  0.817352                0.907631             0.937759   \n",
      "10       es  0.854932                0.942598             0.960000   \n",
      "11       en  0.852332                0.971175             0.973333   \n",
      "\n",
      "    Hierarchical F1  \n",
      "0          0.923077  \n",
      "1          0.935484  \n",
      "2          0.898182  \n",
      "3          0.955665  \n",
      "4          0.926503  \n",
      "5          0.773537  \n",
      "6          0.909091  \n",
      "7          0.898711  \n",
      "8          0.917241  \n",
      "9          0.922449  \n",
      "10         0.951220  \n",
      "11         0.972253  \n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "test_data_df = test_data.to_pandas()\n",
    "results_df = pd.DataFrame(columns=['Language', 'Accuracy', 'Hierarchical Precision', 'Hierarchical Recall', 'Hierarchical F1'])\n",
    "\n",
    "# Iterate over unique languages\n",
    "for language in test_data_df[\"LANGUAGE\"].unique():\n",
    "    # Filter test data for the current language\n",
    "    test_data_subset = test_data_df[test_data_df[\"LANGUAGE\"] == language]\n",
    "\n",
    "    # Evaluate the model for the current language\n",
    "    predictions = []\n",
    "    references = []\n",
    "    for example in test_data_subset.to_dict(\"records\"):\n",
    "        # Predict\n",
    "        prediction = pipe(example[\"JOB_DUTIES\"])\n",
    "        predicted_label = extract_isco_code(prediction[0][\"label\"])\n",
    "        predictions.append(predicted_label)\n",
    "\n",
    "        # Reference\n",
    "        reference_label = example[\"ISCO\"]\n",
    "        references.append(reference_label)\n",
    "\n",
    "    # Compute the hierarchical accuracy for the current language\n",
    "    test_results = hierarchical_accuracy.compute(\n",
    "        predictions=predictions, references=references\n",
    "    )\n",
    "\n",
    "    # Save the results to a JSON file\n",
    "    results_df = pd.concat(\n",
    "        [\n",
    "            pd.DataFrame(\n",
    "                {\n",
    "                    \"Language\": [language],\n",
    "                    \"Accuracy\": [test_results[\"accuracy\"]],\n",
    "                    \"Hierarchical Precision\": [test_results[\"hierarchical_precision\"]],\n",
    "                    \"Hierarchical Recall\": [test_results[\"hierarchical_recall\"]],\n",
    "                    \"Hierarchical F1\": [test_results[\"hierarchical_fmeasure\"]],\n",
    "                }\n",
    "            ),\n",
    "            results_df,\n",
    "        ],\n",
    "        ignore_index=True\n",
    "    )\n",
    "\n",
    "# Print the evaluation results\n",
    "print(results_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "results_df.to_csv('model_language_results.csv', index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Validation set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.8576800694243564, Hierarchical Precision: 0.9757462686567164, Hierarchical Recall: 0.9812382739212008, Hierarchical F-measure: 0.9784845650140319\n",
      "Evaluation results saved to isco_validation_results.json\n"
     ]
    }
   ],
   "source": [
    "# Evaluate the model\n",
    "predictions = []\n",
    "references = []\n",
    "for example in validation_data:\n",
    "\n",
    "    # Predict\n",
    "    prediction = pipe(\n",
    "        example[\"JOB_DUTIES\"]\n",
    "    )  # Use the key \"JOB_DUTIES\" for the text data\n",
    "    predicted_label = extract_isco_code(prediction[0][\"label\"])\n",
    "    predictions.append(predicted_label)\n",
    "\n",
    "    # Reference\n",
    "    reference_label = example[\"ISCO\"]  # Use the key \"ISCO\" for the ISCO code\n",
    "    references.append(reference_label)\n",
    "\n",
    "# Compute the hierarchical accuracy\n",
    "validation_results = hierarchical_accuracy.compute(predictions=predictions, references=references)\n",
    "\n",
    "# Save the results to a JSON file\n",
    "with open(\"isco_validation_results.json\", \"w\") as f:\n",
    "    json.dump(validation_results, f)\n",
    "\n",
    "print(\"Evaluation results saved to isco_validation_results.json\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inter rater agreement"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## All ICILS 2018 data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# icils_isco_int_ml = \"/datasets/isco-data/processed/2018/icils_2018_isco_ml.parquet\"\n",
    "icils_isco_int_ml = \"gs://isco-data-asia-southeast1/processed/2018/icils_2018_isco_ml.parquet\"\n",
    "\n",
    "icils_df = pd.read_parquet(icils_isco_int_ml)[['JOB', 'DUTIES', 'ISCO', 'ISCO_REL', 'LANGUAGE']]\n",
    "\n",
    "# Create a new pandas dataframe with samples that have ISCO_REL values\n",
    "isco_rel_df = icils_df[icils_df['ISCO'].notna()].copy()\n",
    "\n",
    "# remove rows with None values in ISCO_REL\n",
    "isco_rel_df = isco_rel_df[isco_rel_df['ISCO_REL'].notna()]\n",
    "\n",
    "# Group the DataFrame by LANGUAGE column\n",
    "grouped_df = isco_rel_df.groupby('LANGUAGE')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### By language"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "results_df = pd.DataFrame(columns=['Language', 'Accuracy', 'Hierarchical Precision', 'Hierarchical Recall', 'Hierarchical F1'])\n",
    "\n",
    "# Iterate over each group\n",
    "for language, group in grouped_df:\n",
    "    references = group['ISCO'].tolist()\n",
    "    predictions = group['ISCO_REL'].tolist()\n",
    "    \n",
    "    # Apply the compute function\n",
    "    rel_result = hierarchical_accuracy.compute(references=references, predictions=predictions)\n",
    "    \n",
    "    # Create a new DataFrame with the result for the current group\n",
    "    group_result_df = pd.DataFrame({'Language': [language], 'Accuracy': [rel_result['accuracy']], 'Hierarchical Precision': [rel_result['hierarchical_precision']], 'Hierarchical Recall': [rel_result['hierarchical_recall']], 'Hierarchical F1': [rel_result['hierarchical_fmeasure']]})\n",
    "    \n",
    "    # Concatenate the group_result_df with the results_df\n",
    "    results_df = pd.concat([results_df, group_result_df], ignore_index=True)\n",
    "    \n",
    "    # Print the result\n",
    "    print(f\"Language: {language}\")\n",
    "    # print(f\"References: {references}\")\n",
    "    # print(f\"Predictions: {predictions}\")\n",
    "    print(f\"Result: {rel_result}\")\n",
    "    print()\n",
    "\n",
    "average_accuracy = results_df['Accuracy'].mean()\n",
    "average_hierarchical_precision = results_df['Hierarchical Precision'].mean()\n",
    "average_hierarchical_recall = results_df['Hierarchical Recall'].mean()\n",
    "average_hierarchical_f1 = results_df['Hierarchical F1'].mean()\n",
    "\n",
    "average_row = ['Average', average_accuracy, average_hierarchical_precision, average_hierarchical_recall, average_hierarchical_f1]\n",
    "results_df.loc[len(results_df)] = average_row\n",
    "\n",
    "\n",
    "results_df.to_csv('inter-rater_language_results.csv', index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "test_data_df = test_data.to_pandas()\n",
    "unknown_reliability_samples = test_data_df[test_data_df['ISCO_REL'].isna() | test_data_df['ISCO_REL'].isin([\"9998\", \"9999\"])]\n",
    "\n",
    "# Exclude unknown reliability samples from test_data_df\n",
    "test_split_rel_df = test_data_df[~test_data_df['ISCO_REL'].isna() & ~test_data_df['ISCO_REL'].isin([\"9998\", \"9999\"])]\n",
    "\n",
    "# Group the DataFrame by LANGUAGE column\n",
    "test_split_rel_grouped_df = test_split_rel_df.groupby('LANGUAGE')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Validation data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a dataframe with samples where ISCO and ISCO_REL the same\n",
    "isco_rel_df_same = isco_rel_df[isco_rel_df['ISCO'] == isco_rel_df['ISCO_REL']]\n",
    "\n",
    "isco_rel_df_same"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a dataframe with samples where ISCO and ISCO_REL are different\n",
    "isco_rel_df_diff = isco_rel_df[isco_rel_df['ISCO'] != isco_rel_df['ISCO_REL']]\n",
    "\n",
    "isco_rel_df_diff"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Make a list of all values in ISCO and ISCO_REL columns\n",
    "coder1 = list(isco_rel_df['ISCO'])\n",
    "coder2 = list(isco_rel_df['ISCO_REL'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the hierarchical accuracy\n",
    "reliability_results = hierarchical_accuracy.compute(predictions=coder2, references=coder1)\n",
    "\n",
    "# Save the results to a JSON file\n",
    "with open(\"isco_rel_results.json\", \"w\") as f:\n",
    "    json.dump(reliability_results, f)\n",
    "\n",
    "print(\"Evaluation results saved to isco_rel_results.json\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "autogenstudio",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}