{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# linear algebra\nimport numpy as np \n# data processing\nimport pandas as pd \n#import Libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.linear_model import LogisticRegression, Ridge\nfrom sklearn.preprocessing import OneHotEncoder\nfrom tqdm import tqdm\nfrom sklearn.decomposition import PCA\nimport os\nimport imagesize\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir(\"../input/siim-isic-melanoma-classification\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reading the dataset\ntrain = pd.read_csv(\"../input/siim-isic-melanoma-classification/train.csv\")\ntest = pd.read_csv(\"../input/siim-isic-melanoma-classification/test.csv\")\nprint(\"{} images in train set.\".format(train.shape[0]))\nprint(\"{} images in test set.\".format(test.shape[0]))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Data Exploration & Visualisations","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train.isnull().any()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.nunique()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"plt.figure(figsize=(20, 6))\nplt.subplot(1,3,1)\nsns.distplot(train.age_approx,kde=False)\nplt.title(\"Histogram for age_approx\")","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(train['benign_malignant'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig,ax = plt.subplots(figsize=(15,5))\nsns.countplot(train['age_approx'],hue=train['benign_malignant'],ax=ax)\nplt.xlabel('age_approx')\nplt.ylabel('Counts')\nplt.xticks(rotation=45)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(x='benign_malignant',hue='sex',data=train)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ax = train[\"age_approx\"].hist(bins=15, density=True, stacked=True, color='teal', alpha=0.6)\ntrain[\"age_approx\"].plot(kind='density', color='teal')\nax.set(xlabel='Age')\nplt.xlim(-10,85)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.age_approx.hist()\nplt.title('Histogram of age_approx')\nplt.xlabel('age_approx')\nplt.ylabel('Frequency')\nplt.savefig('age_approx')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"multi_target_count = train.groupby(\"patient_id\").target.sum()\n\nfig, ax = plt.subplots(1,2,figsize=(15,5))\n\nsns.countplot(train.target, ax=ax[0], palette=\"Reds\")\nax[0].set_xlabel(\"Binary target\")\nax[0].set_title(\"How often do we observe a positive label?\");\n\nsns.countplot(multi_target_count, ax=ax[1])\nax[1].set_xlabel(\"Numer of targets per image\")\nax[1].set_ylabel(\"Frequency\")\nax[1].set_title(\"Multi-Hot occurences\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gbSub = train.groupby('anatom_site_general_challenge').sum()\ngbSub\nsns.barplot(y=gbSub.index, x=gbSub.target, palette=\"deep\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig=plt.figure(figsize=(10, 8))\n\nsns.countplot(x=\"anatom_site_general_challenge\", hue=\"target\", data=train)\n\nplt.title(\"Total Images by Subtype\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.mean(train.target)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Images Visualisations","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Showing a sample image\nimage = plt.imread('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/ISIC_5766923.jpg')\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Benign Images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"w = 10\nh = 10\nfig = plt.figure(figsize=(15, 15))\ncolumns = 4\nrows = 4\n\n# ax enables access to manipulate each of subplots\nax = []\n\nfor i in range(columns*rows):\n    img = plt.imread('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'+train['image_name'][i]+'.jpg')\n    # create subplot and append to ax\n    ax.append( fig.add_subplot(rows, columns, i+1) )\n    # Hide grid lines\n    ax[-1].grid(False)\n\n      # Hide axes ticks\n    ax[-1].set_xticks([])\n    ax[-1].set_yticks([])\n    ax[-1].set_title(train['benign_malignant'][i])  # set title\n    plt.imshow(img)\n\n\nplt.show()  # finally, render the plot","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"w = 10\nh = 10\nfig = plt.figure(figsize=(15, 15))\ncolumns = 4\nrows = 4\n\n# ax enables access to manipulate each of subplots\nax = []\n\nfor i in range(columns*rows):\n    img = plt.imread('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'+train.loc[train['target'] == 1]['image_name'].values[i]+'.jpg')\n    # create subplot and append to ax\n    ax.append( fig.add_subplot(rows, columns, i+1) )\n    # Hide grid lines\n    ax[-1].grid(False)\n\n      # Hide axes ticks\n    ax[-1].set_xticks([])\n    ax[-1].set_yticks([])\n    ax[-1].set_title(train.loc[train['target'] == 1]['benign_malignant'].values[i])  # set title\n    plt.imshow(img)\n\n\n\nplt.show()  # finally, render the plot","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### I have importe RandomForest model to predict the target\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train['benign_malignant'] = train['benign_malignant'].replace('malignant',np.nan)\ntrain['benign_malignant'] = train['benign_malignant'].fillna(1)\ntrain['benign_malignant'] = train['benign_malignant'].replace('benign',np.nan)\ntrain['benign_malignant'] = train['benign_malignant'].fillna(0)\n\ntrain['diagnosis'] = train['diagnosis'].replace('nevus',np.nan)\ntrain['diagnosis'] = train['diagnosis'].fillna(1)\ntrain['diagnosis'] = train['diagnosis'].replace('unknown',np.nan)\ntrain['diagnosis'] = train['diagnosis'].fillna(0)\n\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].replace('head/neck',np.nan)\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].fillna(1)\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].replace('upper extremity',np.nan)\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].fillna(0)\n\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].replace('lower extremity',np.nan)\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].fillna(2)\n\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].replace('torso',np.nan)\ntrain['anatom_site_general_challenge'] = train['anatom_site_general_challenge'].fillna(3)\n\ntrain['sex'] = train['sex'].replace('male',np.nan)\ntrain['sex'] = train['sex'].fillna(1)\ntrain['sex'] = train['sex'].replace('female',np.nan)\ntrain['sex'] = train['sex'].fillna(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df3=train.drop(['patient_id','image_name','anatom_site_general_challenge','diagnosis'], axis=1)\ndf3.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df3= train.dropna()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X=df3[['age_approx','benign_malignant','sex']]  \ny= df3[['target']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nmodel= RandomForestClassifier(n_estimators= 10)\nmodel.fit(X_train,y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = RandomForestClassifier(n_estimators=100, max_depth=2,random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(X_train, y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.score(X_test, y_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}