{ "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": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IDSTUDJOB_DUTIESISCOISCO_RELISCO_TITLEISCO_CODE_TITLECOUNTRYLANGUAGE
010670109forældre 1: Han arbejder som med-chef sammen...7412NoneElectrical Mechanics and Fitters7412 Electrical Mechanics and FittersDNKda
110130106asistente de parbulo y basica. ayudaba en la e...53125312Teachers' Aides5312 Teachers' AidesCHLes
210740120trabajaba en el campo como capatas. aveces cui...6121NoneLivestock and Dairy Producers6121 Livestock and Dairy ProducersURYes
310170109gas abastible. vende gas abastible96215243Messengers, Package Deliverers and Luggage Por...9621 Messengers, Package Deliverers and Luggag...CHLes
411480109jordbruk. sår potatis tar upp potatis plogar h...61116111Field Crop and Vegetable Growers6111 Field Crop and Vegetable GrowersFINsv
...........................
49511780107acountent mannager|she mannages calls for jobs...12119998Finance Managers1211 Finance ManagersAUSen
49610850104geometra/muratore. proggetta case e le restaura31123112Civil Engineering Technicians3112 Civil Engineering TechniciansITAit
49711460111fa parte della misericordia. Trasporta i malat...32583258Ambulance Workers3258 Ambulance WorkersITAit
49810340111사회복지사. 회사에서 복지원 관리26352635Social Work and Counselling Professionals2635 Social Work and Counselling ProfessionalsKORko
49910370105자영업. 가게를 운영하신다.5221NoneShopkeepers5221 ShopkeepersKORko
\n", "

500 rows × 8 columns

\n", "
" ], "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 here for more info. \n", "\u001b[1;31mView Jupyter log 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=\"\")\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 }