{"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-20T09:37:41.236577Z","iopub.execute_input":"2022-07-20T09:37:41.237234Z","iopub.status.idle":"2022-07-20T09:37:41.246423Z","shell.execute_reply.started":"2022-07-20T09:37:41.237196Z","shell.execute_reply":"2022-07-20T09:37:41.245322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import glob\nimport shutil\n\n#csvファイルをコピー\nshutil.copyfile('../input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv',\n                '/kaggle/working/sample_submission.csv')\n\n\n# ipファイルを解凍\nimport zipfile\nwith zipfile.ZipFile('../input/dogs-vs-cats-redux-kernels-edition/train.zip') as existing_zip:\n    existing_zip.extractall()\nwith zipfile.ZipFile('../input/dogs-vs-cats-redux-kernels-edition/test.zip') as existing_zip:\n    existing_zip.extractall()\n    \n#ファイルを確認\nfiles = glob.glob('/kaggle/working/*')\nfor file in files:\n    print(file)","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:37:41.251630Z","iopub.execute_input":"2022-07-20T09:37:41.251949Z","iopub.status.idle":"2022-07-20T09:37:55.740589Z","shell.execute_reply.started":"2022-07-20T09:37:41.251923Z","shell.execute_reply":"2022-07-20T09:37:55.739441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#中身を確認\nfiles = sorted(glob.glob('/kaggle/working/train/*.jpg'))\nprint('学習フォルダ内の画像数', len(files))\n\n#中身を確認\nfiles = sorted(glob.glob('/kaggle/working/test/*.jpg'))\nprint('評価フォルダ内の画像数', len(files))\n\n#画像枚数の確認\nn_dog = 0 # 犬の画像枚数\nn_cat = 0 # 猫の画像枚数\nfiles = glob.glob('/kaggle/working/train/*')\nfor file in files:\n    if 'dog.' in file:\n        n_dog += 1\n    elif 'cat.' in file:\n        n_cat += 1\n        \nprint('学習させる画像枚数...')\nprint('犬の画像枚数：', n_dog)\nprint('猫の画像枚数：', n_cat)","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:37:55.742921Z","iopub.execute_input":"2022-07-20T09:37:55.743492Z","iopub.status.idle":"2022-07-20T09:37:55.973846Z","shell.execute_reply.started":"2022-07-20T09:37:55.743438Z","shell.execute_reply":"2022-07-20T09:37:55.972670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#フォルダのパスを定義\ndog_dir = '/kaggle/working/train/dog'\ncat_dir = '/kaggle/working/train/cat'\n\n#フォルダの作成\nif not os.path.exists(dog_dir):\n    os.mkdir(dog_dir)\nif not os.path.exists(cat_dir):\n    os.mkdir(cat_dir)\n\n#フォルダに移動する\nfiles = glob.glob('/kaggle/working/train/*.jpg')#全ファイルパスを取得\nfor file in files:\n    file_name = os.path.basename(file)\n    if 'dog' in file:\n        shutil.move(file,'/kaggle/working/train/dog/' + file_name)\n    else:\n        shutil.move(file,'/kaggle/working/train/cat/' + file_name)","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:37:55.975438Z","iopub.execute_input":"2022-07-20T09:37:55.976406Z","iopub.status.idle":"2022-07-20T09:37:57.075786Z","shell.execute_reply.started":"2022-07-20T09:37:55.976361Z","shell.execute_reply":"2022-07-20T09:37:57.074735Z"},"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 not os.path.exists(val):\n    os.mkdir(val)\nif not os.path.exists(val_dog):\n    os.mkdir(val_dog)\nif not os.path.exists(val_cat):\n    os.mkdir(val_cat)\n\n#フォルダに移動する\ndog_files = glob.glob('/kaggle/working/train/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/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-20T09:37:57.078829Z","iopub.execute_input":"2022-07-20T09:37:57.079557Z","iopub.status.idle":"2022-07-20T09:37:57.948783Z","shell.execute_reply.started":"2022-07-20T09:37:57.079518Z","shell.execute_reply":"2022-07-20T09:37:57.947768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow.keras.layers as layers\nfrom tensorflow.keras import layers, models, optimizers\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)))\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\n#model.add(layers.Dropout(0.5))\n\nmodel.add(layers.Flatten())\n\nmodel.add(layers.Dense(512,activation='relu'))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n             optimizer=optimizers.Adam(learning_rate=1e-4),\n             metrics=['acc'])\n \nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:37:57.950551Z","iopub.execute_input":"2022-07-20T09:37:57.951001Z","iopub.status.idle":"2022-07-20T09:38:06.541382Z","shell.execute_reply.started":"2022-07-20T09:37:57.950962Z","shell.execute_reply":"2022-07-20T09:38:06.540394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n# データの正規化 \ntrain_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\n# 学習データ\ntrain_dir = ('/kaggle/working/train') \n# 評価データ\nvalidation_dir = ('/kaggle/working/val') \n\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150,150),\n    batch_size=32,\n    class_mode='binary'\n)\n\nvalidation_generator = validation_datagen.flow_from_directory(\n    validation_dir,\n    target_size=(150,150),\n    batch_size=32,\n    class_mode='binary'\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:38:06.542862Z","iopub.execute_input":"2022-07-20T09:38:06.543637Z","iopub.status.idle":"2022-07-20T09:38:07.318726Z","shell.execute_reply.started":"2022-07-20T09:38:06.543598Z","shell.execute_reply":"2022-07-20T09:38:07.317673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#学習\nhistory = model.fit(train_generator,\n                    steps_per_epoch=625,\n                    epochs=3,\n                    validation_data=validation_generator,\n                    validation_steps=5000/32)\n#学習済みモデルの保存\nmodel.save(\"/kaggle/working/dog_cat.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:38:07.319954Z","iopub.execute_input":"2022-07-20T09:38:07.320316Z","iopub.status.idle":"2022-07-20T09:42:01.512922Z","shell.execute_reply.started":"2022-07-20T09:38:07.320279Z","shell.execute_reply":"2022-07-20T09:42:01.511869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nmetrics = ['loss', 'acc']\n \nplt.figure(figsize=(10, 5))\n \nfor i in range(len(metrics)):\n \n    metric = metrics[i]\n \n    plt.subplot(1, 2, i+1)\n    plt.title(metric)\n    \n    plt_train = history.history[metric]\n    plt_test = history.history['val_' + metric]\n    \n    plt.plot(plt_train, label='training')\n    plt.plot(plt_test, label='test')\n    plt.legend() \n    \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:42:01.514454Z","iopub.execute_input":"2022-07-20T09:42:01.514827Z","iopub.status.idle":"2022-07-20T09:42:01.860598Z","shell.execute_reply.started":"2022-07-20T09:42:01.514792Z","shell.execute_reply":"2022-07-20T09:42:01.859629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import re\nimport csv\nfrom keras.preprocessing import image\nfrom tqdm import tqdm\n\np = re.compile(r'\\d+')\ntest_list = glob.glob('/kaggle/working/test/*.jpg')\ntest_list = sorted(test_list,key=lambda s: int(p.search(s).group())) # ソート\n\nmodel = models.load_model('/kaggle/working/dog_cat.h5')\n\nimcount = 0\n\nwith open('/kaggle/working/sample_submission.csv', 'w') as f:\n    writer= csv.writer(f, lineterminator='\\n')\n    writer.writerow(['id', 'label'])\n    \n    for test in tqdm(test_list): \n        \n     \n        img = image.load_img(test, target_size=(150, 150))\n        \n        x = image.img_to_array(img) \n        x = np.expand_dims(x, axis=0)\n        x = x / 255.0\n        \n        result_predict = model.predict(x)\n        \n        imcount += 1\n        writer.writerow([imcount, result_predict[0][0]])","metadata":{"execution":{"iopub.status.busy":"2022-07-20T09:42:01.862087Z","iopub.execute_input":"2022-07-20T09:42:01.862643Z","iopub.status.idle":"2022-07-20T09:51:03.352090Z","shell.execute_reply.started":"2022-07-20T09:42:01.862605Z","shell.execute_reply":"2022-07-20T09:51:03.350886Z"},"trusted":true},"execution_count":null,"outputs":[]}]}