Spaces:
Running
Running
File size: 5,671 Bytes
57fbf67 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 48,
"id": "7aaceacb",
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"from app.config import DATASET_PATH, MODEL_SOURCE\n",
"from app.utils import load_dataset, load_model_and_tokenizer, preprocess\n",
"from scipy.special import softmax\n"
]
},
{
"cell_type": "code",
"execution_count": 49,
"id": "7defab3e",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Some weights of the model checkpoint at cardiffnlp/twitter-roberta-base-sentiment-latest were not used when initializing RobertaForSequenceClassification: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n",
"- This IS expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
"- This IS NOT expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
]
}
],
"source": [
"tokenizer, model = load_model_and_tokenizer(MODEL_SOURCE)\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "0a1dcfdd",
"metadata": {},
"outputs": [],
"source": [
"dataset = load_dataset(DATASET_PATH).shuffle()[\"test\"][:N_SAMPLES]\n"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "501e6728",
"metadata": {},
"outputs": [],
"source": [
"import torch"
]
},
{
"cell_type": "code",
"execution_count": 47,
"id": "82b25de1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"N_BEVAL_BATCH_SIZE = 64\n",
"N_SAMPLES = 500\n",
"N_BATCHES = len(dataset[\"text\"])//EVAL_BATCH_SIZE\n",
"N_BATCHES"
]
},
{
"cell_type": "code",
"execution_count": 54,
"id": "7dd5371b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 64\n",
"64 128\n",
"128 192\n",
"192 256\n",
"256 320\n",
"320 384\n",
"384 448\n",
"448 500\n"
]
},
{
"data": {
"text/plain": [
"np.float64(0.71)"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"EVAL_BATCH_SIZE = 64\n",
"N_SAMPLES = 500\n",
"def evaluate_accuracy():\n",
"\n",
" dataset = load_dataset(DATASET_PATH).shuffle()[\"test\"][:N_SAMPLES]\n",
" N_BATCHES = len(dataset[\"text\"])//EVAL_BATCH_SIZE\n",
"\n",
" accuracy = 0\n",
" for i in range(N_BATCHES+1):\n",
"\n",
" start = i*EVAL_BATCH_SIZE\n",
" end = min(N_SAMPLES, (i+1)*EVAL_BATCH_SIZE)\n",
" print(start, end)\n",
" samples, labels = dataset[\"text\"][start:end], dataset[\"label\"][start:end]\n",
" \n",
" model.eval()\n",
" encoded_batch = tokenizer(\n",
" [preprocess(t) for t in samples],\n",
" padding=True, # pad to same length\n",
" truncation=True, # truncate long texts\n",
" return_tensors=\"pt\",\n",
" )\n",
"\n",
" with torch.no_grad():\n",
" output = model(**encoded_batch)\n",
" \n",
" logits = output[0].detach().cpu().numpy()\n",
" scores = softmax(logits, axis=-1)\n",
" pred_labels = scores.argmax(axis=-1)\n",
" accuracy += sum(pred_labels==labels)\n",
" accuracy/=N_SAMPLES\n",
" return accuracy\n",
"evaluate_accuracy()"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "dbd3bb8c",
"metadata": {},
"outputs": [],
"source": [
"def _load_test_data():\n",
" \"\"\"\n",
" Expects CSV with columns: text,label\n",
" label values must be one of labels (negative, neutral, positive) or their indices (0,1,2).\n",
" \"\"\"\n",
" df = pd.read_csv(TEST_DATA_PATH)\n",
" # normalize label column to strings matching our 'labels' list\n",
" if np.issubdtype(df[\"label\"].dtype, np.number):\n",
" df[\"label\"] = df[\"label\"].astype(int).map(lambda i: labels[i])\n",
" else:\n",
" df[\"label\"] = df[\"label\"].str.lower().str.strip()\n",
" # keep only supported labels\n",
" df = df[df[\"label\"].isin(labels)].dropna(subset=[\"text\", \"label\"])\n",
" return df"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ec0b086e",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "800c8018",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "ProjectEnv",
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|