File size: 45,025 Bytes
e847a58
 
 
 
 
 
 
 
 
 
 
a5b84dd
e847a58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b84dd
e847a58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b84dd
e847a58
a5b84dd
e847a58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b84dd
 
 
 
e847a58
 
 
 
 
 
 
 
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e847a58
 
 
 
 
 
 
 
a5b84dd
e847a58
 
 
 
a5b84dd
e847a58
 
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e847a58
 
a5b84dd
e847a58
 
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd9a05a
a5b84dd
bd9a05a
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd9a05a
a5b84dd
bd9a05a
a5b84dd
 
 
 
 
 
 
 
 
bd9a05a
a5b84dd
bd9a05a
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd9a05a
a5b84dd
bd9a05a
a5b84dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e847a58
a5b84dd
 
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
{
 "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": [
    "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",
    "# Load the dataset\n",
    "test_data_subset = (\n",
    "    load_dataset(\n",
    "        \"ICILS/multilingual_parental_occupations\", split=\"test\", token=hf_token\n",
    "    )\n",
    "    .shuffle(seed=42)\n",
    "    .select(range(100))\n",
    ")\n",
    "test_data = load_dataset(\n",
    "    \"ICILS/multilingual_parental_occupations\", split=\"test\", token=hf_token\n",
    ")\n",
    "\n",
    "validation_data = load_dataset(\n",
    "    \"ICILS/multilingual_parental_occupations\", split=\"validation\", token=hf_token\n",
    ")\n",
    "\n",
    "# Initialize the pipeline\n",
    "pipe = pipeline(\"text-classification\", model=\"ICILS/XLM-R-ISCO\", token=hf_token)\n",
    "\n",
    "# Define the mapping from ISCO_CODE_TITLE to ISCO codes\n",
    "def extract_isco_code(isco_code_title: str):\n",
    "    # ISCO_CODE_TITLE is a string like \"7412 Electrical Mechanics and Fitters\" so we need to extract the first part for the evaluation.\n",
    "    return isco_code_title.split()[0]\n",
    "\n",
    "# Initialize the hierarchical accuracy measure\n",
    "hierarchical_accuracy = evaluate.load(\"danieldux/isco_hierarchical_accuracy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.8611914401388086, Hierarchical Precision: 0.989010989010989, Hierarchical Recall: 0.9836065573770492, Hierarchical F-measure: 0.9863013698630136\n",
      "Evaluation results saved to isco_test_results.json\n"
     ]
    }
   ],
   "source": [
    "# Evaluate the model\n",
    "predictions = []\n",
    "references = []\n",
    "for example in test_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",
    "test_results = hierarchical_accuracy.compute(predictions=predictions, references=references)\n",
    "\n",
    "# Save the results to a JSON file\n",
    "with open(\"isco_test_results.json\", \"w\") as f:\n",
    "    json.dump(test_results, f)\n",
    "\n",
    "print(\"Evaluation results saved to isco_test_results.json\")"
   ]
  },
  {
   "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": "code",
   "execution_count": 70,
   "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": "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('language_results.csv', index=False)"
   ]
  },
  {
   "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\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Giskard model testing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from scipy.special import softmax\n",
    "from datasets import load_dataset\n",
    "from transformers import AutoModelForSequenceClassification, AutoTokenizer\n",
    "\n",
    "from giskard import Dataset, Model, scan, testing, GiskardClient, Suite"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>IDSTUD</th>\n",
       "      <th>JOB_DUTIES</th>\n",
       "      <th>ISCO</th>\n",
       "      <th>ISCO_REL</th>\n",
       "      <th>ISCO_TITLE</th>\n",
       "      <th>ISCO_CODE_TITLE</th>\n",
       "      <th>COUNTRY</th>\n",
       "      <th>LANGUAGE</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>10670109</td>\n",
       "      <td>forรฆldre 1:   Han arbejder som med-chef sammen...</td>\n",
       "      <td>7412</td>\n",
       "      <td>None</td>\n",
       "      <td>Electrical Mechanics and Fitters</td>\n",
       "      <td>7412 Electrical Mechanics and Fitters</td>\n",
       "      <td>DNK</td>\n",
       "      <td>da</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10130106</td>\n",
       "      <td>asistente de parbulo y basica. ayudaba en la e...</td>\n",
       "      <td>5312</td>\n",
       "      <td>5312</td>\n",
       "      <td>Teachers' Aides</td>\n",
       "      <td>5312 Teachers' Aides</td>\n",
       "      <td>CHL</td>\n",
       "      <td>es</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>10740120</td>\n",
       "      <td>trabajaba en el campo como capatas. aveces cui...</td>\n",
       "      <td>6121</td>\n",
       "      <td>None</td>\n",
       "      <td>Livestock and Dairy Producers</td>\n",
       "      <td>6121 Livestock and Dairy Producers</td>\n",
       "      <td>URY</td>\n",
       "      <td>es</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>10170109</td>\n",
       "      <td>gas abastible. vende gas abastible</td>\n",
       "      <td>9621</td>\n",
       "      <td>5243</td>\n",
       "      <td>Messengers, Package Deliverers and Luggage Por...</td>\n",
       "      <td>9621 Messengers, Package Deliverers and Luggag...</td>\n",
       "      <td>CHL</td>\n",
       "      <td>es</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>11480109</td>\n",
       "      <td>jordbruk. sรฅr potatis tar upp potatis plogar h...</td>\n",
       "      <td>6111</td>\n",
       "      <td>6111</td>\n",
       "      <td>Field Crop and Vegetable Growers</td>\n",
       "      <td>6111 Field Crop and Vegetable Growers</td>\n",
       "      <td>FIN</td>\n",
       "      <td>sv</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>495</th>\n",
       "      <td>11780107</td>\n",
       "      <td>acountent mannager|she mannages calls for jobs...</td>\n",
       "      <td>1211</td>\n",
       "      <td>9998</td>\n",
       "      <td>Finance Managers</td>\n",
       "      <td>1211 Finance Managers</td>\n",
       "      <td>AUS</td>\n",
       "      <td>en</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>496</th>\n",
       "      <td>10850104</td>\n",
       "      <td>geometra/muratore. proggetta case e le restaura</td>\n",
       "      <td>3112</td>\n",
       "      <td>3112</td>\n",
       "      <td>Civil Engineering Technicians</td>\n",
       "      <td>3112 Civil Engineering Technicians</td>\n",
       "      <td>ITA</td>\n",
       "      <td>it</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>497</th>\n",
       "      <td>11460111</td>\n",
       "      <td>fa parte della misericordia. Trasporta i malat...</td>\n",
       "      <td>3258</td>\n",
       "      <td>3258</td>\n",
       "      <td>Ambulance Workers</td>\n",
       "      <td>3258 Ambulance Workers</td>\n",
       "      <td>ITA</td>\n",
       "      <td>it</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>498</th>\n",
       "      <td>10340111</td>\n",
       "      <td>์‚ฌํšŒ๋ณต์ง€์‚ฌ. ํšŒ์‚ฌ์—์„œ ๋ณต์ง€์› ๊ด€๋ฆฌ</td>\n",
       "      <td>2635</td>\n",
       "      <td>2635</td>\n",
       "      <td>Social Work and Counselling Professionals</td>\n",
       "      <td>2635 Social Work and Counselling Professionals</td>\n",
       "      <td>KOR</td>\n",
       "      <td>ko</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>499</th>\n",
       "      <td>10370105</td>\n",
       "      <td>์ž์˜์—…. ๊ฐ€๊ฒŒ๋ฅผ ์šด์˜ํ•˜์‹ ๋‹ค.</td>\n",
       "      <td>5221</td>\n",
       "      <td>None</td>\n",
       "      <td>Shopkeepers</td>\n",
       "      <td>5221 Shopkeepers</td>\n",
       "      <td>KOR</td>\n",
       "      <td>ko</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>500 rows ร— 8 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "       IDSTUD                                         JOB_DUTIES  ISCO  \\\n",
       "0    10670109  forรฆldre 1:   Han arbejder som med-chef sammen...  7412   \n",
       "1    10130106  asistente de parbulo y basica. ayudaba en la e...  5312   \n",
       "2    10740120  trabajaba en el campo como capatas. aveces cui...  6121   \n",
       "3    10170109                 gas abastible. vende gas abastible  9621   \n",
       "4    11480109  jordbruk. sรฅr potatis tar upp potatis plogar h...  6111   \n",
       "..        ...                                                ...   ...   \n",
       "495  11780107  acountent mannager|she mannages calls for jobs...  1211   \n",
       "496  10850104    geometra/muratore. proggetta case e le restaura  3112   \n",
       "497  11460111  fa parte della misericordia. Trasporta i malat...  3258   \n",
       "498  10340111                                 ์‚ฌํšŒ๋ณต์ง€์‚ฌ. ํšŒ์‚ฌ์—์„œ ๋ณต์ง€์› ๊ด€๋ฆฌ  2635   \n",
       "499  10370105                                    ์ž์˜์—…. ๊ฐ€๊ฒŒ๋ฅผ ์šด์˜ํ•˜์‹ ๋‹ค.  5221   \n",
       "\n",
       "    ISCO_REL                                         ISCO_TITLE  \\\n",
       "0       None                   Electrical Mechanics and Fitters   \n",
       "1       5312                                    Teachers' Aides   \n",
       "2       None                      Livestock and Dairy Producers   \n",
       "3       5243  Messengers, Package Deliverers and Luggage Por...   \n",
       "4       6111                   Field Crop and Vegetable Growers   \n",
       "..       ...                                                ...   \n",
       "495     9998                                   Finance Managers   \n",
       "496     3112                      Civil Engineering Technicians   \n",
       "497     3258                                  Ambulance Workers   \n",
       "498     2635          Social Work and Counselling Professionals   \n",
       "499     None                                        Shopkeepers   \n",
       "\n",
       "                                       ISCO_CODE_TITLE COUNTRY LANGUAGE  \n",
       "0                7412 Electrical Mechanics and Fitters     DNK       da  \n",
       "1                                 5312 Teachers' Aides     CHL       es  \n",
       "2                   6121 Livestock and Dairy Producers     URY       es  \n",
       "3    9621 Messengers, Package Deliverers and Luggag...     CHL       es  \n",
       "4                6111 Field Crop and Vegetable Growers     FIN       sv  \n",
       "..                                                 ...     ...      ...  \n",
       "495                              1211 Finance Managers     AUS       en  \n",
       "496                 3112 Civil Engineering Technicians     ITA       it  \n",
       "497                             3258 Ambulance Workers     ITA       it  \n",
       "498     2635 Social Work and Counselling Professionals     KOR       ko  \n",
       "499                                   5221 Shopkeepers     KOR       ko  \n",
       "\n",
       "[500 rows x 8 columns]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "MODEL_NAME = \"ICILS/XLM-R-ISCO\"\n",
    "# DATASET_CONFIG = {\"path\": \"tweet_eval\", \"name\": \"sentiment\", \"split\": \"validation\"}\n",
    "TEXT_COLUMN = \"JOB_DUTIES\"\n",
    "TARGET_COLUMN = \"ISCO_CODE_TITLE\"\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)\n",
    "model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)\n",
    "\n",
    "label2id: dict = model.config.label2id\n",
    "id2label: dict = model.config.id2label\n",
    "# LABEL_MAPPING = id2label.items()\n",
    "\n",
    "# raw_data = load_dataset(**DATASET_CONFIG).to_pandas().iloc[:500]\n",
    "raw_data = load_dataset(\"ICILS/multilingual_parental_occupations\", split=\"test\").to_pandas().iloc[:500]\n",
    "# raw_data = raw_data.replace({\"ISCO_CODE_TITLE\": LABEL_MAPPING})\n",
    "raw_data[\"ISCO\"] = raw_data[\"ISCO\"].astype(str)\n",
    "raw_data[\"ISCO_REL\"] = raw_data[\"ISCO_REL\"].astype(str)\n",
    "\n",
    "raw_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-03-15 01:07:06,923 pid:166193 MainThread giskard.datasets.base INFO     Your 'pandas.DataFrame' is successfully wrapped by Giskard's 'Dataset' wrapper class.\n",
      "2024-03-15 01:07:06,925 pid:166193 MainThread giskard.models.automodel INFO     Your 'prediction_function' is successfully wrapped by Giskard's 'PredictionFunctionModel' wrapper class.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/dux/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/giskard/datasets/base/__init__.py:466: UserWarning: The column ISCO is declared as numeric but has 'object' as data type. To avoid potential future issues, make sure to cast this column to the correct data type.\n",
      "  warning(\n"
     ]
    }
   ],
   "source": [
    "giskard_dataset = Dataset(\n",
    "    df=raw_data,  # A pandas.DataFrame that contains the raw data (before all the pre-processing steps) and the actual ground truth variable (target).\n",
    "    target=TARGET_COLUMN,  # Ground truth variable.\n",
    "    name=\"ISCO-08 Parental Occupation Corpus\",  # Optional.\n",
    ")\n",
    "\n",
    "def prediction_function(df: pd.DataFrame) -> np.ndarray:\n",
    "    encoded_input = tokenizer(list(df[TEXT_COLUMN]), padding=True, return_tensors=\"pt\")\n",
    "    output = model(**encoded_input)\n",
    "    return softmax(output[\"logits\"].detach().numpy(), axis=1)\n",
    "\n",
    "\n",
    "giskard_model = Model(\n",
    "    model=prediction_function,  # A prediction function that encapsulates all the data pre-processing steps and that\n",
    "    model_type=\"classification\",  # Either regression, classification or text_generation.\n",
    "    name=\"XLM-R ISCO\",  # Optional\n",
    "    classification_labels=list(label2id.keys()),  # Their order MUST be identical to the prediction_function's\n",
    "    feature_names=[TEXT_COLUMN],  # Default: all columns of your dataset\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-03-15 01:07:10,228 pid:166193 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'JOB_DUTIES': 'object'} to {'JOB_DUTIES': 'object'}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-03-15 01:07:12,838 pid:166193 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (10, 8) executed in 0:00:02.617399\n",
      "2024-03-15 01:07:12,848 pid:166193 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'JOB_DUTIES': 'object'} to {'JOB_DUTIES': 'object'}\n",
      "2024-03-15 01:07:13,007 pid:166193 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (1, 8) executed in 0:00:00.166843\n",
      "2024-03-15 01:07:13,015 pid:166193 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'JOB_DUTIES': 'object'} to {'JOB_DUTIES': 'object'}\n",
      "2024-03-15 01:07:13,017 pid:166193 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (10, 8) executed in 0:00:00.009517\n",
      "2024-03-15 01:07:13,029 pid:166193 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'JOB_DUTIES': 'object'} to {'JOB_DUTIES': 'object'}\n"
     ]
    },
    {
     "ename": "",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n",
      "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n",
      "\u001b[1;31mClick <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. \n",
      "\u001b[1;31mView Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details."
     ]
    }
   ],
   "source": [
    "results = scan(giskard_model, giskard_dataset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'results' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[7], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m display(\u001b[43mresults\u001b[49m)\n\u001b[1;32m      3\u001b[0m \u001b[38;5;66;03m# Save it to a file\u001b[39;00m\n\u001b[1;32m      4\u001b[0m results\u001b[38;5;241m.\u001b[39mto_html(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mscan_report.html\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
      "\u001b[0;31mNameError\u001b[0m: name 'results' is not defined"
     ]
    }
   ],
   "source": [
    "display(results)\n",
    "\n",
    "# Save it to a file\n",
    "results.to_html(\"scan_report.html\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "GiskardError",
     "evalue": "No details or messages available.",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mGiskardError\u001b[0m                              Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[2], line 10\u001b[0m\n\u001b[1;32m      7\u001b[0m project_name \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mxlmr_isco\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m      9\u001b[0m \u001b[38;5;66;03m# Create a giskard client to communicate with Giskard\u001b[39;00m\n\u001b[0;32m---> 10\u001b[0m client \u001b[38;5;241m=\u001b[39m \u001b[43mGiskardClient\u001b[49m\u001b[43m(\u001b[49m\u001b[43murl\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/giskard/client/giskard_client.py:153\u001b[0m, in \u001b[0;36mGiskardClient.__init__\u001b[0;34m(self, url, key, hf_token)\u001b[0m\n\u001b[1;32m    150\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m hf_token:\n\u001b[1;32m    151\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_session\u001b[38;5;241m.\u001b[39mcookies[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mspaces-jwt\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m hf_token\n\u001b[0;32m--> 153\u001b[0m server_settings: ServerInfo \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_server_info\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    155\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m server_settings\u001b[38;5;241m.\u001b[39mserverVersion \u001b[38;5;241m!=\u001b[39m giskard\u001b[38;5;241m.\u001b[39m__version__:\n\u001b[1;32m    156\u001b[0m     warning(\n\u001b[1;32m    157\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mYour giskard client version (\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mgiskard\u001b[38;5;241m.\u001b[39m__version__\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m) does not match the hub version \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    158\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m(\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mserver_settings\u001b[38;5;241m.\u001b[39mserverVersion\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m). \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    159\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPlease upgrade your client to the latest version. \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    160\u001b[0m         \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mpip install \u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgiskard[hub]>=2.0.0b\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m -U\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[1;32m    161\u001b[0m     )\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/giskard/client/giskard_client.py:417\u001b[0m, in \u001b[0;36mGiskardClient.get_server_info\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m    416\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mget_server_info\u001b[39m(\u001b[38;5;28mself\u001b[39m) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m ServerInfo:\n\u001b[0;32m--> 417\u001b[0m     resp \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_session\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43m/public-api/ml-worker-connect\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m    418\u001b[0m     \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m    419\u001b[0m         \u001b[38;5;28;01mreturn\u001b[39;00m ServerInfo\u001b[38;5;241m.\u001b[39mparse_obj(resp\u001b[38;5;241m.\u001b[39mjson())\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/requests/sessions.py:602\u001b[0m, in \u001b[0;36mSession.get\u001b[0;34m(self, url, **kwargs)\u001b[0m\n\u001b[1;32m    594\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124mr\u001b[39m\u001b[38;5;124;03m\"\"\"Sends a GET request. Returns :class:`Response` object.\u001b[39;00m\n\u001b[1;32m    595\u001b[0m \n\u001b[1;32m    596\u001b[0m \u001b[38;5;124;03m:param url: URL for the new :class:`Request` object.\u001b[39;00m\n\u001b[1;32m    597\u001b[0m \u001b[38;5;124;03m:param \\*\\*kwargs: Optional arguments that ``request`` takes.\u001b[39;00m\n\u001b[1;32m    598\u001b[0m \u001b[38;5;124;03m:rtype: requests.Response\u001b[39;00m\n\u001b[1;32m    599\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m    601\u001b[0m kwargs\u001b[38;5;241m.\u001b[39msetdefault(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mallow_redirects\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[0;32m--> 602\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mGET\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43murl\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/requests_toolbelt/sessions.py:76\u001b[0m, in \u001b[0;36mBaseUrlSession.request\u001b[0;34m(self, method, url, *args, **kwargs)\u001b[0m\n\u001b[1;32m     74\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Send the request after generating the complete URL.\"\"\"\u001b[39;00m\n\u001b[1;32m     75\u001b[0m url \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcreate_url(url)\n\u001b[0;32m---> 76\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mBaseUrlSession\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m     77\u001b[0m \u001b[43m    \u001b[49m\u001b[43mmethod\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43murl\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\n\u001b[1;32m     78\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/requests/sessions.py:589\u001b[0m, in \u001b[0;36mSession.request\u001b[0;34m(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)\u001b[0m\n\u001b[1;32m    584\u001b[0m send_kwargs \u001b[38;5;241m=\u001b[39m {\n\u001b[1;32m    585\u001b[0m     \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtimeout\u001b[39m\u001b[38;5;124m\"\u001b[39m: timeout,\n\u001b[1;32m    586\u001b[0m     \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mallow_redirects\u001b[39m\u001b[38;5;124m\"\u001b[39m: allow_redirects,\n\u001b[1;32m    587\u001b[0m }\n\u001b[1;32m    588\u001b[0m send_kwargs\u001b[38;5;241m.\u001b[39mupdate(settings)\n\u001b[0;32m--> 589\u001b[0m resp \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msend\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprep\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43msend_kwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    591\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/requests/sessions.py:703\u001b[0m, in \u001b[0;36mSession.send\u001b[0;34m(self, request, **kwargs)\u001b[0m\n\u001b[1;32m    700\u001b[0m start \u001b[38;5;241m=\u001b[39m preferred_clock()\n\u001b[1;32m    702\u001b[0m \u001b[38;5;66;03m# Send the request\u001b[39;00m\n\u001b[0;32m--> 703\u001b[0m r \u001b[38;5;241m=\u001b[39m \u001b[43madapter\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msend\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    705\u001b[0m \u001b[38;5;66;03m# Total elapsed time of the request (approximately)\u001b[39;00m\n\u001b[1;32m    706\u001b[0m elapsed \u001b[38;5;241m=\u001b[39m preferred_clock() \u001b[38;5;241m-\u001b[39m start\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/requests/adapters.py:538\u001b[0m, in \u001b[0;36mHTTPAdapter.send\u001b[0;34m(self, request, stream, timeout, verify, cert, proxies)\u001b[0m\n\u001b[1;32m    535\u001b[0m     \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m    536\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m\n\u001b[0;32m--> 538\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mbuild_response\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mresp\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m~/miniconda3/envs/autogenstudio/lib/python3.11/site-packages/giskard/client/giskard_client.py:107\u001b[0m, in \u001b[0;36mErrorHandlingAdapter.build_response\u001b[0;34m(self, req, resp)\u001b[0m\n\u001b[1;32m    105\u001b[0m resp \u001b[38;5;241m=\u001b[39m \u001b[38;5;28msuper\u001b[39m(ErrorHandlingAdapter, \u001b[38;5;28mself\u001b[39m)\u001b[38;5;241m.\u001b[39mbuild_response(req, resp)\n\u001b[1;32m    106\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m _get_status(resp) \u001b[38;5;241m>\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m400\u001b[39m:\n\u001b[0;32m--> 107\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m explain_error(resp)\n\u001b[1;32m    109\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp\n",
      "\u001b[0;31mGiskardError\u001b[0m: No details or messages available."
     ]
    }
   ],
   "source": [
    "import giskard\n",
    "from datasets import load_dataset\n",
    "\n",
    "dataset = load_dataset(\"ICILS/multilingual_parental_occupations\", split=\"test\")\n",
    "\n",
    "# Replace this with your own data & model creation.\n",
    "# df = giskard.demo.titanic_df()\n",
    "df = dataset\n",
    "demo_data_preprocessing_function, demo_sklearn_model = giskard.demo.titanic_pipeline()\n",
    "\n",
    "# Wrap your Pandas DataFrame\n",
    "giskard_dataset = giskard.Dataset(df=df,\n",
    "                                  target=\"ISCO_CODE_TITLE\",\n",
    "                                  name=\"ISCO-08 Parental Occupation Corpus\",\n",
    "                                  cat_columns=['LANGUAGE', 'COUNTRY'])\n",
    "\n",
    "# Wrap your model\n",
    "def prediction_function(df):\n",
    "    preprocessed_df = demo_data_preprocessing_function(df)\n",
    "    return demo_sklearn_model.predict_proba(preprocessed_df)\n",
    "\n",
    "giskard_model = giskard.Model(model=prediction_function,\n",
    "                              model_type=\"classification\",\n",
    "                              name=\"Titanic model\",\n",
    "                              classification_labels=demo_sklearn_model.classes_,\n",
    "                              feature_names=['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked'])\n",
    "\n",
    "# Then apply the scan\n",
    "results = giskard.scan(giskard_model, giskard_dataset)\n",
    "\n",
    "\n",
    "# Create a Giskard client\n",
    "client = giskard.GiskardClient(\n",
    "    url=\"https://danieldux-giskard.hf.space\",  # URL of your Giskard instance\n",
    "    key=\"<Generate your API Key on the Giskard Hub settings page first>\")\n",
    "\n",
    "\n",
    "# Upload an automatically created test suite to the current project โœ‰๏ธ\n",
    "results.generate_test_suite(\"Test suite created by scan\").upload(client, \"xlmr_isco\")\n"
   ]
  }
 ],
 "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
}