{"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-17T09:22:54.392122Z","iopub.execute_input":"2022-07-17T09:22:54.392593Z","iopub.status.idle":"2022-07-17T09:22:54.425598Z","shell.execute_reply.started":"2022-07-17T09:22:54.392507Z","shell.execute_reply":"2022-07-17T09:22:54.424572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np \nimport glob\nimport shutil","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:22:54.427624Z","iopub.execute_input":"2022-07-17T09:22:54.429060Z","iopub.status.idle":"2022-07-17T09:22:54.433974Z","shell.execute_reply.started":"2022-07-17T09:22:54.429024Z","shell.execute_reply":"2022-07-17T09:22:54.432906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# /kaggle/inputのzipファイルを/kaggle/workingに解凍\nimport zipfile\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip') as existing_zip:\n    existing_zip.extractall()\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip') as existing_zip:\n    existing_zip.extractall()\n\n\n# '/kaggle/working'に入っているファイルを確認\nfiles = glob.glob('/kaggle/working/*')\nfor file in files:\n    print(file)","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:22:54.435200Z","iopub.execute_input":"2022-07-17T09:22:54.436046Z","iopub.status.idle":"2022-07-17T09:23:13.000605Z","shell.execute_reply.started":"2022-07-17T09:22:54.436021Z","shell.execute_reply":"2022-07-17T09:23:12.999561Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\n\n# 犬・猫の画像を，それぞれ保存するフォルダのパスを定義\ntrain_dir = '/kaggle/working/train_lap'\ntest_dir = '/kaggle/working/test_lap'\ndog_dir = '/kaggle/working/train_lap/dog'\ncat_dir = '/kaggle/working/train_lap/cat'\n\n# # フォルダの作成\nif(os.path.exists(train_dir) == False):\n    os.mkdir(train_dir)\nif(os.path.exists(test_dir) == False):\n    os.mkdir(test_dir)\nif(os.path.exists(dog_dir) == False):\n    os.mkdir(dog_dir)\nif(os.path.exists(cat_dir) == False):\n    os.mkdir(cat_dir)\n    \n\n    \n\n# 犬・猫の画像を，それぞれのフォルダに移動する\nfiles = glob.glob('/kaggle/working/train/*.jpg')# 訓練用フォルダ内の全ファイルパスを取得\nfor file in files:\n    file_name = os.path.basename(file)\n    #画像を読み込み\n    img = cv2.imread(file)\n    #グレースケール化\n    img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n    #ノイズ除去（ガウシアンフィルター）\n    img_gauss = cv2.GaussianBlur(img_gray,(3,3),3)\n    #エッジ検出（ラプラシアンフィルター）\n    img_lap = cv2.Laplacian(img_gauss,cv2.CV_32F)\n    if 'cat' in file:\n        #shutil.move(file,'/kaggle/working/train/cat/' + file_name)\n        cv2.imwrite(cat_dir +'/' + file_name,img_lap)\n    else:\n        #shutil.move(file,'/kaggle/working/train/dog/' + file_name)\n        cv2.imwrite(dog_dir +'/' + file_name,img_lap)\n\nfiles = glob.glob('/kaggle/working/test/*.jpg')\nfor file in files:\n    file_name = os.path.basename(file)\n    #画像を読み込み\n    img = cv2.imread(file)\n    #グレースケール化\n    img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n    #ノイズ除去（ガウシアンフィルター）\n    img_gauss = cv2.GaussianBlur(img_gray,(3,3),3)\n    #エッジ検出（ラプラシアンフィルター）\n    img_lap = cv2.Laplacian(img_gauss,cv2.CV_32F)\n    cv2.imwrite(test_dir + '/' + file_name,img_lap)\n    ","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:23:13.007340Z","iopub.execute_input":"2022-07-17T09:23:13.008228Z","iopub.status.idle":"2022-07-17T09:26:11.944411Z","shell.execute_reply.started":"2022-07-17T09:23:13.008188Z","shell.execute_reply":"2022-07-17T09:26:11.943333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:26:11.947169Z","iopub.execute_input":"2022-07-17T09:26:11.947431Z","iopub.status.idle":"2022-07-17T09:26:12.636223Z","shell.execute_reply.started":"2022-07-17T09:26:11.947408Z","shell.execute_reply":"2022-07-17T09:26:12.635125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\n#バリデーションフォルダのパスを定義\nval = '/kaggle/working/val'\nval_dog = '/kaggle/working/val/dog'\nval_cat = '/kaggle/working/val/cat'\n\n# フォルダの作成\nif(os.path.exists(val) == False):\n    os.mkdir(val)\n    os.mkdir(val_dog)\n    os.mkdir(val_cat)\n\n# 訓練画像の一部を，バリデーションフォルダに移動する(犬)\ndog_files = glob.glob('/kaggle/working/train_lap/dog/*.jpg')\ndog_train, dog_val = train_test_split(dog_files, test_size=0.2, random_state=42)\n# 画像の一部をバリデーションフォルダに移動する\nfor file in dog_val:\n    file_name = os.path.basename(file)\n    shutil.move(file,'/kaggle/working/val/dog/' + file_name)\n    \n# 訓練画像の一部を，バリデーションフォルダに移動する(猫)\ncat_files = glob.glob('/kaggle/working/train_lap/cat/*.jpg')\ncat_train, cat_val = train_test_split(cat_files, test_size=0.2, random_state=42)\n# 画像の一部をバリデーションフォルダに移動する\nfor file in cat_val:\n    file_name = os.path.basename(file)\n    shutil.move(file,'/kaggle/working/val/cat/' + file_name)","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:26:12.637967Z","iopub.execute_input":"2022-07-17T09:26:12.638608Z","iopub.status.idle":"2022-07-17T09:26:13.247802Z","shell.execute_reply.started":"2022-07-17T09:26:12.638568Z","shell.execute_reply":"2022-07-17T09:26:13.246873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow.keras.layers as layers\nimport tensorflow.keras.optimizers as optimizers\nfrom keras import layers, models\n\n\nmodel = models.Sequential()\n\nmodel.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)))\nmodel.add(layers.Conv2D(32,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Conv2D(64,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Conv2D(128,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Conv2D(128,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(learning_rate=1e-4),metrics=['acc'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:26:13.249101Z","iopub.execute_input":"2022-07-17T09:26:13.249438Z","iopub.status.idle":"2022-07-17T09:26:22.205712Z","shell.execute_reply.started":"2022-07-17T09:26:13.249406Z","shell.execute_reply":"2022-07-17T09:26:22.203105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\ntrain_data_dir = '/kaggle/working/train_lap'\ntest_data_dir = '/kaggle/working/val'\n\n\n# 学習データのデータ拡張を設定\ntrain_datagen = ImageDataGenerator(rescale = 1.0 / 255)\n\n# 評価データのデータ拡張を設定\ntest_datagen = ImageDataGenerator(rescale = 1.0 / 255)\n\n# 学習データのジェネレータを生成\ntrain_generator = train_datagen.flow_from_directory(\n        train_data_dir,\n        target_size = (150, 150),\n        batch_size = 32,\n        class_mode = 'binary')\n\n# 評価データのジェネレータを生成\ntest_generator = test_datagen.flow_from_directory(\n        test_data_dir,\n        target_size = (150, 150),\n        batch_size = 32,\n        class_mode = 'binary')","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:26:22.207073Z","iopub.execute_input":"2022-07-17T09:26:22.208187Z","iopub.status.idle":"2022-07-17T09:26:23.001686Z","shell.execute_reply.started":"2022-07-17T09:26:22.208149Z","shell.execute_reply":"2022-07-17T09:26:23.000768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epoch = 10\n\n# ジェネレータを用いたモデルの学習\nhistory = model.fit_generator(\n    train_generator,\n    steps_per_epoch = 20000/32,\n    epochs=epoch,\n    validation_data = test_generator,\n    validation_steps=5000/32)\n\nmodel.save('/kaggle/working/dog_vs_cat.h5')","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:26:23.002915Z","iopub.execute_input":"2022-07-17T09:26:23.003244Z","iopub.status.idle":"2022-07-17T09:35:18.186785Z","shell.execute_reply.started":"2022-07-17T09:26:23.003209Z","shell.execute_reply":"2022-07-17T09:35:18.185695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing import image\nfrom keras.models import load_model\nimport re\nimport csv","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:35:18.188328Z","iopub.execute_input":"2022-07-17T09:35:18.188682Z","iopub.status.idle":"2022-07-17T09:35:18.193377Z","shell.execute_reply.started":"2022-07-17T09:35:18.188645Z","shell.execute_reply":"2022-07-17T09:35:18.192497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"p = re.compile(r'\\d+')\nimcount = 1\ntest_list = glob.glob('/kaggle/working/test_lap/*.jpg')\ntest_list = sorted(test_list,key=lambda s: int(p.search(s).group()))\n\n#モデルの読み込み\nmodel = load_model('/kaggle/working/dog_vs_cat.h5')\n\n\n#csv書き込み\nwith open('../working/submission.csv', 'w') as f:\n  writer= csv.writer(f, lineterminator='\\n')\n  writer.writerow(['id', 'label'])\n  for i in test_list:\n    img = image.load_img(i, target_size=(150, 150))\n    x = image.img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    x = x / 255.0\n    result_predict = model.predict(x)\n    writer.writerow([imcount, result_predict[0][0]])\n    imcount += 1\n    ","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:35:18.194787Z","iopub.execute_input":"2022-07-17T09:35:18.195353Z","iopub.status.idle":"2022-07-17T09:42:58.716376Z","shell.execute_reply.started":"2022-07-17T09:35:18.195315Z","shell.execute_reply":"2022-07-17T09:42:58.715381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls ","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:43:53.612413Z","iopub.execute_input":"2022-07-17T09:43:53.612763Z","iopub.status.idle":"2022-07-17T09:43:54.318464Z","shell.execute_reply.started":"2022-07-17T09:43:53.612734Z","shell.execute_reply":"2022-07-17T09:43:54.317356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#img = cv2.imread('/kaggle/working/train_lap/cat/cat.3247.jpg')\n#print(img.shape)\n#cv2.imshow('img',img)","metadata":{"execution":{"iopub.status.busy":"2022-07-17T09:42:58.730607Z","iopub.execute_input":"2022-07-17T09:42:58.733049Z","iopub.status.idle":"2022-07-17T09:42:58.747870Z","shell.execute_reply.started":"2022-07-17T09:42:58.733010Z","shell.execute_reply":"2022-07-17T09:42:58.746901Z"},"trusted":true},"execution_count":null,"outputs":[]}]}