{"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":{},"cell_type":"markdown","source":"# TRAIN","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ntrain=pd.read_csv(\"/kaggle/input/siim-isic-melanoma-classification/train.csv\")\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.sort_values('image_name',ascending=True,inplace=True)\ntrain.head()","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['sex'].fillna(train['sex'].mode()[0],inplace=True)\ntrain['age_approx'].fillna(train['age_approx'].mean(),inplace=True)\ntrain['anatom_site_general_challenge'].fillna(train['anatom_site_general_challenge'].mode()[0],inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.anatom_site_general_challenge.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"corr = train.corr()\ncorr.style.background_gradient(cmap='inferno')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15,10))\nsns.countplot(train.sex)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15,10))\nsns.countplot(train.anatom_site_general_challenge)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15,10))\nsns.countplot(train.diagnosis)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15,10))\nsns.countplot(y=\"benign_malignant\",data=train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Deep Learning","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nlab=LabelEncoder()\nlabels=lab.fit_transform(train.benign_malignant)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import glob\nimport cv2\nfrom PIL import Image\nimport numpy as np\nfrom tqdm import tqdm\nimage_array=[]\nl=[]\ni=0\nfor img in tqdm(glob.glob(\"../input/siim-isic-melanoma-classification/jpeg/train/*.jpg\")):\n    image= cv2.imread(img)\n    image_from_array = Image.fromarray(image, 'RGB')\n    size_image = image_from_array.resize((50,50))\n    image_array.append(np.array(size_image))\n    i=i+1\n    if i==1000:\n        break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(image_array)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data=np.array(image_array)\nlabels=labels[:1000]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(labels),np.unique(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nfigure=plt.figure(figsize=(15,10))\nax=figure.add_subplot(121)\nax.imshow(data[0])\nbx=figure.add_subplot(122)\nbx.imshow(data[60])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.save(\"Cells\",data)\nnp.save(\"labels\",labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Cells=np.load(\"Cells.npy\")\nlabels=np.load(\"labels.npy\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"s=np.arange(Cells.shape[0])\nnp.random.shuffle(s)\nCells=Cells[s]\nlabels=labels[s]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes=len(np.unique(labels))\nlen_data=len(Cells)\nnum_classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train,x_test=Cells[(int)(0.1*len_data):],Cells[:(int)(0.1*len_data)]\nx_train = x_train.astype('float32')/255\nx_test = x_test.astype('float32')/255\ntrain_len=len(x_train)\ntest_len=len(x_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train,y_test=labels[(int)(0.1*len_data):],labels[:(int)(0.1*len_data)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\ny_train=keras.utils.to_categorical(y_train,num_classes)\ny_test=keras.utils.to_categorical(y_test,num_classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential,Model\nfrom keras.layers import Dense,Conv2D,MaxPooling2D,Dropout,Flatten,MaxPool2D\nfrom keras.optimizers import RMSprop,Adam\nfrom keras.layers import Activation, Convolution2D, Dropout, Conv2D,AveragePooling2D, BatchNormalization,Flatten,GlobalAveragePooling2D\nfrom keras import layers\nfrom keras.regularizers import l2\nfrom keras.callbacks import ModelCheckpoint,ReduceLROnPlateau\nfrom keras.applications.resnet50 import ResNet50","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = ResNet50(weights='imagenet',include_top=False, input_shape=(50,50,3))\nx = base_model.output\nx = Flatten()(x)\nx=Dense(500, activation='relu')(x)\nx=Dropout(0.2)(x)\npredictions = Dense(2, activation='softmax')(x)\nmodel = Model(inputs=base_model.input, outputs=predictions)\nfor layer in base_model.layers:\n    layer.trainable = False\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filepath=\"weights.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')\nhistory=model.fit(x_train,y_train,batch_size=128,epochs=20,verbose=1,validation_split=0.33,callbacks=[checkpoint])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"figure=plt.figure(figsize=(15,15))\nax=figure.add_subplot(121)\nax.plot(history.history['accuracy'])\nax.plot(history.history['val_accuracy'])\nax.legend(['Training Accuracy','Val Accuracy'])\nbx=figure.add_subplot(122)\nbx.plot(history.history['loss'])\nbx.plot(history.history['val_loss'])\nbx.legend(['Training Loss','Val Loss'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_image_array=[]\nfor img in tqdm(glob.glob(\"../input/siim-isic-melanoma-classification/jpeg/test/*.jpg\")):\n    image= cv2.imread(img)\n    image_from_array = Image.fromarray(image, 'RGB')\n    size_image = image_from_array.resize((50,50))\n    test_image_array.append(np.array(size_image))\nnp.save(\"test\",test_image_array)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ts_array=np.load(\"../input/siimpred/test.npy\")\np=np.argmax(model.predict(ts_array),axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"a=lab.inverse_transform(p)\na=pd.DataFrame(a)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"a.to_csv(\"benign_malignant.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Machine Learning","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nla=LabelEncoder()\ntrain['benign_malignant']=la.fit_transform(train['benign_malignant'])\ntrain['diagnosis']=la.fit_transform(train['diagnosis'])\ntrain['anatom_site_general_challenge']=la.fit_transform(train['anatom_site_general_challenge'])\ntrain['sex']=la.fit_transform(train['sex'])","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.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x=train.drop(['image_name','patient_id','target','diagnosis'],axis=1)\ny=train['target']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from imblearn.over_sampling import SMOTE\nsm=SMOTE()\nx,y=sm.fit_sample(x,y)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Machine Learning","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split,KFold,cross_val_score\nxr,xt,yr,yt=train_test_split(x,y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import GradientBoostingClassifier,RandomForestClassifier,RandomForestRegressor,GradientBoostingRegressor\nfrom xgboost import XGBClassifier,XGBRFRegressor,XGBRegressor\nfrom sklearn.tree import DecisionTreeClassifier,DecisionTreeRegressor\nfrom sklearn.linear_model import LogisticRegression,LinearRegression,SGDRegressor\nfrom sklearn.svm import SVC,SVR\nfrom sklearn.neighbors import KNeighborsClassifier,KNeighborsRegressor\nfrom sklearn.naive_bayes import GaussianNB\nfrom lightgbm import LGBMRegressor,LGBMRegressor","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=XGBClassifier(n_estimators=1000)\nmodel.fit(x,y)\n# kfold=KFold(n_splits=10)\n# res=cross_val_score(model,x,y,cv=kfold)\n# res.mean()*100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"yp=model.predict(xt)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score\nprint(r2_score(yt,yp))\nprint(mean_absolute_error(yt,yp))\nprint(mean_squared_error(yt,yp))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample=pd.read_csv(\"/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv\")\nsample.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TEST","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test=pd.read_csv(\"/kaggle/input/siim-isic-melanoma-classification/test.csv\")\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['sex'].fillna(test['sex'].mode()[0],inplace=True)\ntest['age_approx'].fillna(test['age_approx'].mean(),inplace=True)\ntest['anatom_site_general_challenge'].fillna(test['anatom_site_general_challenge'].mode()[0],inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['anatom_site_general_challenge']=la.fit_transform(test['anatom_site_general_challenge'])\ntest['sex']=la.fit_transform(test['sex'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test=pd.concat([test,a],axis=1)\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.columns=[                   'image_name',                    'patient_id',\n                                 'sex',                    'age_approx',\n       'anatom_site_general_challenge',                               'benign_malignant']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['benign_malignant']=la.fit_transform(test['benign_malignant'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x1=test.drop(['image_name','patient_id'],axis=1)\nyp1=model.predict(x1)\nyp1=pd.DataFrame(yp1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test=pd.concat([test,yp1],axis=1)\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.columns=[                   'image_name',                    'patient_id',\n                                 'sex',                    'age_approx',\n       'anatom_site_general_challenge',              'benign_malignant',\n                                     'target']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.to_csv('sub.csv',columns=['image_name','target'],index=False)","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}