File size: 18,522 Bytes
7b2757d f1a1f1c 7b2757d f1a1f1c 7b2757d f1a1f1c 7b2757d f1a1f1c 7b2757d f1a1f1c 7b2757d f1a1f1c 7b2757d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "cc7823e4",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\BILAL\\AppData\\Roaming\\Python\\Python37\\site-packages\\medcat\\cat.py:18: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",
" from tqdm.autonotebook import tqdm, trange\n",
"[nltk_data] Downloading package stopwords to\n",
"[nltk_data] C:\\Users\\BILAL\\AppData\\Roaming\\nltk_data...\n",
"[nltk_data] Package stopwords is already up-to-date!\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import pickle\n",
"import seaborn as sns\n",
"\n",
"from matplotlib import pyplot as plt\n",
"from medcat.cat import CAT\n",
"import re\n",
"from nltk.corpus import stopwords\n",
"import nltk\n",
"nltk.download('stopwords')"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "cb092ad7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'3.1.3'"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import spacy\n",
"spacy.__version__"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "8e4b9aee",
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (860621229.py, line 1)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"C:\\Users\\BILAL\\AppData\\Local\\Temp\\ipykernel_9408\\860621229.py\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m import torch-vision\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"import torch-vision"
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "a48a030f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'4.30.2'"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"transformers.__version__"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "135d2773",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'2021.2.3'"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import py2neo\n",
"py2neo.__version__"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "32876e6c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found an existing unziped model pack at: mc_modelpack_snomed_int_16_mar_2022_25be3857ba34bdd5, the provided zip will not be touched.\n",
"{\n",
" \"Model ID\": \"25be3857ba34bdd5\",\n",
" \"Last Modifed On\": \"16 March 2022\",\n",
" \"History (from least to most recent)\": [\n",
" \"a474096eb4566638\",\n",
" \"009617d7ff372682\"\n",
" ],\n",
" \"Description\": \"SNOMED INT enriched with UMLS and trained unsupervised on MIMIC-III\",\n",
" \"Source Ontology\": \"SnomedCT_InternationalRF2_PRODUCTION_20210131T120000Z\",\n",
" \"Location\": \"MedCAT Rosalind machine, available for public download from https://github.com/CogStack/MedCAT\",\n",
" \"MetaCAT models\": {\n",
" \"Status\": \"Detects is a concept Affirmed or Negated/Hypothetical\"\n",
" },\n",
" \"Basic CDB Stats\": {\n",
" \"Number of concepts\": 354448,\n",
" \"Number of names\": 2049216,\n",
" \"Number of concepts that received training\": 29674,\n",
" \"Number of seen training examples in total\": 20585988,\n",
" \"Average training examples per concept\": 693.7382220125362\n",
" },\n",
" \"Performance\": {\n",
" \"ner\": {},\n",
" \"meta\": {}\n",
" },\n",
" \"Important Parameters (Partial view, all available in cat.config)\": {\n",
" \"config.ner['min_name_len']\": {\n",
" \"value\": 3,\n",
" \"description\": \"Minimum detection length (found terms/mentions shorter than this will not be detected).\"\n",
" },\n",
" \"config.ner['upper_case_limit_len']\": {\n",
" \"value\": 4,\n",
" \"description\": \"All detected terms shorter than this value have to be uppercase, otherwise they will be ignored.\"\n",
" },\n",
" \"config.linking['similarity_threshold']\": {\n",
" \"value\": 0.2,\n",
" \"description\": \"If the confidence of the model is lower than this a detection will be ignore.\"\n",
" },\n",
" \"config.general['spell_check']\": {\n",
" \"value\": true,\n",
" \"description\": \"Is spell checking enabled.\"\n",
" },\n",
" \"config.general['spell_check_len_limit']\": {\n",
" \"value\": 7,\n",
" \"description\": \"Words shorter than this will not be spell checked.\"\n",
" }\n",
" }\n",
"}\n"
]
}
],
"source": [
"# Load model pack and Create CAT - the main class from medcat used for concept annotation\n",
"\n",
"model_pack_path = 'mc_modelpack_snomed_int_16_mar_2022_25be3857ba34bdd5'\n",
"cat = CAT.load_model_pack(model_pack_path)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "f0d57280",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3.7.16 (default, Jan 17 2023, 16:06:28) [MSC v.1916 64 bit (AMD64)]\n"
]
}
],
"source": [
"import sys\n",
"print(sys.version)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6b130c8c",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 5,
"id": "fe904215",
"metadata": {},
"outputs": [],
"source": [
"example = ' \\nName: ___ Unit No: ___\\n \\nAdmission Date: ___ Discharge Date: ___\\n \\nDate of Birth: ___ Sex: M\\n \\nService: ORTHOPAEDICS\\n \\nAllergies: \\nerythromycin base\\n \\nAttending: ___.\\n \\nChief Complaint:\\nLeft ankle fracture\\n \\nMajor Surgical or Invasive Procedure:\\nORIF left ankle ___\\n \\nHistory of Present Illness:\\n___ yr old man fall down 3 stairs while holding lumbar at \\nconstruction\\njob, resulting in immediate L ankle pain. ED ankle fracture, \\nsurgery performed\\n\\n \\nPast Medical History:\\nPrevious R ankle fracture\\nRLE cellulitis\\nOsteoarthritis\\n\\n \\nSocial History:\\n___\\nFamily History:\\nN/A\\n \\nPhysical Exam:\\nAOXO3\\nsplint intact, positive CSM\\nPain well controlled, no N/V\\n\\n \\nPertinent Results:\\n___ 08:28PM WBC-9.5 RBC-4.49* HGB-13.7 HCT-41.0 MCV-91 \\nMCH-30.5 MCHC-33.4 RDW-13.8 RDWSD-46.7*\\n___ 08:28PM GLUCOSE-96 UREA N-13 CREAT-0.7 SODIUM-145 \\nPOTASSIUM-4.1 CHLORIDE-108 TOTAL CO2-24 ANION GAP-13\\n___ 08:28PM CALCIUM-9.0 PHOSPHATE-3.5 MAGNESIUM-1.9\\n \\nBrief Hospital Course:\\nTaken to operating room and underwent surgical fixation of ankle \\nfracture on ___. No complications. Post op doing well, pain \\nwell controlled. Cleared by ___ to go home without services\\n \\nMedications on Admission:\\nThe Preadmission Medication list is accurate and complete.\\n1. Multivitamins 1 TAB PO DAILY \\n2. Naproxen 500 mg PO Q8H:PRN Pain - Mild \\n\\n \\nDischarge Medications:\\n1. Acetaminophen 1000 mg PO Q8H \\nRX *acetaminophen 500 mg 2 tablet(s) by mouth every eight (8) \\nhours Disp #*40 Tablet Refills:*0 \\n2. Aspirin 325 mg PO DAILY \\nRX *aspirin 325 mg 1 tablet(s) by mouth once a day Disp #*14 \\nTablet Refills:*0 \\n3. Docusate Sodium 100 mg PO BID \\nRX *docusate sodium 100 mg 1 capsule(s) by mouth twice a day \\nDisp #*30 Capsule Refills:*0 \\n4. Ondansetron 4 mg PO Q8H:PRN severe nausea \\nRX *ondansetron 4 mg 1 tablet(s) by mouth every six (6) hours \\nDisp #*8 Tablet Refills:*0 \\n5. OxyCODONE (Immediate Release) ___ mg PO Q4H:PRN Pain - \\nModerate \\nRX *oxycodone 5 mg ___ tablet(s) by mouth every four (4) hours- \\n(6) hours Disp #*60 Tablet Refills:*0 \\n6. Multivitamins 1 TAB PO DAILY \\n\\n \\nDischarge Disposition:\\nHome\\n \\nDischarge Diagnosis:\\nleft ankle fracture, s/p ORIF ___\\n \\nDischarge Condition:\\nMental Status: Clear and coherent.\\nLevel of Consciousness: Alert and interactive.\\nActivity Status: Ambulatory - Independent.\\n \\nDischarge Instructions:\\nNWB to LLE\\nKeep splint dry, in place\\nElevate LLE\\nFollow up in ___ clinic in 2 weeks\\n \\nFollowup Instructions:\\n___\\n'"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "5569c580",
"metadata": {},
"outputs": [],
"source": [
"medical_stopwords = stopwords.words(\"english\")\n",
"\n",
"\n",
"medical_stopwords.extend(['speaking', 'none', 'time', 'flush'])\n",
"\n",
"def process_clinical_note(clinical_note):\n",
" # Define the sections to remove\n",
" sections_to_remove = [\n",
" \"Name:\",\n",
" \"Unit No:\",\n",
" \"Admission Date:\",\n",
" \"Discharge Date:\",\n",
" \"Date of Birth:\",\n",
" \"Sex:\",\n",
" \"Service:\",\n",
" \"Allergies:\",\n",
" \"Attending:\",\n",
" \"Past Medical History:\",\n",
" \"Social History:\",\n",
" \"Family History:\",\n",
" \"Vitals:\",\n",
" \"Pertinent Results:\",\n",
" \"Medications on Admission:\",\n",
" \"Discharge Medications:\",\n",
" \"Discharge Disposition:\",\n",
" \"Discharge Condition:\",\n",
" \"Discharge Instructions:\",\n",
" \"Followup Instructions:\"\n",
" ]\n",
"\n",
" # Split the clinical note into lines\n",
" lines = clinical_note.split('\\n')\n",
"\n",
" # Initialize the processed note\n",
" processed_note = []\n",
"\n",
" # Flag to exclude lines within unwanted sections\n",
" exclude_section = False\n",
"\n",
" # Iterate through the lines and filter unwanted sections\n",
" for line in lines:\n",
" if any(section in line for section in sections_to_remove):\n",
" exclude_section = True\n",
" elif line.strip() == \"\":\n",
" # Empty lines separate sections, so reset the flag\n",
" exclude_section = False\n",
"\n",
" if not exclude_section:\n",
" processed_note.append(line)\n",
"\n",
" # Join the lines to create the final note\n",
" final_note = '\\n '.join(processed_note)\n",
" \n",
" sections_to_remove = [\n",
" r'chief complaint',\n",
" r'history of present illness',\n",
" r'Major Surgical or Invasive Procedure',\n",
" r'physical exam',\n",
" r'brief hospital course',\n",
" r'Discharge',\n",
" \n",
" r'completed by',\n",
" ]\n",
" \n",
" for pattern in sections_to_remove:\n",
" final_note = re.sub(pattern, '', final_note, flags=re.IGNORECASE)\n",
"\n",
" # Define patterns to identify negations\n",
" negation_patterns = [\n",
" r'no\\s+\\w+',\n",
" r'not\\s+\\w+',\n",
" r'did\\s+not\\s+have\\s+\\w+'\n",
" ]\n",
" \n",
" # Filter out sentences with negations\n",
" sentences = [sentence for sentence in final_note.split('\\n') if not any(re.search(pattern, sentence, re.IGNORECASE) for pattern in negation_patterns)]\n",
"\n",
" # Remove keys and special characters\n",
" cleaned_note = re.sub(r'\\w+:', '', '\\n'.join(sentences), flags=re.IGNORECASE) # Remove keys (case-insensitive)\n",
" cleaned_note = re.sub(r'[^a-zA-Z\\s]', '', cleaned_note) # Remove special characters\n",
" # Tokenize the note into sentences based on '\\n'\n",
" sentences = [sentence.strip() for sentence in cleaned_note.split('\\n') if sentence.strip()]\n",
"\n",
" # Remove stop words and empty sentences\n",
" sentences = [\n",
" ' '.join(word for word in sentence.split() if word.lower() not in medical_stopwords)\n",
" for sentence in sentences\n",
" ]\n",
" sentences = [item for item in sentences if item != '']\n",
" \n",
" final_text = '. '.join(sentence for sentence in sentences)\n",
" return final_text"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "71ea5560",
"metadata": {},
"outputs": [],
"source": [
"processed_example = process_clinical_note(example)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "62d9f235",
"metadata": {},
"outputs": [],
"source": [
"icd10_data = {\n",
" 'hadm_id': [],\n",
" 'icd10_codes': [],\n",
" 'text': []\n",
"}\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "83b2c3df",
"metadata": {},
"outputs": [],
"source": [
"# Get the entities from the text\n",
"all_entities = cat.get_entities(processed_example)\n",
"\n",
"icd_codes = set() # Using a set to automatically remove duplicates\n",
"\n",
"for entity_id, entity_data in all_entities['entities'].items():\n",
" icd10 = entity_data.get('icd10', [])\n",
" for code in icd10:\n",
" if code: # Check if the code is not an empty string\n",
" icd_codes.add(code)\n",
"\n",
"icd10_data['hadm_id'].append('dummy_example')\n",
"icd10_data['icd10_codes'].append(list(icd_codes))\n",
"icd10_data['text'].append(processed_example)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "e61ad6af",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>hadm_id</th>\n",
" <th>icd10_codes</th>\n",
" <th>text</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>dummy_example</td>\n",
" <td>[S82.80, M79.67]</td>\n",
" <td>Left ankle fracture. ORIF left ankle. yr old m...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" hadm_id icd10_codes \\\n",
"0 dummy_example [S82.80, M79.67] \n",
"\n",
" text \n",
"0 Left ankle fracture. ORIF left ankle. yr old m... "
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create a DataFrame from the processed data\n",
"df_icd10 = pd.DataFrame(icd10_data)\n",
"df_icd10"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "5ac99ff1",
"metadata": {},
"outputs": [],
"source": [
"def reformat(code):\n",
" code = ''.join(code.split('.'))\n",
" code = code[:3] + '.'\n",
" return code"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "7acd717d",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>hadm_id</th>\n",
" <th>icd10_codes</th>\n",
" <th>text</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>dummy_example</td>\n",
" <td>[S82., M79.]</td>\n",
" <td>Left ankle fracture. ORIF left ankle. yr old m...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" hadm_id icd10_codes \\\n",
"0 dummy_example [S82., M79.] \n",
"\n",
" text \n",
"0 Left ankle fracture. ORIF left ankle. yr old m... "
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_icd10['icd10_codes'] = df_icd10['icd10_codes'].apply(lambda lst: [reformat(x) for x in lst])\n",
"df_icd10"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.7.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|