{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:22:51.488246Z","iopub.execute_input":"2025-07-18T07:22:51.488591Z","iopub.status.idle":"2025-07-18T07:22:51.495968Z","shell.execute_reply.started":"2025-07-18T07:22:51.488560Z","shell.execute_reply":"2025-07-18T07:22:51.495163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport shutil\nimport glob\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras.optimizers import Adam","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:22:51.497203Z","iopub.execute_input":"2025-07-18T07:22:51.497408Z","iopub.status.idle":"2025-07-18T07:22:51.509030Z","shell.execute_reply.started":"2025-07-18T07:22:51.497392Z","shell.execute_reply":"2025-07-18T07:22:51.508321Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# データの解凍\nshutil.unpack_archive('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip', '/kaggle/working')\nshutil.unpack_archive('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip', '/kaggle/working')\nshutil.copyfile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv','/kaggle/working/sample_submission.csv')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:22:51.509663Z","iopub.execute_input":"2025-07-18T07:22:51.510069Z","iopub.status.idle":"2025-07-18T07:22:59.773430Z","shell.execute_reply.started":"2025-07-18T07:22:51.510043Z","shell.execute_reply":"2025-07-18T07:22:59.772737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 犬猫のフォルダを作って振り分け\ndog_dir = '/kaggle/working/train/dog'\ncat_dir = '/kaggle/working/train/cat'\nos.makedirs(dog_dir, exist_ok=True)\nos.makedirs(cat_dir, exist_ok=True)\n\nfiles = glob.glob('/kaggle/working/train/*.jpg')\nfor file in files:\n    file_name = os.path.basename(file)\n    if 'cat' in file_name:\n        shutil.move(file, os.path.join(cat_dir, file_name))\n    else:\n        shutil.move(file, os.path.join(dog_dir, file_name))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:22:59.775103Z","iopub.execute_input":"2025-07-18T07:22:59.775347Z","iopub.status.idle":"2025-07-18T07:23:01.503633Z","shell.execute_reply.started":"2025-07-18T07:22:59.775328Z","shell.execute_reply":"2025-07-18T07:23:01.503023Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 設定\nimg_width, img_height = 224, 224\nbatch_size = 32\nepochs = 20\ntrain_dir = '/kaggle/working/train'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:23:01.504358Z","iopub.execute_input":"2025-07-18T07:23:01.504601Z","iopub.status.idle":"2025-07-18T07:23:01.508592Z","shell.execute_reply.started":"2025-07-18T07:23:01.504576Z","shell.execute_reply":"2025-07-18T07:23:01.507963Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# データ拡張（Augmentation）\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=30,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    validation_split=0.2\n)\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(img_height, img_width),\n    batch_size=batch_size,\n    class_mode='binary',\n    subset='training'\n)\n\nvalidation_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(img_height, img_width),\n    batch_size=batch_size,\n    class_mode='binary',\n    subset='validation'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:23:01.509556Z","iopub.execute_input":"2025-07-18T07:23:01.509902Z","iopub.status.idle":"2025-07-18T07:23:01.786428Z","shell.execute_reply.started":"2025-07-18T07:23:01.509855Z","shell.execute_reply":"2025-07-18T07:23:01.785849Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# モデル構築（VGG16ベース）\nvgg_base = VGG16(include_top=False, weights='imagenet', input_shape=(img_height, img_width, 3))\nvgg_base.trainable = False  # 全層凍結\n\nmodel = Sequential([\n    vgg_base,\n    Flatten(),\n    Dense(256, activation='relu'),\n    Dropout(0.5),\n    Dense(1, activation='sigmoid')  # 2クラス分類\n])\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:23:01.787391Z","iopub.execute_input":"2025-07-18T07:23:01.787642Z","iopub.status.idle":"2025-07-18T07:23:02.053411Z","shell.execute_reply.started":"2025-07-18T07:23:01.787619Z","shell.execute_reply":"2025-07-18T07:23:02.052639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# コールバック設定\ncheckpoint_cb = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True, verbose=1)\nearly_cb = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True, verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:23:02.054306Z","iopub.execute_input":"2025-07-18T07:23:02.054544Z","iopub.status.idle":"2025-07-18T07:23:03.339200Z","shell.execute_reply.started":"2025-07-18T07:23:02.054524Z","shell.execute_reply":"2025-07-18T07:23:03.338126Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 学習\nhistory = model.fit(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    callbacks=[checkpoint_cb, early_cb]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T07:23:03.340115Z","iopub.execute_input":"2025-07-18T07:23:03.340388Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(history.history)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T09:12:30.142478Z","iopub.execute_input":"2025-07-18T09:12:30.143146Z","iopub.status.idle":"2025-07-18T09:12:30.147826Z","shell.execute_reply.started":"2025-07-18T09:12:30.143113Z","shell.execute_reply":"2025-07-18T09:12:30.146925Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# グラフ表示\nplt.plot(history.history['loss'], label='loss', marker='o')\nplt.plot(history.history['val_loss'], label='val_loss', marker='x')\nplt.xlabel('Epoch'); plt.ylabel('Loss'); plt.legend(); plt.grid(); plt.show()\n\nplt.plot(history.history['accuracy'], label='accuracy', marker='o')\nplt.plot(history.history['val_accuracy'], label='val_accuracy', marker='x')\nplt.xlabel('Epoch'); plt.ylabel('Accuracy'); plt.legend(); plt.grid(); plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T09:13:10.339325Z","iopub.execute_input":"2025-07-18T09:13:10.339602Z","iopub.status.idle":"2025-07-18T09:13:10.643778Z","shell.execute_reply.started":"2025-07-18T09:13:10.339581Z","shell.execute_reply":"2025-07-18T09:13:10.643083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# テスト画像から予測（ファイル名にID含む前提）\ntest_dir = '/kaggle/working/test'\ntest_files = sorted(glob.glob(os.path.join(test_dir, '*.jpg')))\n\nmodel = load_model('best_model.h5')\n\nresults = []\nfor file in test_files:\n    img = load_img(file, target_size=(img_height, img_width))\n    x = img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    x = x / 255.0\n    pred = model.predict(x,verbose=0)[0][0]\n    image_id = int(os.path.basename(file).split('.')[0])\n    results.append([image_id, pred])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T09:13:17.387033Z","iopub.execute_input":"2025-07-18T09:13:17.387756Z","iopub.status.idle":"2025-07-18T09:30:41.912274Z","shell.execute_reply.started":"2025-07-18T09:13:17.387732Z","shell.execute_reply":"2025-07-18T09:30:41.911522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# CSVで保存\nresults_df = pd.DataFrame(results, columns=['id', 'label'])\nresults_df.sort_values('id', inplace=True)\nresults_df.to_csv('/kaggle/working/submission.csv', index=False)\nprint(\"保存完了\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-18T09:35:09.374562Z","iopub.execute_input":"2025-07-18T09:35:09.374796Z","iopub.status.idle":"2025-07-18T09:35:09.408503Z","shell.execute_reply.started":"2025-07-18T09:35:09.374780Z","shell.execute_reply":"2025-07-18T09:35:09.407849Z"}},"outputs":[],"execution_count":null}]}