{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# <h1 align = \"center\"><div style = \"background-color: #6600cc; color:white;font-weight:bold; border-radius: 15px; padding: 20px; margin: 2px;\">🧠HuBMAP + HPA - Hacking the Human Body🫁🫁</div></h1>\n<img src = \"https://images.unsplash.com/photo-1638272467190-4ff6f773315c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1015&q=80\" width = 100%>","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 15px; padding: 20px; margin: 2px;\"><b><span>📗1 | Story</span></b></div></h2>\n\n <div style=\"background:#1a0033   ;font-family: mono;font-size:15px;color:  #f2f2f2;padding:30px\" >\n <p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">   \n <b style=\"font-size:30px\">W</b>hen you think of “life hacks,” normally you’d imagine productivity techniques. But how about the kind that helps you understand your body at a molecular level? It may be possible! Researchers must first determine the function and relationships among the 37 trillion cells that make up the human body. A better understanding of our cellular composition could help people live healthier, longer lives.\n <p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">'''\nA previous Kaggle competition aimed to annotate cell population neighborhoods that perform an organ’s main physiologic function, also called functional tissue units (FTUs). Manually annotating FTUs (e.g., glomeruli in kidney or alveoli in the lung) is a time-consuming process. In the average kidney, there are over 1 million glomeruli FTUs. While there are existing cell and FTU segmentation methods, we want to push the boundaries by building algorithms that generalize across different organs and are robust across different dataset differences.\n\n\n <p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">'''The Human BioMolecular Atlas Program (HuBMAP) is working to create a Human Reference Atlas at the cellular level. Sponsored by the National Institutes of Health (NIH), HuBMAP and Indiana University’s Cyberinfrastructure for Network Science Center (CNS) have partnered with institutions across the globe for this endeavor. A major partner is the Human Protein Atlas (HPA), a Swedish research program aiming to map the protein expression in human cells, tissues, and organs, funded by the Knut and Alice Wallenberg Foundation.\n\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">  '''In this competition, you’ll identify and segment functional tissue units (FTUs) across five human organs. You'll build your model using a dataset of tissue section images, with the best submissions segmenting FTUs as accurately as possible.\n\n\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">'''If successful, you'll help accelerate the world’s understanding of the relationships between cell and tissue organization. With a better idea of the relationship of cells, researchers will have more insight into the function of cells that impact human health. Further, the Human Reference Atlas constructed by HuBMAP will be freely available for use by researchers and pharmaceutical companies alike, potentially improving and prolonging human life.\n","metadata":{}},{"cell_type":"markdown","source":"# <div style = \"background-color: #6600cc; color:white; border-radius: 15px; padding: 20px; margin: 2px;\"><b><span>💿1 | Data</span></b></div>","metadata":{}},{"cell_type":"markdown","source":"# <h2> <div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍1.1 |Importing Libraries</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"import numpy as np #linear algebra\nimport pandas as pd #data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\nimport random\nimport warnings\nfrom matplotlib.font_manager import FontProperties\nwarnings.filterwarnings('ignore')\nimport optuna\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\nfrom PIL import Image\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import  BaggingClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn import metrics\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.preprocessing import PowerTransformer\nfrom lightgbm import LGBMClassifier\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn import preprocessing\nfrom sklearn.linear_model import LogisticRegression\n\nimport cv2\nimport tifffile\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import plot_roc_curve","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:16.581790Z","iopub.execute_input":"2022-06-25T17:35:16.582446Z","iopub.status.idle":"2022-06-25T17:35:19.004712Z","shell.execute_reply.started":"2022-06-25T17:35:16.582404Z","shell.execute_reply":"2022-06-25T17:35:19.003263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍1.2 |Data Description</span></b></div></h2>\n\n <div style=\"background:#1a0033   ;font-family: mono;font-size:15px;color:  #f2f2f2;padding:30px\" >\n  <p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">   \n <b style=\"font-size:30px\">T</b>he goal of this competition is to identify the locations of each functional tissue unit (FTU) in biopsy slides from several different organs. The underlying data includes imagery from different sources prepared with different protocols at a variety of resolutions, reflecting typical challenges for working with medical data.\n <p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">\nThis competition uses data from two different consortia, the Human Protein Atlas (HPA) and Human BioMolecular Atlas Program (HuBMAP). The training dataset consists of data from public HPA data, the public test set is a combination of private HPA data and HuBMAP data, and the private test set contains only HuBMAP data. Adapting models to function properly when presented with data that was prepared using a different protocol will be one of the core challenges of this competition. While this is expected to make the problem more difficult, developing models that generalize is a key goal of this endeavor.</p>\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\"> This competition uses a hidden test. When your submitted notebook is scored the actual test data (including a full length sample submission) will be made available to your notebook.</p>     \n\n<br><b>Files:</b>\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\"><b>[train/test].csv  Metadata for the train/test set. Only the first few rows of the test set are available for download.</b>\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">\n    <ul>\n<li><b>id </b> = The image ID.\n<li><b>organ</b> = The organ that the biopsy sample was taken from.\n<li><b>data_source</b> =  Whether the image was provided by Hubamp or HPA.\n<li><b>img_height</b> = The height of the image in pixels.\n<li><b>img_width</b> =The width of the image in pixels.\n<li><b>pixel_size</b> =The height/width of a single pixel from this image in micrometers. All HPA images have a pixel size of 0.4 µm. For Hubmap imagery the pixel size is 0.5 µm for kidney, 0.2290 µm for large intestine, 0.7562 µm for lung, 0.4945 µm for spleen, and 6.263 µm for prostate.\n<li><b>tissue_thickness</b> =The thickness of the biopsy sample in micrometers. All HPA images have a thickness of 4 µm. The Hubmap samples have tissue slice thicknesses 10 µm for kidney, 8 µm for large intestine, 4 µm for spleen, 5 µm for lung, and 5 µm for prostate.\n<li><b>rle </b> =The target column. A run length encoded copy of the annotations. Provided for the training set only.\n<li><b>age</b> =The patient's age in years. Provided for the training set only.\n<li><b>sex</b> =The sex of the patient. Provided for the training set only.   \n </ul>   \n    \n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\"><b>sample_submission.csv</b>\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">\n  <ul>\n<li><b>id </b> = The image ID.\n<li><b> rle  </b> = T A run length encoded mask of the FTUs in the image.\n\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\"><i>\n[train/test]_images/ The images. Expect roughly 550 images in the hidden test set. All HPA images are 3000 x 3000 pixels with a tissue area within the image around 2500 x 2500 pixels. The Hubmap images range in size from 4500x4500 down to 160x160 pixels. HPA samples were stained with antibodies visualized with 3,3'-diaminobenzidine (DAB) and counterstained with hematoxylin. HuBMAP images were prepared using Periodic acid-Schiff (PAS)/hematoxylin and eosin (H&E) stains. All images used have at least one FTU. All tissue data used in this competition is from healthy donors that pathologists identified as pathologically unremarkable tissue.</i>\n\n<p style=\"font-family: mono;font-size:15px;color:  #f2f2f2\">train_annotations/ The annotations provided in the format of points that define the boundaries of the polygon masks of the FTUs.\n    \n    \n    \n    \n    \n    \n    \n\n","metadata":{}},{"cell_type":"markdown","source":"<body>\n\n<table style=\"width:100%\">\n  <tr>\n    <th style=\" font-size: 20px;padding:20px\", bgcolor='#6600cc'>Feature</th>\n    <th style=\" font-size: 20px\", bgcolor='#6600cc'>Description</th> \n    \n  </tr>\n  <tr>\n      <td style=\" font-size: 17px ;padding:20px \"><b>id</b></td>\n      <td style=\"font-size: 17px\">The image ID.</td>\n    </tr>\n      <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>organ </b></td>\n      <td style=\"font-size: 17px\">The organ that the biopsy sample was taken from.</td>\n    </tr>\n          <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>data_source* </b></td>\n      <td style=\"font-size: 17px\">Whether the image was provided by Hubamp or HPA.</td>\n    </tr>\n       <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>img_height</b></td>\n      <td style=\"font-size: 17px\">The height of the image in pixels. </td>\n    </tr>\n  <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>img_width*</b></td>\n      <td style=\"font-size: 17px\">The width of the image in pixels.</td>\n    </tr>\n  <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>pixel_size</b></td>\n      <td style=\"font-size: 17px\">The height/width of a single pixel from this image in micrometers. All HPA images have a pixel size of 0.4 µm. For Hubmap imagery the pixel size is 0.5 µm for kidney, 0.2290 µm for large intestine, 0.7562 µm for lung, 0.4945 µm for spleen, and 6.263 µm for prostate.</td>\n    </tr>\n      <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>tissue_thickness</b></td>\n      <td style=\"font-size: 17px\">The thickness of the biopsy sample in micrometers. All HPA images have a thickness of 4 µm. The Hubmap samples have tissue slice thicknesses 10 µm for kidney, 8 µm for large intestine, 4 µm for spleen, 5 µm for lung, and 5 µm for prostate.</td>\n    </tr>\n      <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>rle</b></td>\n      <td style=\"font-size: 17px\">The target column. A run length encoded copy of the annotations. Provided for the training set only</td>\n    </tr>\n      <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>age</b></td>\n      <td style=\"font-size: 17px\">The patient's age in years. Provided for the training set only.</td>\n    </tr>\n      <tr>\n      <td style=\" font-size: 17px;padding:20px\"><b>sex</b></td>\n      <td style=\"font-size: 17px\">The sex of the patient. Provided for the training set only.  </td>\n    </tr>\n    \n</table>\n\n</body>\n","metadata":{}},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍1.3 |Reading Data</span></b></div></h2>\n1. ","metadata":{}},{"cell_type":"code","source":"BASE_DIR = \"../input/hubmap-organ-segmentation\"\nTRAIN_DIR = \"../input/hubmap-organ-segmentation/train_images\"\nTEST_DIR = \"../input/hubmap-organ-segmentation/test_images\"\nLABEL_DIR = \"../input/hubmap-organ-segmentation/train_annotations\"\ntrain_df = pd.read_csv(os.path.join(BASE_DIR, \"train.csv\"))","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:19.007299Z","iopub.execute_input":"2022-06-25T17:35:19.007724Z","iopub.status.idle":"2022-06-25T17:35:19.314676Z","shell.execute_reply.started":"2022-06-25T17:35:19.007689Z","shell.execute_reply":"2022-06-25T17:35:19.313570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":" <div style=\"background:#1a0033   ;font-family: mono;font-size:15px;color:  white;padding:30px\" > <b>Note</b>:Analysis will be based on training dataset only</div>\n\n\n    ","metadata":{}},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍1.31 |Number Of Training Samples</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"\ndef overview(df):\n    num_rows=len(df.index)\n    num_col=len(df.columns)\n    fig, ax = plt.subplots()\n      \n    #create values for table\n    lab = ['Number Of Rows', 'Number Of Columns']\n    table_data=[\n    [num_rows,num_col]\n        ]\n    ax.set_title('Samples', \n             fontweight =\"bold\") \n    #create table\n   \n    table = ax.table(cellText=table_data, colLabels=lab,colColours =[\"#6600cc\"] * 10, loc='center')\n    for i in enumerate(lab):\n        table[(0, i[0])].get_text().set_color('white')\n        \n    for (row, col), cell in table.get_celld().items():\n                if (row == 0):\n                    cell.set_text_props(fontproperties=FontProperties(weight='bold',size=25))    \n    #modify table\n    table.set_fontsize(14)\n    table.scale(2,4)\n    ax.axis('off')\n    #display table\n    plt.show()\n    \noverview(train_df) ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:19.317196Z","iopub.execute_input":"2022-06-25T17:35:19.318276Z","iopub.status.idle":"2022-06-25T17:35:19.498502Z","shell.execute_reply.started":"2022-06-25T17:35:19.318240Z","shell.execute_reply":"2022-06-25T17:35:19.497067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍1.32 |General Informations</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"def info(df):\n    missing= train_df.isnull().sum()\n    percent_missing = (train_df.isnull().sum() * 100 / len(train_df)).round(2)\n    dtypes=train_df.dtypes\n    data=df\n    data=pd.DataFrame([np.array(list(train_df.columns)).T,np.array(list(missing)).T,np.array(list(percent_missing)).T,np.array(list(dtypes)).T])\n    data = data.transpose()\n    data.columns=['Features','Num of Missing values','percentage Missing','DataType']\n   \n    fig, ax = plt.subplots()\n      \n    #create values for tabl\n\n    #create table\n    ax.set_title(\"General Informations\", fontsize=40, y=2.2)\n    table = ax.table(cellText=data.values, colLabels=data.columns,colColours =[\"#6600cc\"] * len(data.columns), loc='center')\n    for i in enumerate(data.columns):\n                    table[(0, i[0])].get_text().set_color('white')\n\n    for (row, col), cell in table.get_celld().items():\n                if (row == 0):\n                    cell.set_text_props(fontproperties=FontProperties(weight='bold',size=30))\n\n\n    #modify table\n    table.set_fontsize(14)\n    table.scale(5,5)\n    ax.axis('off')\n    #display table\n  \n    plt.show()\ninfo(train_df)   ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:19.502253Z","iopub.execute_input":"2022-06-25T17:35:19.502840Z","iopub.status.idle":"2022-06-25T17:35:20.005266Z","shell.execute_reply.started":"2022-06-25T17:35:19.502779Z","shell.execute_reply":"2022-06-25T17:35:20.004126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍1.33 |Null values</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"\"\"\"What are the counts of missing values in train ?\"\"\"\ndef missing(df):\n        ncounts = (pd.DataFrame([df.isnull().sum() * 100 / len(df)]).T).round(2) \n        ncounts = ncounts.rename(columns={0: \"train_missing\"})\n        margin = 0.60\n        #width = (1.-2.*margin)/len(train_df.columns)\n        ax=ncounts.sort_values('train_missing', ascending=True).plot(\n            kind=\"barh\", figsize=(8, 12), color='#8a3cf6' ,title=\"% of Values Missing\"\n        )\n\n        ax.bar_label(ax.containers[0])\n        plt.tight_layout()\n        plt.show()\n        \nmissing(train_df)        ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:20.006837Z","iopub.execute_input":"2022-06-25T17:35:20.007458Z","iopub.status.idle":"2022-06-25T17:35:20.370110Z","shell.execute_reply.started":"2022-06-25T17:35:20.007422Z","shell.execute_reply":"2022-06-25T17:35:20.369134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 15px; padding: 20px; margin: 2px;\"><b><span>💿2 | EDA</span></b></div></h2>","metadata":{}},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍2.1 |Univariate analysis</span></b></div></h2>\n","metadata":{}},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍2.11 | Age analysis</span></b></div></h2>\n","metadata":{}},{"cell_type":"code","source":"def hist(col,title):\n    \n    plt.figure(figsize = (10,8))\n    \n    ax = sns.histplot(col,kde=False);\n    \n    values = np.array([patch.get_height() for patch in ax.patches])\n    \n    #normalizing the values to get a range of colours\n    norm = plt.Normalize(values.min(), values.max())\n    \n    #range of colours from colourmap-rainbow\n    colors = plt.cm.RdPu(norm(values))\n    ax.grid(False)\n    #set colour for each patch\n    for patch, color in zip(ax.patches, colors):\n        patch.set_color(color)\n\n    plt.title(title, size = 20)\n    \nhist(train_df['age'],'Distribution of Age')","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:20.371589Z","iopub.execute_input":"2022-06-25T17:35:20.371891Z","iopub.status.idle":"2022-06-25T17:35:20.620251Z","shell.execute_reply.started":"2022-06-25T17:35:20.371865Z","shell.execute_reply":"2022-06-25T17:35:20.618961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍2.12 | Categorical Variables analysis</span></b></div></h2>\n","metadata":{}},{"cell_type":"code","source":"def pie_target(feat,df):\n    fig, ax = plt.subplots(3,2,figsize=(22,22))\n    for i in enumerate(feat):\n        \n            colors = [\"#570990\",\"#e4b6fe\",'#8b22ba', \"#8a3cf6\"]\n            fig.suptitle('Pie chart and Count Plot', size = 29)\n            ax[i[0],0].title.set_text(f'Pie of {i[1]}')\n            labels = list(df[i[1]].value_counts().index)\n            values = df[i[1]].value_counts()\n            \n            ax[i[0],0].pie( values,colors=colors,startangle=60, labels=labels,autopct='%1.0f%%', pctdistance=0.6)\n            ax[i[0],1].title.set_text(f'Count Plot for {i[1]}')\n            sns.countplot(x=i[1],data=df,palette=colors ,ax=ax[i[0],1])\n            ax[i[0],0].add_artist(plt.Circle((0,0),0.4,fc='white'))\n    fig.tight_layout()        \n    plt.show()\ncat_features=['organ','sex','data_source']\n\npie_target(cat_features,train_df)","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:20.621566Z","iopub.execute_input":"2022-06-25T17:35:20.621843Z","iopub.status.idle":"2022-06-25T17:35:21.430508Z","shell.execute_reply.started":"2022-06-25T17:35:20.621817Z","shell.execute_reply":"2022-06-25T17:35:21.429414Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍2.2 |Bivariate analysis</span></b></div></h2>\n","metadata":{}},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍2.21 | Sex vs Organs</span></b></div></h2>\n","metadata":{}},{"cell_type":"code","source":"cat_features=['organ']\nplt.figure(figsize = (18,18))\ndef rel_tar(df,feat_list,target):\n    \n        for i in enumerate(feat_list):\n                colors = [ \"#570990\",\"#e4b6fe\",'#8b22ba', \"#8a3cf6\", '#967032', '#2734DE'] \n                rand_col = colors[random.sample(range(6),1)[0]]\n                plt.subplot(2,2,i[0]+1)\n                sns.countplot(x=i[1], data=df, hue=target,palette=colors)\n                plt.title (i[1]+f' vs {target}')\n                plt.xlabel(\" \")\n                plt.ylabel(\" \")\n                plt.xticks(rotation = 45)\n                plt.tight_layout()\n                \n                \nrel_tar(train_df,cat_features,'sex')   ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:21.432140Z","iopub.execute_input":"2022-06-25T17:35:21.432534Z","iopub.status.idle":"2022-06-25T17:35:21.725564Z","shell.execute_reply.started":"2022-06-25T17:35:21.432498Z","shell.execute_reply":"2022-06-25T17:35:21.724143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍2.22 | Age vs Sex</span></b></div></h2>\n","metadata":{}},{"cell_type":"code","source":"cat_features=['age']\nplt.figure(figsize = (18,18))\ndef rel_tar(df,feat_list,target):\n    \n        for i in enumerate(feat_list):\n                colors = [ \"#570990\",\"#e4b6fe\",'#8b22ba', \"#8a3cf6\", '#967032', '#2734DE'] \n                rand_col = colors[random.sample(range(6),1)[0]]\n                plt.subplot(2,2,i[0]+1)\n               # sns.countplot(x=i[1], data=df, hue=target,palette=colors)\n                sns.histplot(x=\"age\", hue=\"sex\", multiple=\"stack\", kde=True, data=df,palette=colors[:2])\n                plt.title (i[1]+f' vs {target}')\n                plt.xlabel(\" \")\n                plt.ylabel(\" \")\n                plt.xticks(rotation = 45)\n                plt.tight_layout()\n                \n                \nrel_tar(train_df,cat_features,'sex')   ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:21.727434Z","iopub.execute_input":"2022-06-25T17:35:21.727855Z","iopub.status.idle":"2022-06-25T17:35:22.139665Z","shell.execute_reply.started":"2022-06-25T17:35:21.727815Z","shell.execute_reply":"2022-06-25T17:35:22.138869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍2.23 | Organs vs Age</span></b></div></h2>\n","metadata":{}},{"cell_type":"code","source":"cat_features=['age']\nplt.figure(figsize = (18,18))\ndef rel_tar(df,feat_list,target):\n    \n        for i in enumerate(feat_list):\n                colors = [ \"#570990\",\"#e4b6fe\",'#8b22ba', \"#8a3cf6\", '#967032', '#2734DE'] \n                rand_col = colors[random.sample(range(6),1)[0]]\n                plt.subplot(2,2,i[0]+1)\n               # sns.countplot(x=i[1], data=df, hue=target,palette=colors)\n                sns.histplot(x=\"age\", hue=\"organ\", multiple=\"stack\", kde=True, data=df,palette=colors[:5])\n                plt.title (i[1]+f' vs {target}')\n                plt.xlabel(\" \")\n                plt.ylabel(\" \")\n                plt.xticks(rotation = 45)\n                plt.tight_layout()\n                \n                \nrel_tar(train_df,cat_features,'organ')   ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T17:35:22.142124Z","iopub.execute_input":"2022-06-25T17:35:22.143017Z","iopub.status.idle":"2022-06-25T17:35:22.713755Z","shell.execute_reply.started":"2022-06-25T17:35:22.142984Z","shell.execute_reply":"2022-06-25T17:35:22.712582Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍3 |Images</span></b></div></h2>\n","metadata":{}},{"cell_type":"markdown","source":" <div style=\"background:#1a0033   ;font-family: mono;font-size:15px;color:  white;padding:30px\" > <b>Note</b>:The underlying data includes imagery from different sources prepared with different protocols at a variety of resolutions, reflecting typical challenges for working with medical data.</div>\n\n\n    ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T11:04:03.397477Z","iopub.execute_input":"2022-06-25T11:04:03.398526Z","iopub.status.idle":"2022-06-25T11:04:03.408958Z","shell.execute_reply.started":"2022-06-25T11:04:03.398474Z","shell.execute_reply":"2022-06-25T11:04:03.407487Z"}}},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍3.1 |Sample Images And Masks</span></b></div></h2>\n","metadata":{}},{"cell_type":"code","source":"# Reference : https://www.kaggle.com/code/ishandutta/hubmap-complete-understanding-and-eda-w-b\ndef rle2mask(mask_rle, shape=(1600,256)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (width,height) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n    return img.reshape(shape).T\ndef sample_img(images_list,train_df,title):\n    \n        fig, ax = plt.subplots(5,3,figsize=(22,22))\n        for i in enumerate(five_samples):\n            \n                colors = [\"#570990\",\"#e4b6fe\",'#8b22ba', \"#8a3cf6\"]\n                fig.suptitle(f'Plotting {title}', size = 25,y=1.01)\n                ax[i[0],0].title.set_text(f'Sample id : {i[1]}')\n                ax[i[0],1].title.set_text(f'Mask of id :{i[1]}')\n                ax[i[0],2].title.set_text(f'(Mask + Image) id : {i[1]}')\n                im = Image.open(images_list[i[0]])\n                mask=rle2mask(train_df[train_df[\"id\"]==i[1]][\"rle\"].iloc[-1], (im.size[1], im.size[0]))\n                ax[i[0],0].imshow(im)\n                ax[i[0],1].imshow(mask)\n                ax[i[0],2].imshow( im)\n                ax[i[0],2].imshow(mask, cmap='jet', alpha=0.5)\n                ax[i[0],2].axis('off')\n                ax[i[0],1].axis('off')\n                ax[i[0],0].axis('off')\n                \n        fig.tight_layout() \n        plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:48:43.330241Z","iopub.execute_input":"2022-06-25T19:48:43.330918Z","iopub.status.idle":"2022-06-25T19:48:43.349067Z","shell.execute_reply.started":"2022-06-25T19:48:43.330874Z","shell.execute_reply":"2022-06-25T19:48:43.348303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"five_samples=random.sample(list(train_df['id']),5)\nimages_list=[]\nfor sample in five_samples:\n    images_list.append(f\"../input/hubmap-organ-segmentation/train_images/{sample}.tiff\")\n\nsample_img(images_list,train_df,'random images')        \n        ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:48:46.320882Z","iopub.execute_input":"2022-06-25T19:48:46.321539Z","iopub.status.idle":"2022-06-25T19:49:06.444916Z","shell.execute_reply.started":"2022-06-25T19:48:46.321500Z","shell.execute_reply":"2022-06-25T19:49:06.443794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍3.2|Prostate</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"filtered_df = train_df.query('organ==\"prostate\"')\nfive_samples=random.sample(list(filtered_df ['id']),5)\nimages_list=[]\nfor sample in five_samples:\n    images_list.append(f\"../input/hubmap-organ-segmentation/train_images/{sample}.tiff\")\n\nsample_img(images_list,train_df,'Prostate')        \n        ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:49:39.052714Z","iopub.execute_input":"2022-06-25T19:49:39.053117Z","iopub.status.idle":"2022-06-25T19:50:01.537371Z","shell.execute_reply.started":"2022-06-25T19:49:39.053084Z","shell.execute_reply":"2022-06-25T19:50:01.536233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍3.3|Spleen</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"filtered_df = train_df.query('organ==\"spleen\"')\nfive_samples=random.sample(list(filtered_df ['id']),5)\nimages_list=[]\nfor sample in five_samples:\n    images_list.append(f\"../input/hubmap-organ-segmentation/train_images/{sample}.tiff\")\n\nsample_img(images_list,train_df,'Spleen')        \n        ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:50:30.576097Z","iopub.execute_input":"2022-06-25T19:50:30.577106Z","iopub.status.idle":"2022-06-25T19:50:52.866297Z","shell.execute_reply.started":"2022-06-25T19:50:30.577069Z","shell.execute_reply":"2022-06-25T19:50:52.865262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍3.4|Lung</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"filtered_df = train_df.query('organ==\"lung\"')\nfive_samples=random.sample(list(filtered_df ['id']),5)\nimages_list=[]\nfor sample in five_samples:\n    images_list.append(f\"../input/hubmap-organ-segmentation/train_images/{sample}.tiff\")\n\nsample_img(images_list,train_df,'Lung')        \n        ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:51:02.472669Z","iopub.execute_input":"2022-06-25T19:51:02.473045Z","iopub.status.idle":"2022-06-25T19:51:24.459623Z","shell.execute_reply.started":"2022-06-25T19:51:02.473008Z","shell.execute_reply":"2022-06-25T19:51:24.458470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍3.5 |Kidney</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"filtered_df = train_df.query('organ==\"kidney\"')\nfive_samples=random.sample(list(filtered_df ['id']),5)\nimages_list=[]\nfor sample in five_samples:\n    images_list.append(f\"../input/hubmap-organ-segmentation/train_images/{sample}.tiff\")\n\nsample_img(images_list,train_df,'Kidney')        \n        ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:51:24.461234Z","iopub.execute_input":"2022-06-25T19:51:24.461636Z","iopub.status.idle":"2022-06-25T19:51:46.609921Z","shell.execute_reply.started":"2022-06-25T19:51:24.461608Z","shell.execute_reply":"2022-06-25T19:51:46.608687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <h2 ><div style = \"background-color: #6600cc; color:white; border-radius: 30px 5px; padding: 20px; margin: 2px;\"><b><span>📍3.6 |Large Intestine</span></b></div></h2>","metadata":{}},{"cell_type":"code","source":"filtered_df = train_df.query('organ==\"largeintestine\"')\nfive_samples=random.sample(list(filtered_df ['id']),5)\nimages_list=[]\nfor sample in five_samples:\n    images_list.append(f\"../input/hubmap-organ-segmentation/train_images/{sample}.tiff\")\n\nsample_img(images_list,train_df,'Large Intestine')   ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:52:30.799170Z","iopub.execute_input":"2022-06-25T19:52:30.799566Z","iopub.status.idle":"2022-06-25T19:52:53.475183Z","shell.execute_reply.started":"2022-06-25T19:52:30.799539Z","shell.execute_reply":"2022-06-25T19:52:53.474436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style=\"background:#7300e6   ;font-family:'Times';font-size:20px;color:  white\" ><center>&ensp;Thank you</center></div>\n<div style=\"background:#7300e6   ;font-family:'Times';font-size:20px;color:  white\" ><center>&ensp;⚠ WORK IN PROGRESS ⚠\n<br>Please consider upvoting the kernel if you found it useful.</center></div>\n","metadata":{}}]}