{"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":"# LOADING LIBRARY","execution_count":null},{"metadata":{"trusted":true},"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)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nimport openslide\nimport os\nimport cv2\nimport PIL\nfrom IPython.display import Image, display\nfrom keras.applications.vgg16 import VGG16,preprocess_input\nimport plotly.graph_objs as go\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential, Model,load_model\nfrom keras.applications.vgg16 import VGG16,preprocess_input\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing.image import ImageDataGenerator,load_img, img_to_array\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Input, Flatten,BatchNormalization,Activation\nfrom keras.layers import GlobalMaxPooling2D\nfrom keras.models import Model\nfrom keras.optimizers import Adam, SGD, RMSprop\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping\nfrom keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport gc\nimport skimage.io\nfrom sklearn.model_selection import KFold\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.\nimport tensorflow as tf\nfrom tensorflow.python.keras import backend as K\nsess = K.get_session()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train=pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test=pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub=pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### LOAD ALL THE IMAGES FROM JPEG TRAIN DATASET AND SAVE ALL PATH TO DF DATASET","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=[]\ndata=[]\ndata_dir='/kaggle/input/siim-isic-melanoma-classification/jpeg/train'\nfor i in range(train.shape[0]):\n    data.append(data_dir + train['image_name'].iloc[i]+'.jpg')\n    labels.append(train['target'].iloc[i])\ndf=pd.DataFrame(data)\ndf.columns=['images']\ndf['target']=labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\ntrain_image = []\nfor i in range(train.shape[0]):\n    img = image.load_img('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'+train['image_name'].iloc[i]+'.jpg', target_size=(28,28,1), grayscale=True)\n    img = image.img_to_array(img)\n    img = img/255\n    train_image.append(img)\nX = np.array(train_image)\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\nimport glob\nimport cv2\nimport numpy as np\npic_num=1\nIMG_DIR='/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'\ndef read_images(directory):\n    for img in glob.glob(directory+\"/*.jpg\"):\n        image = cv2.imread(img)\n        image=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        train_image = cv2.resize(image/255.0  , (32 , 32))\n        #cv2.imwrite(\"small/\"+str(pic_num)+'.jpg',resized_img)\n\n        yield train_image\n\ntrain_image =  np.array(list(read_images(IMG_DIR)))\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df","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['target'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(df['images'],df['target'], test_size=0.2, random_state=1234)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train=pd.DataFrame(X_train)\ntrain.columns=['images']\ntrain['target']=y_train\n\nvalidation=pd.DataFrame(X_val)\nvalidation.columns=['images']\nvalidation['target']=y_val\n\ntrain['target']=train['target'].astype(str)\nvalidation['target']=validation['target'].astype(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator()\n                                   #,rotation_range=20,\n    #width_shift_range=0.2,\n    #height_shift_range=0.2,horizontal_flip=True)\nval_datagen=train_datagen = ImageDataGenerator()\ntrain_generator = train_datagen.flow_from_dataframe(\n    train,\n    x_col='images',\n    y_col='target',\n    target_size=(224, 224)\n    #batch_size=32,\n    #class_mode='categorical'\n)\n\nvalidation_generator = val_datagen.flow_from_dataframe(\n    validation,\n    x_col='images',\n    y_col='target',\n    target_size=(224, 244)\n    #batch_size=32,\n    #class_mode='categorical'\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications import VGG16\n\n# include top should be False to remove the softmax layer\npretrained_model = VGG16(include_top=False, weights='imagenet')\npretrained_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def vgg16_model( num_classes=None):\n\n    model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\n    x=Flatten()(model.output)\n    x=Dropout(0.5)(x)\n    output=Dense(num_classes,activation='softmax')(x)\n    model=Model(model.input,output)\n    return model\n\nvgg_conv=vgg16_model(6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_conv.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def kappa_score(y_true, y_pred):\n    \n    y_true=tf.math.argmax(y_true)\n    y_pred=tf.math.argmax(y_pred)\n    return tf.compat.v1.py_func(cohen_kappa_score ,(y_true, y_pred),tf.double)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"opt = SGD(0.001,momentum=0.9,decay=1e-4)\nvgg_conv.compile(loss='categorical_crossentropy',optimizer=opt,metrics=[kappa_score])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_epochs = 5\nbatch_size=32\nnb_train_steps = train.shape[0]//batch_size\nnb_val_steps=validation.shape[0]//batch_size\nprint(\"Number of training and validation steps: {} and {}\".format(nb_train_steps,nb_val_steps))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_conv.fit_generator(\n    train_generator,\n    steps_per_epoch=nb_train_steps,\n    epochs=nb_epochs,\n    validation_data=validation_generator,\n    validation_steps=nb_val_steps)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# submission code from https://www.kaggle.com/frlemarchand/high-res-samples-into-multi-input-cnn-keras\ndef predict_submission(df, path):\n    \n    df[\"image_path\"] = [path+image_id+\".tiff\" for image_id in df[\"image_name\"]]\n    df[\"target\"] = 0\n    predictions = []\n    for idx, row in df.iterrows():\n        print(row.image_path)\n        img=skimage.io.imread(str(row.image_path))\n        img = cv2.resize(img, (224,224))\n        img = cv2.resize(img, (224,224))\n        img = img.astype(np.float32)/255.\n        img=np.reshape(img,(1,224,224,3))\n        prediction=vgg_conv.predict(img)\n        predictions.append(np.argmax(prediction))\n            \n    df[\"target\"] = predictions\n    df = df.drop('image_path', 1)\n    return df[[\"image_name\",\"target\"]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_path = \"'/kaggle/input/siim-isic-melanoma-classification/jpeg/train\"\nsubmission_df = pd.read_csv(\"/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv\")\n\nif os.path.exists(test_path):\n    test_df = pd.read_csv(\"/kaggle/input/siim-isic-melanoma-classification/test.csv\")\n    submission_df = predict_submission(test_df, test_path)\n\nsubmission_df.to_csv('submission.csv', index=False)\nsubmission_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import to_categorical\n# extract train and val features\nvgg_features_train = pretrained_model.predict(train_generator)\nvgg_features_val = pretrained_model.predict(validation_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_features_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model2 = Sequential()\nmodel2.add(Flatten(input_shape=(7,7,512)))\nmodel2.add(Dense(100, activation='relu'))\nmodel2.add(Dropout(0.5))\nmodel2.add(BatchNormalization())\nmodel2.add(Dense(10, activation='softmax'))\n\n# compile the model\nmodel2.compile(optimizer='adam', metrics=['accuracy'], loss='categorical_crossentropy')\n\nmodel2.summary()\n\n# train model using features generated from VGG16 model\n\n#model2.fit(vgg_features_train, epochs=50,  validation_data=vgg_features_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}