{ "cells": [ { "cell_type": "markdown", "id": "e25090fa-f990-4f1a-84f3-b12159eedae8", "metadata": {}, "source": [ "# Working with a Large Language Model (LLM)" ] }, { "cell_type": "markdown", "id": "3bbee2e4-55c8-4b06-9929-72026edf7932", "metadata": {}, "source": [ "## Prerequisites" ] }, { "cell_type": "code", "execution_count": 1, "id": "f8c28d2d-8458-49fd-8ebf-5e729d6e861f", "metadata": {}, "outputs": [], "source": [ "import math\n", "import json\n", "import pickle\n", "import os\n", "import time\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "from tabulate import tabulate\n", "from transformers import pipeline\n", "\n", "# Get candidate labels\n", "with open(\"packing_label_structure.json\", \"r\") as file:\n", " candidate_labels = json.load(file)\n", "keys_list = list(candidate_labels.keys())\n", "\n", "# Load test data (list of dictionaries)\n", "with open(\"test_data.json\", \"r\") as file:\n", " packing_data = json.load(file)\n", "# Extract trip descriptions and classification (trip_types)\n", "trip_descriptions = [trip['description'] for trip in packing_data]\n", "trip_types = [trip['trip_types'] for trip in packing_data]" ] }, { "cell_type": "markdown", "id": "5cf4f76f-0035-44e8-93af-52eafaec686e", "metadata": {}, "source": [ "**All trip descriptions**" ] }, { "cell_type": "code", "execution_count": 2, "id": "89d42ca7-e871-4eda-b428-69e9bd965428", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 . I am planning a trip to Greece with my boyfriend, where we will visit two islands. We have booked an apartment on each island for a few days and plan to spend most of our time relaxing. Our main goals are to enjoy the beach, try delicious local food, and possibly go on a hike—if it’s not too hot. We will be relying solely on public transport. We’re in our late 20s and traveling from the Netherlands. \n", "\n", "beach vacation\n", "['swimming', 'going to the beach', 'relaxing', 'hiking']\n", "warm destination / summer\n", "lightweight (but comfortable)\n", "casual\n", "indoor\n", "no own vehicle\n", "no special conditions to consider\n", "7+ days\n", "\n", "\n", "1 . We are a couple in our thirties traveling to Vienna for a three-day city trip. We’ll be staying at a friend’s house and plan to explore the city by sightseeing, strolling through the streets, visiting markets, and trying out great restaurants and cafés. We also hope to attend a classical music concert. Our journey to Vienna will be by train. \n", "\n", "city trip\n", "['sightseeing']\n", "variable weather / spring / autumn\n", "luxury (including evening wear)\n", "casual\n", "indoor\n", "no own vehicle\n", "no special conditions to consider\n", "3 days\n", "\n", "\n", "2 . My partner and I are traveling to the Netherlands and Germany to spend Christmas with our family. We are in our late twenties and will start our journey with a two-hour flight to the Netherlands. From there, we will take a 5.5-hour train ride to northern Germany. \n", "\n", "city trip\n", "['relaxing']\n", "cold destination / winter\n", "lightweight (but comfortable)\n", "casual\n", "indoor\n", "no own vehicle\n", "no special conditions to consider\n", "7+ days\n", "\n", "\n", "3 . I’m in my twenties and will be traveling to Peru for three weeks. I’m going solo but will meet up with a friend to explore the Sacred Valley and take part in a Machu Picchu tour. We plan to hike, go rafting, and explore the remnants of the ancient Inca Empire. We’re also excited to try Peruvian cuisine and immerse ourselves in the local culture. Depending on our plans, we might also visit the rainforest region, such as Tarapoto. I’ll be flying to Peru on a long-haul flight and will be traveling in August. \n", "\n", "cultural exploration\n", "['sightseeing', 'hiking', 'rafting']\n", "variable weather / spring / autumn\n", "lightweight (but comfortable)\n", "casual\n", "indoor\n", "no own vehicle\n", "rainy climate\n", "7+ days\n", "\n", "\n", "4 . We’re planning a 10-day trip to Austria in the summer, combining hiking with relaxation by the lake. We love exploring scenic trails and enjoying the outdoors, but we also want to unwind and swim in the lake. It’s the perfect mix of adventure and relaxation. \n", "\n", "nature escape\n", "['swimming', 'relaxing', 'hiking']\n", "warm destination / summer\n", "lightweight (but comfortable)\n", "casual\n", "indoor\n", "no own vehicle\n", "no special conditions to consider\n", "7+ days\n", "\n", "\n", "5 . I am going on a multiple day hike and passing though mountains and the beach in Croatia. I like to pack light and will stay in refugios/huts with half board and travel to the start of the hike by car. It will be 6-7 days. \n", "\n", "long-distance hike / thru-hike\n", "['going to the beach']\n", "tropical / humid\n", "minimalist\n", "casual\n", "huts with half board\n", "own vehicle\n", "off-grid / no electricity\n", "6 days\n", "\n", "\n", "6 . I will go with a friend on a beach holiday and we will do stand-up paddling, and surfing in the North of Spain. The destination is windy and can get cold, but is generally sunny. We will go by car and bring a tent to sleep in. It will be two weeks. \n", "\n", "beach vacation\n", "['stand-up paddleboarding (SUP)', 'surfing']\n", "cold destination / winter\n", "ultralight\n", "casual\n", "sleeping in a tent\n", "own vehicle\n", "off-grid / no electricity\n", "6 days\n", "\n", "\n", "7 . We will go to Sweden in the winter, to go for a yoga and sauna/wellness retreat. I prefer lightweight packing and also want clothes to go for fancy dinners and maybe on a winter hike. We stay in hotels. \n", "\n", "yoga / wellness retreat\n", "['hiking', 'yoga']\n", "cold destination / winter\n", "lightweight (but comfortable)\n", "casual\n", "indoor\n", "no own vehicle\n", "snow and ice\n", "7 days\n", "\n", "\n", "8 . I go on a skitouring trip where we also make videos/photos and the destination is Japan. Mainly sports clothes and isolation are needed (it is winter). We stay in a guesthouse. It will be 10 days. \n", "\n", "ski tour / skitour\n", "['ski touring', 'photography']\n", "cold destination / winter\n", "minimalist\n", "conservative\n", "indoor\n", "no own vehicle\n", "avalanche-prone terrain\n", "7+ days\n", "\n", "\n", "9 . We plan a wild camping trip with activities such as snorkeling, kayaking and canoeing. It is a warm place and we want to bring little stuff. We stay in tents and hammocks and travel with a car, it will be 3 days. \n", "\n", "camping trip (wild camping)\n", "['scuba diving', 'kayaking / canoeing']\n", "tropical / humid\n", "lightweight (but comfortable)\n", "casual\n", "sleeping in a tent\n", "own vehicle\n", "self-supported (bring your own cooking gear)\n", "3 days\n", "\n", "\n" ] } ], "source": [ "for i, item in enumerate(trip_descriptions):\n", " print(i, \".\", item, \"\\n\")\n", " for elem in trip_types[i]:\n", " print(elem)\n", " print(\"\\n\")" ] }, { "cell_type": "markdown", "id": "0f60c54b-affc-4d9a-acf1-da70f68c5578", "metadata": {}, "source": [ "**Functions**" ] }, { "cell_type": "code", "execution_count": 3, "id": "fac51224-9575-4b4b-8567-4ad4e759ecc9", "metadata": {}, "outputs": [], "source": [ "def pred_trip(model_name, trip_descr, trip_type, cut_off = 0.5):\n", " \"\"\"\n", " Classifies trip\n", " \n", " Parameters:\n", " model_name: name of hugging-face model\n", " trip_descr: text describing the trip\n", " trip_type: true trip classification\n", " cut_off: cut_off for choosing activities\n", "\n", " Returns:\n", " pd Dataframe: with class predictions and true values\n", " \"\"\"\n", " \n", " classifier = pipeline(\"zero-shot-classification\", model=model_name)\n", " df = pd.DataFrame(columns=['superclass', 'pred_class'])\n", " for i, key in enumerate(keys_list):\n", " print(i)\n", " if key == 'activities':\n", " result = classifier(trip_descr, candidate_labels[key], multi_label=True)\n", " indices = [i for i, score in enumerate(result['scores']) if score > cut_off]\n", " classes = [result['labels'][i] for i in indices]\n", " else:\n", " result = classifier(trip_descr, candidate_labels[key])\n", " classes = result[\"labels\"][0]\n", " df.loc[i] = [key, classes]\n", " df['true_class'] = trip_type\n", " return df" ] }, { "cell_type": "code", "execution_count": 4, "id": "b36ab806-2f35-4950-ac5a-7c192190cba7", "metadata": {}, "outputs": [], "source": [ "def perf_measure(df):\n", " \"\"\"\n", " Calculates performance measures:\n", " Accuracy of classification excluding activities superclass\n", " Percentage of correctly identified activities (#correctly predicted/#true activities)\n", " Percentage of wrongly identified activities (#wrongly predicted/#predicted activities)\n", "\n", " Parameters:\n", " df: pd Dataframe returned from pred_trip()\n", "\n", " Returns:\n", " pd Dataframe: containing performance measures\n", " \"\"\"\n", " \n", " df['same_value'] = df['pred_class'] == df['true_class']\n", " correct = sum(df.loc[df.index != 1, 'same_value'])\n", " total = len(df['same_value'])\n", " accuracy = correct/total\n", " pred_class = df.loc[df.index == 1, 'pred_class'].iloc[0]\n", " true_class = df.loc[df.index == 1, 'true_class'].iloc[0]\n", " correct = [label for label in pred_class if label in true_class]\n", " num_correct = len(correct)\n", " correct_perc = num_correct/len(true_class)\n", " num_pred = len(pred_class)\n", " if num_pred == 0:\n", " wrong_perc = math.nan\n", " else:\n", " wrong_perc = (num_pred - num_correct)/num_pred\n", " df_perf = pd.DataFrame({\n", " 'accuracy': [accuracy],\n", " 'true_ident': [correct_perc],\n", " 'false_pred': [wrong_perc]\n", " })\n", " return(df_perf)" ] }, { "cell_type": "markdown", "id": "c10aa57d-d7ed-45c7-bdf5-29af193c7fd5", "metadata": {}, "source": [ "## Make predictions for many models and trip descriptions\n", "\n", "Provide a list of candidate models and apply them to the test data." ] }, { "cell_type": "code", "execution_count": 22, "id": "dd7869a8-b436-40de-9ea0-28eb4b7d3248", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Using model: pongjin/roberta_with_kornli\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a44415d353264dda885031d6570e21a7", "version_major": 2, "version_minor": 0 }, "text/plain": [ "config.json: 0%| | 0.00/985 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "d31b49452fe64db39745a833a832a340", "version_major": 2, "version_minor": 0 }, "text/plain": [ "pytorch_model.bin: 0%| | 0.00/443M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a4c31853bc854b8d91dca8689b7cdc18", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer_config.json: 0%| | 0.00/415 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "048df7d028224b5bb36b5b8042c8579b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "vocab.txt: 0.00B [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b9a39be1b8024e27aee465f0253c8274", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer.json: 0.00B [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "c4170138359149728e468730ee237f8e", "version_major": 2, "version_minor": 0 }, "text/plain": [ "special_tokens_map.json: 0%| | 0.00/173 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "\n", "Using model: MoritzLaurer/mDeBERTa-v3-base-xnli-multilingual-nli-2mil7\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "c1b011a630894a23b58f4a88e97a849d", "version_major": 2, "version_minor": 0 }, "text/plain": [ "config.json: 0.00B [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "5fa889524f9c439d9bbd79426e2eefa6", "version_major": 2, "version_minor": 0 }, "text/plain": [ "model.safetensors: 0%| | 0.00/558M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Error while downloading from https://cas-bridge.xethub.hf.co/xet-bridge-us/6303b5f71dd5d3c62482f3e9/11250a388e769f8d819bc3d9b55590ab43bde78b2d4f37df57bc5603c5dea0b0?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=cas%2F20251104%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251104T105145Z&X-Amz-Expires=3600&X-Amz-Signature=603bdf8dd3ba17470e9f30bd3b31141b09a02d57e6cf00b63996b798d985c323&X-Amz-SignedHeaders=host&X-Xet-Cas-Uid=public&response-content-disposition=inline%3B+filename*%3DUTF-8%27%27model.safetensors%3B+filename%3D%22model.safetensors%22%3B&x-id=GetObject&Expires=1762257105&Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTc2MjI1NzEwNX19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2FzLWJyaWRnZS54ZXRodWIuaGYuY28veGV0LWJyaWRnZS11cy82MzAzYjVmNzFkZDVkM2M2MjQ4MmYzZTkvMTEyNTBhMzg4ZTc2OWY4ZDgxOWJjM2Q5YjU1NTkwYWI0M2JkZTc4YjJkNGYzN2RmNTdiYzU2MDNjNWRlYTBiMCoifV19&Signature=s7MbLznU9vhypkS2WueXkH%7E41QifR0qWT8YHXKdMNPheh483kMtmwoaCCqvVlcukJygS0K2zvyynfo8zpNM%7EqiH8ZI1k3E7B2f6UH97HlJA48Th3pabY4zi1WYI2IeZDnBdPlreb3qTCkCZw1l11fyt9ri2QOaxuRrT6jcxPOquIFzz5lZ0sZNjngA0rg8gtCGi89qsWATMV3Oh45cRpO%7E6DrmmHfP8LEk8sZOiu9Zi-33x-ZoO4oayJSvzxOw8y8TWs%7E5q3cD9geNVIToO-PJPHQJ6qk9FybNeN75zhWtBtERN77Ie2mf9mGEcnZVqBd%7EH4kyAyYsWUcwviGjJSxA__&Key-Pair-Id=K2L8F4GPSG1IFC: HTTPSConnectionPool(host='cas-bridge.xethub.hf.co', port=443): Read timed out.\n", "Trying to resume download...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "137e0628b2464c4ba34304ff81db5cc3", "version_major": 2, "version_minor": 0 }, "text/plain": [ "model.safetensors: 26%|##6 | 147M/558M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Error while downloading from https://cas-bridge.xethub.hf.co/xet-bridge-us/6303b5f71dd5d3c62482f3e9/11250a388e769f8d819bc3d9b55590ab43bde78b2d4f37df57bc5603c5dea0b0?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=cas%2F20251104%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251104T105145Z&X-Amz-Expires=3600&X-Amz-Signature=603bdf8dd3ba17470e9f30bd3b31141b09a02d57e6cf00b63996b798d985c323&X-Amz-SignedHeaders=host&X-Xet-Cas-Uid=public&response-content-disposition=inline%3B+filename*%3DUTF-8%27%27model.safetensors%3B+filename%3D%22model.safetensors%22%3B&x-id=GetObject&Expires=1762257105&Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTc2MjI1NzEwNX19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2FzLWJyaWRnZS54ZXRodWIuaGYuY28veGV0LWJyaWRnZS11cy82MzAzYjVmNzFkZDVkM2M2MjQ4MmYzZTkvMTEyNTBhMzg4ZTc2OWY4ZDgxOWJjM2Q5YjU1NTkwYWI0M2JkZTc4YjJkNGYzN2RmNTdiYzU2MDNjNWRlYTBiMCoifV19&Signature=s7MbLznU9vhypkS2WueXkH%7E41QifR0qWT8YHXKdMNPheh483kMtmwoaCCqvVlcukJygS0K2zvyynfo8zpNM%7EqiH8ZI1k3E7B2f6UH97HlJA48Th3pabY4zi1WYI2IeZDnBdPlreb3qTCkCZw1l11fyt9ri2QOaxuRrT6jcxPOquIFzz5lZ0sZNjngA0rg8gtCGi89qsWATMV3Oh45cRpO%7E6DrmmHfP8LEk8sZOiu9Zi-33x-ZoO4oayJSvzxOw8y8TWs%7E5q3cD9geNVIToO-PJPHQJ6qk9FybNeN75zhWtBtERN77Ie2mf9mGEcnZVqBd%7EH4kyAyYsWUcwviGjJSxA__&Key-Pair-Id=K2L8F4GPSG1IFC: HTTPSConnectionPool(host='cas-bridge.xethub.hf.co', port=443): Read timed out.\n", "Trying to resume download...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "9a7e7a8614d14b789f54c4e61b526bf8", "version_major": 2, "version_minor": 0 }, "text/plain": [ "model.safetensors: 26%|##6 | 147M/558M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Error while downloading from https://cas-bridge.xethub.hf.co/xet-bridge-us/6303b5f71dd5d3c62482f3e9/11250a388e769f8d819bc3d9b55590ab43bde78b2d4f37df57bc5603c5dea0b0?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=cas%2F20251104%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251104T105145Z&X-Amz-Expires=3600&X-Amz-Signature=603bdf8dd3ba17470e9f30bd3b31141b09a02d57e6cf00b63996b798d985c323&X-Amz-SignedHeaders=host&X-Xet-Cas-Uid=public&response-content-disposition=inline%3B+filename*%3DUTF-8%27%27model.safetensors%3B+filename%3D%22model.safetensors%22%3B&x-id=GetObject&Expires=1762257105&Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTc2MjI1NzEwNX19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2FzLWJyaWRnZS54ZXRodWIuaGYuY28veGV0LWJyaWRnZS11cy82MzAzYjVmNzFkZDVkM2M2MjQ4MmYzZTkvMTEyNTBhMzg4ZTc2OWY4ZDgxOWJjM2Q5YjU1NTkwYWI0M2JkZTc4YjJkNGYzN2RmNTdiYzU2MDNjNWRlYTBiMCoifV19&Signature=s7MbLznU9vhypkS2WueXkH%7E41QifR0qWT8YHXKdMNPheh483kMtmwoaCCqvVlcukJygS0K2zvyynfo8zpNM%7EqiH8ZI1k3E7B2f6UH97HlJA48Th3pabY4zi1WYI2IeZDnBdPlreb3qTCkCZw1l11fyt9ri2QOaxuRrT6jcxPOquIFzz5lZ0sZNjngA0rg8gtCGi89qsWATMV3Oh45cRpO%7E6DrmmHfP8LEk8sZOiu9Zi-33x-ZoO4oayJSvzxOw8y8TWs%7E5q3cD9geNVIToO-PJPHQJ6qk9FybNeN75zhWtBtERN77Ie2mf9mGEcnZVqBd%7EH4kyAyYsWUcwviGjJSxA__&Key-Pair-Id=K2L8F4GPSG1IFC: HTTPSConnectionPool(host='cas-bridge.xethub.hf.co', port=443): Read timed out.\n", "Trying to resume download...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "517575609add45b3a2494deae2cdacc3", "version_major": 2, "version_minor": 0 }, "text/plain": [ "model.safetensors: 26%|##6 | 147M/558M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Error while downloading from https://cas-bridge.xethub.hf.co/xet-bridge-us/6303b5f71dd5d3c62482f3e9/11250a388e769f8d819bc3d9b55590ab43bde78b2d4f37df57bc5603c5dea0b0?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=cas%2F20251104%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251104T105145Z&X-Amz-Expires=3600&X-Amz-Signature=603bdf8dd3ba17470e9f30bd3b31141b09a02d57e6cf00b63996b798d985c323&X-Amz-SignedHeaders=host&X-Xet-Cas-Uid=public&response-content-disposition=inline%3B+filename*%3DUTF-8%27%27model.safetensors%3B+filename%3D%22model.safetensors%22%3B&x-id=GetObject&Expires=1762257105&Policy=eyJTdGF0ZW1lbnQiOlt7IkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTc2MjI1NzEwNX19LCJSZXNvdXJjZSI6Imh0dHBzOi8vY2FzLWJyaWRnZS54ZXRodWIuaGYuY28veGV0LWJyaWRnZS11cy82MzAzYjVmNzFkZDVkM2M2MjQ4MmYzZTkvMTEyNTBhMzg4ZTc2OWY4ZDgxOWJjM2Q5YjU1NTkwYWI0M2JkZTc4YjJkNGYzN2RmNTdiYzU2MDNjNWRlYTBiMCoifV19&Signature=s7MbLznU9vhypkS2WueXkH%7E41QifR0qWT8YHXKdMNPheh483kMtmwoaCCqvVlcukJygS0K2zvyynfo8zpNM%7EqiH8ZI1k3E7B2f6UH97HlJA48Th3pabY4zi1WYI2IeZDnBdPlreb3qTCkCZw1l11fyt9ri2QOaxuRrT6jcxPOquIFzz5lZ0sZNjngA0rg8gtCGi89qsWATMV3Oh45cRpO%7E6DrmmHfP8LEk8sZOiu9Zi-33x-ZoO4oayJSvzxOw8y8TWs%7E5q3cD9geNVIToO-PJPHQJ6qk9FybNeN75zhWtBtERN77Ie2mf9mGEcnZVqBd%7EH4kyAyYsWUcwviGjJSxA__&Key-Pair-Id=K2L8F4GPSG1IFC: HTTPSConnectionPool(host='cas-bridge.xethub.hf.co', port=443): Read timed out.\n", "Trying to resume download...\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "91efbf29652b4f77be230c371d1a515b", "version_major": 2, "version_minor": 0 }, "text/plain": [ "model.safetensors: 26%|##6 | 147M/558M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b57255653a394073ad9f6a10ae142d31", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer_config.json: 0%| | 0.00/467 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "4269962d819c4a06a6fd38069293eef2", "version_major": 2, "version_minor": 0 }, "text/plain": [ "spm.model: 0%| | 0.00/4.31M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "d209ea62c4bb421ebe01856271b32bf5", "version_major": 2, "version_minor": 0 }, "text/plain": [ "tokenizer.json: 0%| | 0.00/16.3M [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "574f0405e8c2410d9659b60b263dab81", "version_major": 2, "version_minor": 0 }, "text/plain": [ "added_tokens.json: 0%| | 0.00/23.0 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "09d43e8d85214c0096ff7836934d23ac", "version_major": 2, "version_minor": 0 }, "text/plain": [ "special_tokens_map.json: 0%| | 0.00/173 [00:00, ?B/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n" ] } ], "source": [ "# List of Hugging Face model names\n", "# trending...\n", "\"\"\"\n", "model_names = [\n", " \"facebook/bart-large-mnli\",\n", " \"MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli\",\n", " \"cross-encoder/nli-deberta-v3-base\",\n", " \"cross-encoder/nli-deberta-v3-large\",\n", " \"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli\",\n", " \"joeddav/bart-large-mnli-yahoo-answers\",\n", " \"MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli\",\n", " \"MoritzLaurer/deberta-v3-large-zeroshot-v2.0\",\n", " \"valhalla/distilbart-mnli-12-1\",\n", " #\"joeddav/xlm-roberta-large-xnli\" # keeps giving errors\n", "]\n", "\"\"\"\n", "\n", "# most downloads\n", "model_names = [\n", " #\"facebook/bart-large-mnli\",\n", " #\"MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli\",\n", " #\"sileod/deberta-v3-base-tasksource-nli\",\n", " #\"vicgalle/xlm-roberta-large-xnli-anli\", # gives errors\n", " #\"joeddav/xlm-roberta-large-xnli\",# errors\n", " #\"chuhac/BiomedCLIP-vit-bert-hf\",# errors\n", " \"pongjin/roberta_with_kornli\",\n", " #\"joeddav/bart-large-mnli-yahoo-answers\",\n", " #\"MoritzLaurer/mDeBERTa-v3-base-mnli-xnli\",\n", " #\"valhalla/distilbart-mnli-12-1\",\n", " \"MoritzLaurer/mDeBERTa-v3-base-xnli-multilingual-nli-2mil7\"\n", "]\n", "\n", "\n", "# Apply each model to the test data\n", "for model_name in model_names:\n", " print(f\"\\nUsing model: {model_name}\")\n", " result_list = []\n", " performance = pd.DataFrame(columns=['accuracy', 'true_ident', 'false_pred'])\n", " \n", " start_time = time.time()\n", " for i in range(len(trip_descriptions)):\n", " current_trip = trip_descriptions[i]\n", " current_type = trip_types[i]\n", " df = pred_trip(model_name, current_trip, current_type, cut_off = 0.5)\n", " performance = pd.concat([performance, perf_measure(df)])\n", " result_list.append(df)\n", " end_time = time.time()\n", " elapsed_time = end_time - start_time\n", " \n", " # Extract and combine columns identifying correct prediction (for each trip)\n", " sv_columns = [df['same_value'] for df in result_list]\n", " sv_columns.insert(0, result_list[0]['superclass'])\n", " sv_df = pd.concat(sv_columns, axis=1)\n", " # Compute accuracy per superclass\n", " row_means = sv_df.iloc[:, 1:].mean(axis=1)\n", " df_row_means = pd.DataFrame({\n", " 'superclass': sv_df['superclass'],\n", " 'accuracy': row_means\n", " })\n", " # Compute performance measures per trip (mean for each column of performance table)\n", " column_means = performance.mean()\n", " # Save results\n", " model = model_name.replace(\"/\", \"-\")\n", " model_result = {\n", " 'model': model,\n", " 'predictions': result_list,\n", " 'performance': performance,\n", " 'perf_summary': column_means,\n", " 'perf_superclass': df_row_means,\n", " 'elapsed_time': elapsed_time\n", " }\n", " filename = os.path.join('results', f'{model}_results.pkl')\n", " with open(filename, 'wb') as f:\n", " pickle.dump(model_result, f)\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "id": "e1cbb54e-abe6-49b6-957e-0683196f3199", "metadata": {}, "source": [ "## Load and compare results" ] }, { "cell_type": "code", "execution_count": 5, "id": "37849e0b-864e-4377-b06c-0ac70c3861f9", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: cross-encoder-nli-deberta-v3-base\n", "Performance Summary:\n", "accuracy 0.444444\n", "true_ident 0.533333\n", "false_pred 0.712500\n", "dtype: float64\n", "----------------------------------------\n", "Model: joeddav-bart-large-mnli-yahoo-answers\n", "Performance Summary:\n", "accuracy 0.355556\n", "true_ident 0.650000\n", "false_pred 0.553792\n", "dtype: float64\n", "----------------------------------------\n", "Model: cross-encoder-nli-deberta-v3-large\n", "Performance Summary:\n", "accuracy 0.466667\n", "true_ident 0.566667\n", "false_pred 0.541667\n", "dtype: float64\n", "----------------------------------------\n", "Model: MoritzLaurer-DeBERTa-v3-large-mnli-fever-anli-ling-wanli\n", "Performance Summary:\n", "accuracy 0.611111\n", "true_ident 0.841667\n", "false_pred 0.546667\n", "dtype: float64\n", "----------------------------------------\n", "Model: MoritzLaurer-mDeBERTa-v3-base-mnli-xnli\n", "Performance Summary:\n", "accuracy 0.455556\n", "true_ident 0.408333\n", "false_pred 0.481250\n", "dtype: float64\n", "----------------------------------------\n", "Model: MoritzLaurer-deberta-v3-large-zeroshot-v2.0\n", "Performance Summary:\n", "accuracy 0.500\n", "true_ident 0.325\n", "false_pred 0.500\n", "dtype: float64\n", "----------------------------------------\n", "Model: pongjin-roberta_with_kornli\n", "Performance Summary:\n", "accuracy 0.233333\n", "true_ident 0.666667\n", "false_pred 0.452857\n", "dtype: float64\n", "----------------------------------------\n", "Model: sileod-deberta-v3-base-tasksource-nli\n", "Performance Summary:\n", "accuracy 0.566667\n", "true_ident 0.700000\n", "false_pred 0.551667\n", "dtype: float64\n", "----------------------------------------\n", "Model: MoritzLaurer-mDeBERTa-v3-base-xnli-multilingual-nli-2mil7\n", "Performance Summary:\n", "accuracy 0.488889\n", "true_ident 0.833333\n", "false_pred 0.688373\n", "dtype: float64\n", "----------------------------------------\n", "Model: facebook-bart-large-mnli\n", "Performance Summary:\n", "accuracy 0.466667\n", "true_ident 0.708333\n", "false_pred 0.400000\n", "dtype: float64\n", "----------------------------------------\n", "Model: valhalla-distilbart-mnli-12-1\n", "Performance Summary:\n", "accuracy 0.500000\n", "true_ident 0.300000\n", "false_pred 0.533333\n", "dtype: float64\n", "----------------------------------------\n", "Model: MoritzLaurer-DeBERTa-v3-base-mnli-fever-anli\n", "Performance Summary:\n", "accuracy 0.522222\n", "true_ident 0.841667\n", "false_pred 0.572381\n", "dtype: float64\n", "----------------------------------------\n" ] } ], "source": [ "# Folder where .pkl files are saved\n", "results_dir = 'results'\n", "\n", "# Dictionary to store all loaded results\n", "all_results = {}\n", "\n", "# Loop through all .pkl files in the folder\n", "for filename in os.listdir(results_dir):\n", " if filename.endswith('.pkl'):\n", " model_name = filename.replace('_results.pkl', '') # Extract model name\n", " file_path = os.path.join(results_dir, filename)\n", " \n", " # Load the result\n", " with open(file_path, 'rb') as f:\n", " result = pickle.load(f)\n", " all_results[model_name] = result\n", "\n", "# Compare performance across models\n", "for model, data in all_results.items():\n", " print(f\"Model: {model}\")\n", " print(f\"Performance Summary:\\n{data['perf_summary']}\")\n", " print(\"-\" * 40)\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "3f1951b1-884d-49ab-985d-ab1779c6f71d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n" ] } ], "source": [ "print(len(all_results))" ] }, { "cell_type": "markdown", "id": "2f65e5b1-bc32-42c2-bbe9-9e3a6ffc72c1", "metadata": {}, "source": [ "**Identify trips that are difficult to predict**" ] }, { "cell_type": "markdown", "id": "040055c9-5df4-49b0-921a-5bf98ff01a69", "metadata": {}, "source": [ "Per model" ] }, { "cell_type": "code", "execution_count": 7, "id": "57fd150d-1cda-4be5-806b-ef380469243a", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cross-encoder-nli-deberta-v3-base: Index([0, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')\n", "\n", "joeddav-bart-large-mnli-yahoo-answers: RangeIndex(start=0, stop=10, step=1)\n", "\n", "cross-encoder-nli-deberta-v3-large: Index([0, 1, 2, 3, 4, 6, 7, 8, 9], dtype='int64')\n", "\n", "MoritzLaurer-DeBERTa-v3-large-mnli-fever-anli-ling-wanli: Index([2, 3, 5, 6, 7, 8, 9], dtype='int64')\n", "\n", "MoritzLaurer-mDeBERTa-v3-base-mnli-xnli: RangeIndex(start=0, stop=10, step=1)\n", "\n", "MoritzLaurer-deberta-v3-large-zeroshot-v2.0: Index([1, 2, 3, 5, 6, 7, 9], dtype='int64')\n", "\n", "pongjin-roberta_with_kornli: RangeIndex(start=0, stop=10, step=1)\n", "\n", "sileod-deberta-v3-base-tasksource-nli: Index([0, 2, 3, 5, 6], dtype='int64')\n", "\n", "MoritzLaurer-mDeBERTa-v3-base-xnli-multilingual-nli-2mil7: Index([0, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')\n", "\n", "facebook-bart-large-mnli: RangeIndex(start=0, stop=10, step=1)\n", "\n", "valhalla-distilbart-mnli-12-1: Index([0, 1, 2, 3, 4, 7, 9], dtype='int64')\n", "\n", "MoritzLaurer-DeBERTa-v3-base-mnli-fever-anli: Index([0, 2, 3, 4, 6, 7], dtype='int64')\n", "\n" ] } ], "source": [ "def get_difficult_trips(model_result, cut_off = 0.6):\n", " \"\"\"\n", " \"\"\"\n", " # model_result is a dict with dict_keys(['model', 'predictions', \n", " # 'performance', 'perf_summary', 'perf_superclass', 'elapsed_time'])\n", " # get performance dataframe and repair index\n", " df = model_result['performance'].reset_index(drop=True)\n", " # find index of trips whose accuracy is below cut_off\n", " index_result = df[df['accuracy'] < cut_off].index\n", " return(index_result)\n", "\n", "# dictionary of trips that have accuracy below cut_off default\n", "difficult_trips_dict = {}\n", "for model, data in all_results.items():\n", " difficult_trips_dict[data[\"model\"]] = get_difficult_trips(data)\n", "\n", "for key, value in difficult_trips_dict.items():\n", " print(f\"{key}: {value}\\n\")" ] }, { "cell_type": "markdown", "id": "d91fb932-c5aa-472a-9b8d-a0cfc83a87f8", "metadata": {}, "source": [ "For all models" ] }, { "cell_type": "code", "execution_count": 8, "id": "a2754cb7-59b9-4f1d-ab74-1bf711b3eba2", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 . My partner and I are traveling to the Netherlands and Germany to spend Christmas with our family. We are in our late twenties and will start our journey with a two-hour flight to the Netherlands. From there, we will take a 5.5-hour train ride to northern Germany. \n", "\n", "city trip\n", "['relaxing']\n", "cold destination / winter\n", "lightweight (but comfortable)\n", "casual\n", "indoor\n", "no own vehicle\n", "no special conditions to consider\n", "7+ days\n", "\n", "\n", "3 . I’m in my twenties and will be traveling to Peru for three weeks. I’m going solo but will meet up with a friend to explore the Sacred Valley and take part in a Machu Picchu tour. We plan to hike, go rafting, and explore the remnants of the ancient Inca Empire. We’re also excited to try Peruvian cuisine and immerse ourselves in the local culture. Depending on our plans, we might also visit the rainforest region, such as Tarapoto. I’ll be flying to Peru on a long-haul flight and will be traveling in August. \n", "\n", "cultural exploration\n", "['sightseeing', 'hiking', 'rafting']\n", "variable weather / spring / autumn\n", "lightweight (but comfortable)\n", "casual\n", "indoor\n", "no own vehicle\n", "rainy climate\n", "7+ days\n", "\n", "\n" ] } ], "source": [ "# Which trips are difficult for all models\n", "common = set.intersection(*(set(v) for v in difficult_trips_dict.values()))\n", "for index in common:\n", " print(index, \".\", trip_descriptions[index], \"\\n\")\n", " for item in trip_types[index]:\n", " print(item)\n", " print(\"\\n\")" ] }, { "cell_type": "markdown", "id": "be58d66f-a491-4f47-98df-2c0aa4af38e7", "metadata": {}, "source": [ "**Identify superclasses that are difficult to predict**" ] }, { "cell_type": "markdown", "id": "7e833c2d-9356-4d40-9b20-0a1eb6628a30", "metadata": {}, "source": [ "Per model" ] }, { "cell_type": "code", "execution_count": 9, "id": "adb491b1-3ac3-4c32-934f-5eb6171f2ec9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cross-encoder-nli-deberta-v3-base: ['activities', 'climate_or_season', 'style_or_comfort', 'special_conditions']\n", "\n", "joeddav-bart-large-mnli-yahoo-answers: ['activities', 'climate_or_season', 'style_or_comfort', 'dress_code', 'accommodation', 'transportation', 'special_conditions']\n", "\n", "cross-encoder-nli-deberta-v3-large: ['activities', 'climate_or_season', 'style_or_comfort', 'transportation', 'special_conditions']\n", "\n", "MoritzLaurer-DeBERTa-v3-large-mnli-fever-anli-ling-wanli: ['activities', 'style_or_comfort']\n", "\n", "MoritzLaurer-mDeBERTa-v3-base-mnli-xnli: ['activities', 'style_or_comfort', 'accommodation', 'special_conditions', 'trip_length_days']\n", "\n", "MoritzLaurer-deberta-v3-large-zeroshot-v2.0: ['activities', 'climate_or_season', 'style_or_comfort', 'accommodation', 'special_conditions']\n", "\n", "pongjin-roberta_with_kornli: ['activity_type', 'activities', 'climate_or_season', 'style_or_comfort', 'dress_code', 'accommodation', 'transportation', 'special_conditions', 'trip_length_days']\n", "\n", "sileod-deberta-v3-base-tasksource-nli: ['activities', 'style_or_comfort', 'special_conditions']\n", "\n", "MoritzLaurer-mDeBERTa-v3-base-xnli-multilingual-nli-2mil7: ['activity_type', 'activities', 'style_or_comfort', 'special_conditions']\n", "\n", "facebook-bart-large-mnli: ['activities', 'style_or_comfort', 'accommodation', 'special_conditions']\n", "\n", "valhalla-distilbart-mnli-12-1: ['activities', 'climate_or_season', 'style_or_comfort', 'accommodation', 'special_conditions']\n", "\n", "MoritzLaurer-DeBERTa-v3-base-mnli-fever-anli: ['activities', 'climate_or_season', 'style_or_comfort', 'special_conditions']\n", "\n" ] } ], "source": [ "def get_difficult_superclasses(model_result, cut_off = 0.6):\n", " # model_result is a dict with dict_keys(['model', 'predictions', \n", " # 'performance', 'perf_summary', 'perf_superclass', 'elapsed_time'])\n", " df = model_result[\"perf_superclass\"]\n", " # find superclass whose accuracy is below cut_off\n", " diff_spc = list(df[df['accuracy'] < cut_off][\"superclass\"])\n", " return(diff_spc)\n", "\n", "# make dictionary of superclasses that have accuracy below cut_off default\n", "difficult_superclass_dict = {}\n", "for model, data in all_results.items():\n", " difficult_superclass_dict[data[\"model\"]] = get_difficult_superclasses(data)\n", "\n", "for key, value in difficult_superclass_dict.items():\n", " print(f\"{key}: {value}\\n\")" ] }, { "cell_type": "markdown", "id": "fbcebdf8-0975-45cb-96f5-15b4645aa7f6", "metadata": {}, "source": [ "For all models" ] }, { "cell_type": "code", "execution_count": 10, "id": "4e51c11b-9a0a-4f9d-b20c-a6feda2d5a3b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'activities', 'style_or_comfort'}\n" ] } ], "source": [ "# Which trips are difficult for all models\n", "common = set.intersection(*(set(v) for v in difficult_superclass_dict.values()))\n", "print(common)" ] }, { "cell_type": "code", "execution_count": 11, "id": "f0e31e2c-e87d-4776-b781-991919492430", "metadata": {}, "outputs": [], "source": [ "# Look at particular predicitons in detail\n", "# print(all_results[\"joeddav-bart-large-mnli-yahoo-answers\"])" ] }, { "cell_type": "markdown", "id": "01e24355-4aac-4ad6-b50c-96f75585ce45", "metadata": {}, "source": [ "**Comparing models**" ] }, { "cell_type": "code", "execution_count": 12, "id": "b020f584-1468-4c84-9dac-7ca7fac6e8ca", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " model accuracy true_ident false_pred\n", "0 MoritzLaurer-DeBERTa-v3-large-mnli-fever-anli-ling-wanli 0.611111 0.841667 0.546667\n", "1 sileod-deberta-v3-base-tasksource-nli 0.566667 0.700000 0.551667\n", "2 MoritzLaurer-DeBERTa-v3-base-mnli-fever-anli 0.522222 0.841667 0.572381\n", "3 MoritzLaurer-deberta-v3-large-zeroshot-v2.0 0.500000 0.325000 0.500000\n", "4 valhalla-distilbart-mnli-12-1 0.500000 0.300000 0.533333\n", "5 MoritzLaurer-mDeBERTa-v3-base-xnli-multilingual-nli-2mil7 0.488889 0.833333 0.688373\n", "6 cross-encoder-nli-deberta-v3-large 0.466667 0.566667 0.541667\n", "7 facebook-bart-large-mnli 0.466667 0.708333 0.400000\n", "8 MoritzLaurer-mDeBERTa-v3-base-mnli-xnli 0.455556 0.408333 0.481250\n", "9 cross-encoder-nli-deberta-v3-base 0.444444 0.533333 0.712500\n", "10 joeddav-bart-large-mnli-yahoo-answers 0.355556 0.650000 0.553792\n", "11 pongjin-roberta_with_kornli 0.233333 0.666667 0.452857\n" ] } ], "source": [ "pd.set_option('display.max_columns', None) # show all columns\n", "pd.set_option('display.max_colwidth', None) # do not truncate cell contents\n", "pd.set_option('display.width', 200) \n", "\n", "perf_table = []\n", "# fill in for loop with perf_summary per model\n", "for model, result in all_results.items():\n", " row = pd.DataFrame(result[\"perf_summary\"]).T\n", " # row[\"model\"] = model\n", " row.insert(0, \"model\", model) # insert as first column\n", " perf_table.append(row)\n", "# Concatenate all into one table\n", "df_all = pd.concat(perf_table, ignore_index=True)\n", "df = df_all.sort_values(by=\"accuracy\", ascending=False).reset_index(drop=True)\n", "\n", "\n", "\n", "print(df)\n", "#print(type(df_all))\n", " \n", "\n", "# rank by accuracy\n" ] }, { "cell_type": "code", "execution_count": 25, "id": "222a70fc-8d3c-4ebb-9954-d5c72baed9e5", "metadata": {}, "outputs": [], "source": [ "# return packing list additionally to classes\n", "# Load packing item data\n", "with open(\"packing_templates_self_supported_offgrid_expanded.json\", \"r\") as file:\n", " packing_items = json.load(file)\n", "\n", "# function and gradio app\n", "def classify(model_name, trip_descr, cut_off = 0.5):\n", " classifier = pipeline(\"zero-shot-classification\", model=model_name)\n", " ## Create and fill dataframe with class predictions\n", " df = pd.DataFrame(columns=['superclass', 'pred_class'])\n", " for i, key in enumerate(keys_list):\n", " if key == 'activities':\n", " result = classifier(trip_descr, candidate_labels[key], multi_label=True)\n", " indices = [i for i, score in enumerate(result['scores']) if score > cut_off]\n", " classes = [result['labels'][i] for i in indices]\n", " else:\n", " result = classifier(trip_descr, candidate_labels[key])\n", " classes = result[\"labels\"][0]\n", " df.loc[i] = [key, classes]\n", "\n", " ## Look up and return list of items to pack based on class predictions\n", " # make list from dataframe column\n", " all_classes = [elem for x in df[\"pred_class\"] for elem in (x if isinstance(x, list) else [x])]\n", " # look up packing items for each class/key\n", " list_of_list_of_items = [packing_items.get(k, []) for k in all_classes]\n", " # combine lists and remove doubble entries\n", " flat_unique = []\n", " for sublist in list_of_list_of_items:\n", " for item in sublist:\n", " if item not in flat_unique:\n", " flat_unique.append(item)\n", " # sort alphabetically to notice duplicates\n", " sorted_list = sorted(flat_unique) \n", " return df, sorted_list" ] }, { "cell_type": "code", "execution_count": 26, "id": "0f7376bd-a50b-47cc-8055-48a6de5dfee6", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "( superclass pred_class\n", "0 activity_type beach vacation\n", "1 activities [going to the beach, relaxing, hiking]\n", "2 climate_or_season warm destination / summer\n", "3 style_or_comfort minimalist\n", "4 dress_code casual\n", "5 accommodation huts with half board\n", "6 transportation no own vehicle\n", "7 special_conditions off-grid / no electricity\n", "8 trip_length_days 7+ days, ['1 set kleding voor elke situatie', 'EHBO-set', 'USB-hub (voor meerdere devices)', 'aantal maaltijden/snacks afgestemd op duur', 'alles-in-één zeep', 'back-up verlichting (bijv. kleine zaklamp)', 'blarenpleisters of tape', 'boek of e-reader', 'comfortabele kleding', 'compacte tandenborstel', 'contant geld voor betalingen', 'dagrugzak', 'extra kledinglaag', 'extra opladerkabels', 'hiking sokken (anti-blaren)', 'hikingstokken', 'hoed of pet', 'hoofdlamp + extra batterijen', 'jeans of comfortabele broek', 'kleine rugzak', 'kleine toilettas', 'koeltas', 'lakenzak (vaak verplicht)', 'lichte handdoek', 'lichte pyjama of slaapkleding', 'lichte schoenen', 'lichtgewicht handdoek', 'luchtige kleding', 'muziek / koptelefoon', 'navigatie (kaart, kompas of GPS)', 'navigatieapparaat met offline kaarten', 'noodcommunicatie (bijv. GPS beacon of satellietboodschapper)', 'notitieboekje + pen', 'ondergoed per dag', 'oorstopjes', 'openbaar vervoer app of ticket', 'oplaadbare batterijen en oplader', 'opvouwbaar zonnepaneel (indien langere tochten)', 'pantoffels of slippers voor binnen', 'papieren kaart en kompas', 'pet of hoed', 'powerbank (minstens 10.000 mAh)', 'regenjas of poncho', 'reserveringsbevestiging', 'rugzak', 'slippers', 'snacks / energierepen', 'snacks voor onderweg', 'sneakers', 'sokken per dag', 'strandlaken', 'strandstoel', 'strandtas', 't-shirts', 'toilettas', 'trui of hoodie', 'verpakking om elektronica droog te houden', 'wandelschoenen of trailrunners', 'waterfles', 'waterfles of waterzak', 'zaklamp of hoofdlamp', 'zitkussen of strandmat', 'zonnebrand', 'zonnebrand en zonnebril', 'zonnebrandcrème', 'zonnebril', 'zonnecrème', 'zonnehoed', 'zonnepaneel of draagbaar laadsysteem', 'zwemkleding'])\n" ] } ], "source": [ "# Access the first trip description\n", "first_trip = trip_descriptions[0]\n", "tmp = classify(\"facebook/bart-large-mnli\", first_trip )\n", "print(tmp)" ] }, { "cell_type": "markdown", "id": "17483df4-55c4-41cd-b8a9-61f7a5c7e8a3", "metadata": {}, "source": [ "# Use gradio for user input" ] }, { "cell_type": "code", "execution_count": 2, "id": "5bf23e10-0a93-4b2f-9508-34bb0974d24c", "metadata": {}, "outputs": [], "source": [ "# Prerequisites\n", "from transformers import pipeline\n", "import json\n", "import pandas as pd\n", "import gradio as gr\n", "\n", "# get candidate labels\n", "with open(\"packing_label_structure.json\", \"r\") as file:\n", " candidate_labels = json.load(file)\n", "keys_list = list(candidate_labels.keys())\n", "\n", "# Load test data (in list of dictionaries)\n", "with open(\"test_data.json\", \"r\") as file:\n", " packing_data = json.load(file)\n", "\n", "# Load packing item data\n", "with open(\"packing_templates_self_supported_offgrid_expanded.json\", \"r\") as file:\n", " packing_items = json.load(file)" ] }, { "cell_type": "code", "execution_count": 3, "id": "61ebbe99-2563-4c99-ba65-d2312c9d5844", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7862\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "