{"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":"from __future__ import print_function\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nimport os\n\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics import confusion_matrix, classification_report\nimport itertools\n\n%matplotlib inline\nimport pandas as pd ","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:38:57.472850Z","iopub.execute_input":"2022-05-10T05:38:57.473356Z","iopub.status.idle":"2022-05-10T05:39:04.506022Z","shell.execute_reply.started":"2022-05-10T05:38:57.473166Z","shell.execute_reply":"2022-05-10T05:39:04.505010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's setting the models hyperparameters and others global parameters.","metadata":{}},{"cell_type":"code","source":"batch_size = 32  # The default batch size of keras.\nnum_classes = 10  # Number of class for the dataset\nepochs = 100\ndata_augmentation = False","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-05-10T05:39:04.507847Z","iopub.execute_input":"2022-05-10T05:39:04.508142Z","iopub.status.idle":"2022-05-10T05:39:04.512299Z","shell.execute_reply.started":"2022-05-10T05:39:04.508099Z","shell.execute_reply":"2022-05-10T05:39:04.511334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2.2 Import and preproces of data \nWe load the data and split it between train and test sets\n","metadata":{}},{"cell_type":"code","source":"# The data, split between train and test sets:\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nprint('x_train shape:', x_train.shape)\nprint('y_train shape:', y_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:04.513449Z","iopub.execute_input":"2022-05-10T05:39:04.513869Z","iopub.status.idle":"2022-05-10T05:39:14.995295Z","shell.execute_reply.started":"2022-05-10T05:39:04.513824Z","shell.execute_reply":"2022-05-10T05:39:14.994392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2.3 Distribution of data.","metadata":{}},{"cell_type":"code","source":"import seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:14.996533Z","iopub.execute_input":"2022-05-10T05:39:14.996818Z","iopub.status.idle":"2022-05-10T05:39:15.000995Z","shell.execute_reply.started":"2022-05-10T05:39:14.996775Z","shell.execute_reply":"2022-05-10T05:39:14.999988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = ['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck']\nlabels_train = np.array([labels[i[0]] for i in y_train])\nlabels_test = np.array([labels[i[0]] for i in y_test])","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:40.783143Z","iopub.execute_input":"2022-05-10T05:39:40.783548Z","iopub.status.idle":"2022-05-10T05:39:40.816096Z","shell.execute_reply.started":"2022-05-10T05:39:40.783493Z","shell.execute_reply":"2022-05-10T05:39:40.815116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.DataFrame(labels_train,columns = [\"label\"])\ndf_test = pd.DataFrame(labels_test,columns = [\"label\"])\ndf_train[\"train_val\"] = \"Train\"\ndf_test[\"train_val\"] = \"Validation\"\ndf = pd.concat([df_train,df_test])\nsns.countplot(y=\"label\", data=df, hue='train_val')","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:41.048993Z","iopub.execute_input":"2022-05-10T05:39:41.049656Z","iopub.status.idle":"2022-05-10T05:39:41.722307Z","shell.execute_reply.started":"2022-05-10T05:39:41.049587Z","shell.execute_reply":"2022-05-10T05:39:41.721298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"R = 5\nC = 5\nfig, axes = plt.subplots(R, C, figsize=(12,12))\naxes = axes.ravel()\nplt.subplots_adjust(wspace=0.1, hspace=0.1)\nfor i in np.arange(0, R*C):\n    axes[i].imshow(x_test[i])\n    axes[i].set_title(labels[y_test[i][0]])\n    axes[i].axis('off')\n    plt.subplots_adjust(wspace=0.5)","metadata":{"execution":{"iopub.status.busy":"2022-05-10T06:01:48.343710Z","iopub.execute_input":"2022-05-10T06:01:48.344506Z","iopub.status.idle":"2022-05-10T06:01:49.900216Z","shell.execute_reply.started":"2022-05-10T06:01:48.344438Z","shell.execute_reply":"2022-05-10T06:01:49.898422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:42.950500Z","iopub.execute_input":"2022-05-10T05:39:42.950979Z","iopub.status.idle":"2022-05-10T05:39:42.955330Z","shell.execute_reply.started":"2022-05-10T05:39:42.950913Z","shell.execute_reply":"2022-05-10T05:39:42.954581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_imgs(imgs, row, col):\n    \"\"\"Show PILimages as row*col\n     # Arguments\n            imgs: 1-D array, include PILimages\n            row: Int, row for plt.subplot\n            col: Int, column for plt.subplot\n    \"\"\"\n    if len(imgs) != (row * col):\n        raise ValueError(\"Invalid imgs len:{} col:{} row:{}\".format(len(imgs), row, col))\n\n    for i, img in enumerate(imgs):\n        plot_num = i+1\n        plt.subplot(row, col, plot_num)\n        plt.tick_params(labelbottom=\"off\") # x軸の削除\n        plt.tick_params(labelleft=\"off\") # y軸の削除\n        plt.imshow(img)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:42.956938Z","iopub.execute_input":"2022-05-10T05:39:42.957466Z","iopub.status.idle":"2022-05-10T05:39:42.966059Z","shell.execute_reply.started":"2022-05-10T05:39:42.957426Z","shell.execute_reply":"2022-05-10T05:39:42.965411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 画像ファイルをPIL形式でオープン\nimg = x_test[6]\n# PIL形式をnumpyのndarray形式に変換\nx = image.img_to_array(img)\n# (height, width, 3) -> (1, height, width, 3)\nx = x.reshape((1,) + x.shape)","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:42.967240Z","iopub.execute_input":"2022-05-10T05:39:42.967694Z","iopub.status.idle":"2022-05-10T05:39:42.980616Z","shell.execute_reply.started":"2022-05-10T05:39:42.967652Z","shell.execute_reply":"2022-05-10T05:39:42.979766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_img_num = 4\nimgs = []\ndatagen = ImageDataGenerator(\n           rotation_range=40,\n           width_shift_range=0,\n           height_shift_range=0,\n           shear_range=0,\n           zoom_range=0,\n           horizontal_flip=False,\n           vertical_flip=False)\n\nfor d in datagen.flow(x, batch_size=1):\n    # このあと画像を表示するためにndarrayをPIL形式に変換して保存する\n    imgs.append(image.array_to_img(d[0], scale=True))\n    # datagen.flowは無限ループするため必要な枚数取得できたらループを抜ける\n    if (len(imgs) % max_img_num) == 0:\n        break\nshow_imgs(imgs, row=2, col=2)","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:42.990084Z","iopub.execute_input":"2022-05-10T05:39:42.990680Z","iopub.status.idle":"2022-05-10T05:39:43.300114Z","shell.execute_reply.started":"2022-05-10T05:39:42.990631Z","shell.execute_reply":"2022-05-10T05:39:43.299469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_img_num = 4\nimgs = []\ndatagen = ImageDataGenerator(\n           rotation_range=0,\n           width_shift_range=0,\n           height_shift_range=0,\n           shear_range=0,\n           zoom_range=0,\n           horizontal_flip=True,\n           vertical_flip=False)\n\nfor d in datagen.flow(x, batch_size=1):\n    # このあと画像を表示するためにndarrayをPIL形式に変換して保存する\n    imgs.append(image.array_to_img(d[0], scale=True))\n    # datagen.flowは無限ループするため必要な枚数取得できたらループを抜ける\n    if (len(imgs) % max_img_num) == 0:\n        break\nshow_imgs(imgs, row=2, col=2)","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:43.355209Z","iopub.execute_input":"2022-05-10T05:39:43.356699Z","iopub.status.idle":"2022-05-10T05:39:43.784981Z","shell.execute_reply.started":"2022-05-10T05:39:43.356597Z","shell.execute_reply":"2022-05-10T05:39:43.783732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_img_num = 4\nimgs = []\ndatagen = ImageDataGenerator(\n           rotation_range=0,\n           width_shift_range=10,\n           height_shift_range=0,\n           shear_range=0,\n           zoom_range=0,\n           horizontal_flip=False,\n           vertical_flip=False)\n\nfor d in datagen.flow(x, batch_size=1):\n    # このあと画像を表示するためにndarrayをPIL形式に変換して保存する\n    imgs.append(image.array_to_img(d[0], scale=True))\n    # datagen.flowは無限ループするため必要な枚数取得できたらループを抜ける\n    if (len(imgs) % max_img_num) == 0:\n        break\nshow_imgs(imgs, row=2, col=2)","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:43.787172Z","iopub.execute_input":"2022-05-10T05:39:43.787845Z","iopub.status.idle":"2022-05-10T05:39:44.228908Z","shell.execute_reply.started":"2022-05-10T05:39:43.787783Z","shell.execute_reply":"2022-05-10T05:39:44.227757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_img_num = 4\nimgs = []\ndatagen = ImageDataGenerator(\n           rotation_range=0,\n           width_shift_range=0,\n           height_shift_range=10,\n           shear_range=0,\n           zoom_range=0,\n           horizontal_flip=False,\n           vertical_flip=False)\n\nfor d in datagen.flow(x, batch_size=1):\n    # このあと画像を表示するためにndarrayをPIL形式に変換して保存する\n    imgs.append(image.array_to_img(d[0], scale=True))\n    # datagen.flowは無限ループするため必要な枚数取得できたらループを抜ける\n    if (len(imgs) % max_img_num) == 0:\n        break\nshow_imgs(imgs, row=2, col=2)","metadata":{"execution":{"iopub.status.busy":"2022-05-10T05:39:44.231049Z","iopub.execute_input":"2022-05-10T05:39:44.231734Z","iopub.status.idle":"2022-05-10T05:39:44.672670Z","shell.execute_reply.started":"2022-05-10T05:39:44.231672Z","shell.execute_reply":"2022-05-10T05:39:44.671558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}