{"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\n# for 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":"!pip install plotly","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install cufflinks","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom plotly.offline import iplot\nimport plotly as py\nimport plotly.tools as tls\nimport cufflinks as cf","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/siim-isic-melanoma-classification/train.csv',na_values=['unknown'])\nsubmission = pd.read_csv('../input/siim-isic-melanoma-classification/sample_submission.csv')\ntest = pd.read_csv('../input/siim-isic-melanoma-classification/test.csv')\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"py.offline.init_notebook_mode(connected = True)\ncf.go_offline()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Pandas-Bokeh is use full and quite handy. I previously tried to use Bokeh but because of its complexcity i gave up and started learning plotly.In this notebook i used both bokeh and plotly for comparison. Except that i have implimented stacking on the tabular data which is giving score of 0.685.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"type(train.columns)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lists = ['anatom_site_general_challenge']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# cf.set_config_file(theme = 'solar')\nfrom bokeh.models.widgets import DataTable, TableColumn\nfrom bokeh.models import ColumnDataSource\n\ndata_table = DataTable(\n    columns=[TableColumn(field=Ci, title=Ci) for Ci in lists],\n    source=ColumnDataSource(train),\n    height=300,\n)\n\n\ncount_anatom = train['anatom_site_general_challenge'].value_counts().plot_bokeh(kind = 'barh',color='green',title=\"count of location of imaged site\", \n    alpha=0.6,show_figure=False)\n\npandas_bokeh.plot_grid([[data_table, count_anatom]], plot_width=400, plot_height=350)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['benign_malignant'].value_counts().plot_bokeh(kind='bar',alpha=0.6,color= 'red',title=\"count of benign and malignant\",ylabel='count',xlabel='benign_malignant')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['diagnosis'].value_counts().plot_bokeh(kind='bar',color ='magenta',alpha=0.6,vertical_xlabel=True,title=\"count of diagnosis\",ylabel='count',xlabel='diagnosis')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['age_approx'].value_counts().plot_bokeh(kind='bar',color = 'blue',title=\"count of age_approx\",vertical_xlabel=True,ylabel='count',xlabel='age_approx',alpha=0.6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['sex'].value_counts().plot_bokeh(kind='bar',alpha=0.6,colormap=[\"#009933\"],title=\"count of sex\",ylabel='count',xlabel='sex')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"p_vs_img = train.groupby('patient_id').image_name.count().to_frame().reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"p_vs_img_plot = p_vs_img.sort_values(by=['image_name'],ascending=False).iloc[0:50]\np_vs_img_plot.plot_bokeh(kind='bar',alpha=0.6,color=\"brown\",title=\"count of top 50 patient_id\",ylabel='count',xlabel='patient_id',vertical_xlabel=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# patient_id\ntrain['patient_id'].value_counts().plot_bokeh(kind='bar',alpha=0.6,color=\"blue\",title=\"count of full patient_id\",ylabel='count',xlabel='patient_id',vertical_xlabel=True,figsize=(1000, 600))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"(train.groupby('patient_id').image_name.count()).max()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(['target','sex']).count()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(['target','anatom_site_general_challenge'])['benign_malignant'].count().iplot(kind = 'bar')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(['target','sex'])['benign_malignant'].count().iplot(kind = 'bar',color='red')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(['target','age_approx'])['benign_malignant'].count().iplot(kind = 'bar',color='green')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(['sex','anatom_site_general_challenge'])['benign_malignant'].count().iplot(kind = 'bar',color = 'blue')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(['target','diagnosis'])['benign_malignant'].count().iplot(kind = 'bar')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.groupby(['sex','diagnosis'])['benign_malignant'].count().iplot(kind = 'bar',color ='magenta')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"amount = train.groupby('anatom_site_general_challenge')['anatom_site_general_challenge'].transform('count')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.graph_objs as go\nlabels = set(train['anatom_site_general_challenge'])\nlabels_list = list(labels)\ntrace = go.Pie(values=amount,labels = labels_list,hole=0.3,pull=[0, 0, 0.2, 0])\niplot([trace])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['diagnosis'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['diagnosis'].value_counts().iplot(kind='bar',color='yellow')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# Feature Engineering:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Feature Engineering:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"numerical_features = [i for i in train.columns if train[i].dtypes != 'O']\nnumerical_features","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categorical_features = [i for i in train.columns if train[i].dtypes == 'O']\ncategorical_features","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"discreat_features = [i for i in numerical_features if len(train[i].unique())<25 ]\ndiscreat_features","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"So, we got some features which are neumerical and categorical. And from above cell it is clear that the neumerical features are discontinious.so there is no continious features.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nan_features = [i for i in train.columns if train[i].isnull().sum()>=1]\nnan_features","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# pd.pandas.set_option('display.max_columns',None)\n# pd.pandas.set_option('display.max_rows',None)\n\ntrain['age_approx'] = train['age_approx'].fillna(train['age_approx'].median())\ntrain['age_approx'].isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['anatom_site_general_challenge'].mode()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['anatom_site_general_challenge']=train['anatom_site_general_challenge'].fillna('torso') \ntrain['anatom_site_general_challenge'].isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['sex'] = train['sex'].fillna(str(train['sex'].mode()))\ntrain['diagnosis'] = train['diagnosis'].fillna(str(train['diagnosis'].mode()))\ntrain['sex'].isnull().sum()\ntrain['diagnosis'].isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Label Encoding","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nlabel_encod = LabelEncoder()\n\nfor i in categorical_features:\n    train[i]=label_encod.fit_transform(train[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Droping some columns:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"data = train.copy()\ndata = data.drop(['image_name','patient_id','diagnosis','benign_malignant'],axis = 1)\ndata.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Train test split:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"Y = data['target']\nX = data.drop(['target'],axis = 1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SEED = 42\nfrom sklearn.model_selection import train_test_split\n\nx_train,x_val,y_train,y_val = train_test_split(X,Y,test_size = 0.2,random_state = SEED)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Building:(RF)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"random_grid = {'bootstrap': [True, False],\n               'max_depth': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, None],\n               'max_features': ['auto', 'sqrt'],\n               'min_samples_leaf': [1, 2, 4],\n               'min_samples_split': [2, 5, 10],\n               'n_estimators': [130, 180, 230]}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import RandomizedSearchCV,GridSearchCV\n\nclassifier_rf = RandomForestClassifier(random_state=SEED)\nrf_random = RandomizedSearchCV(estimator = classifier_rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)\nrf_random.fit(x_train,y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rf_random.best_estimator_","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier_rf1 = RandomForestClassifier(max_depth=70, min_samples_leaf=4, min_samples_split=5,\n                       n_estimators=180, random_state=42)\nclassifier_rf1.fit(x_train,y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = classifier_rf1.predict_proba(x_val)\ntype(y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Test data:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['anatom_site_general_challenge'] = test['anatom_site_general_challenge'].fillna(str(test['anatom_site_general_challenge'].mode())) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categorical_fea_test = [i for i in test.columns if test[i].dtypes == 'O']\nfor i in categorical_fea_test:\n    test[i] = label_encod.fit_transform(test[i])\n    \ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = test.drop(['image_name','patient_id'],axis = 1)\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Evaluation:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import roc_curve, roc_auc_score,auc\nprint(roc_auc_score(y_val, y_pred[:,1]))\n\nfpr, tpr, _ = roc_curve(y_val, y_pred[:,1])\n\nplt.clf()\nplt.plot(fpr, tpr)\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nplt.title('ROC curve')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"auc_rf = auc(fpr,tpr)\nprint(auc_rf)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred_test_rf = classifier_rf1.predict_proba(test)\ny_pred_test_rf[:,1].","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_main = pd.read_csv('../input/siim-isic-melanoma-classification/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Image prediction file: ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"img_sub = pd.read_csv('../input/1st-featuredcom-submission-baseline-keras-vgg16/submission.csv')\nimg_sub.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Building:(XGB)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import xgboost as xgb\nfrom scipy import stats\nfrom scipy.stats import randint\n\nxgb_clf = xgb.XGBClassifier()\n\n\nparam_dist = {'n_estimators': stats.randint(150, 1000),\n              'learning_rate': stats.uniform(0.01, 0.6),\n              'subsample': stats.uniform(0.3, 0.9),\n              'max_depth': [3, 4, 5, 6, 7, 8, 9],\n              'colsample_bytree': stats.uniform(0.5, 0.9),\n              'min_child_weight': [1, 2, 3, 4]\n             }\nclf_xgb = RandomizedSearchCV(xgb_clf, param_distributions = param_dist, n_iter = 25, scoring = 'roc_auc', error_score = 0, verbose = 3, n_jobs = -1)\nclf_xgb.fit(x_train,y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"clf_xgb.best_estimator_\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xgbo = xgb.XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,\n              colsample_bynode=1, colsample_bytree=0.5791848525626986, gamma=0,\n              gpu_id=-1, importance_type='gain', interaction_constraints='',\n              learning_rate=0.47840118037023044, max_delta_step=0, max_depth=4,\n              min_child_weight=4, monotone_constraints='()',\n              n_estimators=585, n_jobs=0, num_parallel_tree=1, random_state=0,\n              reg_alpha=0, reg_lambda=1, scale_pos_weight=1,\n              subsample=0.792826572247452, tree_method='exact',\n              validate_parameters=1, verbosity=None)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xgbo.fit(x_train,y_train)\ny_pred_xgb = xgbo.predict_proba(x_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(roc_auc_score(y_val, y_pred_xgb[:,1]))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### So random Forest is giving me more better results than Xgboost, though the difference is slightly large.","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### Stacking:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import StackingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import (AdaBoostClassifier,GradientBoostingClassifier,ExtraTreesClassifier)\nfrom sklearn.tree import DecisionTreeClassifier\n\nbase_learners = [\n                 ('rf_1', RandomForestClassifier(n_estimators=100, random_state=SEED)),\n                 ('adb',AdaBoostClassifier(n_estimators=100, random_state=SEED)),\n                 ('ext',ExtraTreesClassifier(n_estimators=100, random_state=SEED)),\n                 ('gbc',GradientBoostingClassifier(n_estimators=100,random_state=SEED)),\n                 ('svc', SVC())\n    \n    \n                ]\n\n# Initialize Stacking Classifier with the Meta Learner\nstk_clf = StackingClassifier(estimators=base_learners, final_estimator=LogisticRegression())\n\nstk_clf.fit(x_train, y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred_stk = stk_clf.predict_proba(x_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(roc_auc_score(y_val, y_pred_stk[:,1]))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### So stacking is producing far more better result than, normal xgboost or random forest. And it is found that we are getting same score with and without SVC.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -U pandas_bokeh","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas_bokeh\npd.set_option('plotting.backend', 'pandas_bokeh')\npandas_bokeh.output_notebook()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['anatom_site_general_challenge'].value_counts().plot_bokeh(kind='barh')","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}