{"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":{"_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\")\ntest = pd.read_csv(\"/kaggle/input/siim-isic-melanoma-classification/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **EDA**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(train['age_approx'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.barplot(train['sex'].value_counts().reset_index()['index'], train['sex'].value_counts().reset_index()['sex'] / np.sum(train['sex'].value_counts().reset_index()['sex']) * 100)\nplt.title(\"Male and Female Melanoma Distribution\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = train[train[\"benign_malignant\"] == \"benign\"][[\"anatom_site_general_challenge\", \"diagnosis\", \"target\"]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = sns.countplot(x='anatom_site_general_challenge', hue='diagnosis',data=train[train[\"benign_malignant\"]==\"benign\"])\nplt.xticks(rotation=270)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = sns.countplot(x='anatom_site_general_challenge', hue='diagnosis',data=train[train[\"benign_malignant\"]==\"malignant\"])\nplt.xticks(rotation=270)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Machine Learning Portion**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport os\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Conv2D, MaxPool2D, Activation, Dense, Dropout\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing import image\nimport tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device_name = tf.test.gpu_device_name()\nif \"GPU\" not in device_name:\n    print(\"GPU device not found\")\nprint('Found GPU at: {}'.format(device_name))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"config = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True \nsess = tf.compat.v1.Session(config=config) \ntf.compat.v1.keras.backend.set_session(sess)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = cv2.imread('/kaggle/input/siim-isic-melanoma-classification/jpeg/train/ISIC_0077472.jpg')\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['image'] = [s + \".jpg\" for s in train[\"image_name\"]]\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_directory = '/kaggle/input/siim-isic-melanoma-classification/jpeg/train/'\ntest_directory = '/kaggle/input/siim-isic-melanoma-classification/jpeg/test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['target_string'] = train['target'].astype(str)\ntrain_df, validate_df = train_test_split(train, test_size=0.20, random_state=42)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(\n    train_df,\n    directory = train_directory,\n    x_col = 'image',\n    y_col = 'target',\n    target_size = (256,256),\n    class_mode = 'raw'\n)\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    directory = train_directory,\n    x_col = 'image',\n    y_col = 'target',\n    target_size = (256,256),\n    class_mode = 'raw'\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classifier = tf.keras.models.Sequential()\nclassifier.add(tf.keras.layers.Conv2D(32, (3, 3), input_shape = (256, 256, 3), activation='relu'))\nclassifier.add(tf.keras.layers.MaxPool2D(pool_size=(4,4)))\nclassifier.add(tf.keras.layers.Flatten())\nclassifier.add(tf.keras.layers.Dense(10, activation = 'relu'))\nclassifier.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))\nclassifier.compile(optimizer='adam', loss='binary_crossentropy',metrics=['accuracy'])\nclassifier.fit_generator(train_generator, steps_per_epoch=5, epochs=2, validation_data=validation_generator, validation_steps=5)\n\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dirname='../input/siim-isic-melanoma-classification/'\n#prepare dataframe for test data\ntest_data = []\nfor i in range(len(test)):\n    test_data.append(dirname + 'jpeg/test/' + test['image_name'].iloc[i] + '.jpg')\ntest_path = pd.DataFrame(test_data)\ntest_path.columns = ['images']\n    #img = cv2.resize(img, (224,224))\n    #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    #img = img.astype(np.float32)/255.\n    \n    #img=np.reshape(img,(1,224,224,3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#test data input pipeline\ntest_datagen=ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_dataframe(test_path, x_col='images', y_col=None, \n                                                   target_size = (256,256), shuffle=False, class_mode=None)\ntest_generator.reset()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with tf.device('/device:GPU:0'):\n    preds = classifier.predict(test_generator, steps=test.shape[0]//10+1)\n    ans = np.array(preds)\n    print(ans.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#prep recorded targets\nans=list(ans)\nfor i in range(len(ans)):\n    ans[i]=ans[i][0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final = {'image_name':list(test['image_name']), 'target':ans }\n\nsub = pd.DataFrame(final, columns=['image_name', 'target'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#save predictions\nsub.to_csv('submission.csv', header=True, index=False)\n","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}