{"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_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-28T05:09:30.637834Z","iopub.execute_input":"2022-07-28T05:09:30.639057Z","iopub.status.idle":"2022-07-28T05:09:30.671013Z","shell.execute_reply.started":"2022-07-28T05:09:30.638898Z","shell.execute_reply":"2022-07-28T05:09:30.669907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\n\nimport zipfile\nwith zipfile.ZipFile('../input/dogs-vs-cats/test1.zip') as existing_zip:\n    existing_zip.extractall()\nwith zipfile.ZipFile('../input/dogs-vs-cats/train.zip') as existing_zip:\n    existing_zip.extractall()\n    \nimport os\nprint(os.listdir(\"../input/dogs-vs-cats\"))    ","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:09:30.673236Z","iopub.execute_input":"2022-07-28T05:09:30.673979Z","iopub.status.idle":"2022-07-28T05:09:54.806126Z","shell.execute_reply.started":"2022-07-28T05:09:30.673937Z","shell.execute_reply":"2022-07-28T05:09:54.804996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(\"./train\")\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:09:54.807897Z","iopub.execute_input":"2022-07-28T05:09:54.809054Z","iopub.status.idle":"2022-07-28T05:09:54.958130Z","shell.execute_reply.started":"2022-07-28T05:09:54.809011Z","shell.execute_reply":"2022-07-28T05:09:54.956709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:09:54.963964Z","iopub.execute_input":"2022-07-28T05:09:54.966446Z","iopub.status.idle":"2022-07-28T05:09:55.254278Z","shell.execute_reply.started":"2022-07-28T05:09:54.966404Z","shell.execute_reply":"2022-07-28T05:09:55.253300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(\"./train/\"+sample)\nplt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:09:55.255634Z","iopub.execute_input":"2022-07-28T05:09:55.257270Z","iopub.status.idle":"2022-07-28T05:09:55.506575Z","shell.execute_reply.started":"2022-07-28T05:09:55.257220Z","shell.execute_reply":"2022-07-28T05:09:55.505491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"ここを改変\n","metadata":{}},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras import layers\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation,GlobalMaxPooling2D\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.optimizers import SGD\nfrom keras.models import Model\n\nimage_size = 224\ninput_shape = (image_size, image_size, 3)\n\nepochs = 2\nbatch_size = 16\n\n#ここのpre_trained_modelを改変\n\npre_trained_model = VGG16(input_shape=input_shape, include_top=False, weights=\"imagenet\")\n    \nfor layer in pre_trained_model.layers[:15]:\n    layer.trainable = False\n\nfor layer in pre_trained_model.layers[15:]:\n    layer.trainable = True\n    \nlast_layer = pre_trained_model.get_layer('block5_pool')\nlast_output = last_layer.output\n    \n# Flatten the output layer to 1 dimension\nx = GlobalMaxPooling2D()(last_output)\n# Add a fully connected layer with 512 hidden units and ReLU activation\nx = Dense(512, activation='relu')(x)\n# Add a dropout rate of 0.5\nx = Dropout(0.5)(x)\n# Add a final sigmoid layer for classification\nx = layers.Dense(1, activation='sigmoid')(x)\n\nmodel = Model(pre_trained_model.input, x)\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),\n              metrics=['accuracy'])\n\nmodel.summary()    ","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:09:55.507652Z","iopub.execute_input":"2022-07-28T05:09:55.508054Z","iopub.status.idle":"2022-07-28T05:10:09.538677Z","shell.execute_reply.started":"2022-07-28T05:09:55.508014Z","shell.execute_reply":"2022-07-28T05:10:09.537660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"ここまで改変","metadata":{}},{"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size=0.1)\ntrain_df = train_df.reset_index()\nvalidate_df = validate_df.reset_index()\n\n# validate_df = validate_df.sample(n=100).reset_index() # use for fast testing code purpose\n# train_df = train_df.sample(n=1800).reset_index() # use for fast testing code purpose\n\ntotal_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:10:09.540189Z","iopub.execute_input":"2022-07-28T05:10:09.540779Z","iopub.status.idle":"2022-07-28T05:10:09.554465Z","shell.execute_reply.started":"2022-07-28T05:10:09.540742Z","shell.execute_reply":"2022-07-28T05:10:09.553113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest',\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:10:09.556240Z","iopub.execute_input":"2022-07-28T05:10:09.556645Z","iopub.status.idle":"2022-07-28T05:10:09.564337Z","shell.execute_reply.started":"2022-07-28T05:10:09.556588Z","shell.execute_reply":"2022-07-28T05:10:09.563386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='raw',\n    target_size=(image_size, image_size),\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:10:09.565933Z","iopub.execute_input":"2022-07-28T05:10:09.566360Z","iopub.status.idle":"2022-07-28T05:10:09.764772Z","shell.execute_reply.started":"2022-07-28T05:10:09.566322Z","shell.execute_reply":"2022-07-28T05:10:09.763634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"./train\", \n    x_col='filename',\n    y_col='category',\n    class_mode='raw',\n    target_size=(image_size, image_size),\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:10:09.769625Z","iopub.execute_input":"2022-07-28T05:10:09.769922Z","iopub.status.idle":"2022-07-28T05:10:09.801089Z","shell.execute_reply.started":"2022-07-28T05:10:09.769897Z","shell.execute_reply":"2022-07-28T05:10:09.800047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    \"./train\", \n    x_col='filename',\n    y_col='category',\n    class_mode='raw'\n)\nplt.figure(figsize=(12, 12))\nfor i in range(0, 9):\n    plt.subplot(3, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:10:09.802392Z","iopub.execute_input":"2022-07-28T05:10:09.802826Z","iopub.status.idle":"2022-07-28T05:10:11.554419Z","shell.execute_reply.started":"2022-07-28T05:10:09.802789Z","shell.execute_reply":"2022-07-28T05:10:11.552059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fine-tune the model\nhistory = model.fit_generator(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size)","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:10:11.555832Z","iopub.execute_input":"2022-07-28T05:10:11.557027Z","iopub.status.idle":"2022-07-28T05:21:14.401566Z","shell.execute_reply.started":"2022-07-28T05:10:11.556969Z","shell.execute_reply":"2022-07-28T05:21:14.400454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss, accuracy = model.evaluate_generator(validation_generator, total_validate//batch_size, workers=12)\nprint(\"Test: accuracy = %f  ;  loss = %f \" % (accuracy, loss))","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:14.404260Z","iopub.execute_input":"2022-07-28T05:21:14.404948Z","iopub.status.idle":"2022-07-28T05:21:22.346310Z","shell.execute_reply.started":"2022-07-28T05:21:14.404905Z","shell.execute_reply":"2022-07-28T05:21:22.345338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_val = validate_df['category']\ny_pred =  model.predict_generator(validation_generator)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:22.347573Z","iopub.execute_input":"2022-07-28T05:21:22.347938Z","iopub.status.idle":"2022-07-28T05:21:30.166509Z","shell.execute_reply.started":"2022-07-28T05:21:22.347901Z","shell.execute_reply":"2022-07-28T05:21:30.163074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"threshold = 0.5\ny_final = np.where(y_pred > threshold, 1,0)","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:30.174214Z","iopub.execute_input":"2022-07-28T05:21:30.176898Z","iopub.status.idle":"2022-07-28T05:21:30.184163Z","shell.execute_reply.started":"2022-07-28T05:21:30.176851Z","shell.execute_reply":"2022-07-28T05:21:30.183042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_final.size","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:30.187547Z","iopub.execute_input":"2022-07-28T05:21:30.190695Z","iopub.status.idle":"2022-07-28T05:21:30.201824Z","shell.execute_reply.started":"2022-07-28T05:21:30.190657Z","shell.execute_reply":"2022-07-28T05:21:30.200654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n# Predict the values from the validation dataset\n\n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_val, y_final) \n# plot the confusion matrix\nf,ax = plt.subplots(figsize=(8, 8))\nsns.heatmap(confusion_mtx, annot=True, linewidths=0.01,cmap=\"Greens\",linecolor=\"gray\", fmt= '.1f',ax=ax)\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.title(\"Confusion Matrix\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:30.204573Z","iopub.execute_input":"2022-07-28T05:21:30.206019Z","iopub.status.idle":"2022-07-28T05:21:30.726053Z","shell.execute_reply.started":"2022-07-28T05:21:30.205962Z","shell.execute_reply":"2022-07-28T05:21:30.724952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\n# Generate a classification report\nreport = classification_report(Y_val, y_final, target_names=['0','1'])\n\nprint(report)","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:30.727917Z","iopub.execute_input":"2022-07-28T05:21:30.728608Z","iopub.status.idle":"2022-07-28T05:21:30.748824Z","shell.execute_reply.started":"2022-07-28T05:21:30.728555Z","shell.execute_reply":"2022-07-28T05:21:30.747642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_filenames = os.listdir(\"./test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:30.750420Z","iopub.execute_input":"2022-07-28T05:21:30.750939Z","iopub.status.idle":"2022-07-28T05:21:30.770154Z","shell.execute_reply.started":"2022-07-28T05:21:30.750900Z","shell.execute_reply":"2022-07-28T05:21:30.769102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"./test1\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    batch_size=batch_size,\n    target_size=(image_size, image_size),\n    shuffle=False\n)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:30.771526Z","iopub.execute_input":"2022-07-28T05:21:30.772082Z","iopub.status.idle":"2022-07-28T05:21:30.908469Z","shell.execute_reply.started":"2022-07-28T05:21:30.772041Z","shell.execute_reply":"2022-07-28T05:21:30.906483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size))\nthreshold = 0.5\ntest_df['category'] = np.where(predict > threshold, 1,0)","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:21:30.911908Z","iopub.execute_input":"2022-07-28T05:21:30.913083Z","iopub.status.idle":"2022-07-28T05:22:09.889490Z","shell.execute_reply.started":"2022-07-28T05:21:30.913036Z","shell.execute_reply":"2022-07-28T05:22:09.888397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_test = test_df.sample(n=9).reset_index()\nsample_test.head()\nplt.figure(figsize=(12, 12))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = load_img(\"./test1/\"+filename, target_size=(256, 256))\n    plt.subplot(3, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:22:09.890885Z","iopub.execute_input":"2022-07-28T05:22:09.891456Z","iopub.status.idle":"2022-07-28T05:22:11.306417Z","shell.execute_reply.started":"2022-07-28T05:22:09.891418Z","shell.execute_reply":"2022-07-28T05:22:11.304797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission_13010030.csv', index=False)\n\nplt.figure(figsize=(10,5))\nsns.countplot(submission_df['label'])\nplt.title(\"(Test data)\")","metadata":{"execution":{"iopub.status.busy":"2022-07-28T05:22:11.308245Z","iopub.execute_input":"2022-07-28T05:22:11.308858Z","iopub.status.idle":"2022-07-28T05:22:11.531184Z","shell.execute_reply.started":"2022-07-28T05:22:11.308811Z","shell.execute_reply":"2022-07-28T05:22:11.530057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}