{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.11.11"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"papermill":{"default_parameters":{},"duration":5387.918717,"end_time":"2025-07-07T15:05:15.367195","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2025-07-07T13:35:27.448478","version":"2.6.0"}},"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":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2025-07-22T13:00:45.565046Z","iopub.execute_input":"2025-07-22T13:00:45.565235Z","iopub.status.idle":"2025-07-22T13:00:47.078615Z","shell.execute_reply.started":"2025-07-22T13:00:45.565217Z","shell.execute_reply":"2025-07-22T13:00:47.077837Z"},"papermill":{"duration":1.530589,"end_time":"2025-07-07T13:35:33.126865","exception":false,"start_time":"2025-07-07T13:35:31.596276","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 必要なライブラリをインポート","metadata":{"papermill":{"duration":0.006393,"end_time":"2025-07-07T13:35:33.139921","exception":false,"start_time":"2025-07-07T13:35:33.133528","status":"completed"},"tags":[]}},{"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\n","metadata":{"execution":{"iopub.status.busy":"2025-07-22T13:00:47.079506Z","iopub.execute_input":"2025-07-22T13:00:47.079832Z","iopub.status.idle":"2025-07-22T13:01:00.783225Z","shell.execute_reply.started":"2025-07-22T13:00:47.079815Z","shell.execute_reply":"2025-07-22T13:01:00.782577Z"},"papermill":{"duration":14.351845,"end_time":"2025-07-07T13:35:47.497502","exception":false,"start_time":"2025-07-07T13:35:33.145657","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Zipファイルを解凍","metadata":{"papermill":{"duration":0.005697,"end_time":"2025-07-07T13:35:47.509503","exception":false,"start_time":"2025-07-07T13:35:47.503806","status":"completed"},"tags":[]}},{"cell_type":"code","source":"shutil.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')","metadata":{"execution":{"iopub.status.busy":"2025-07-22T13:01:00.784783Z","iopub.execute_input":"2025-07-22T13:01:00.785224Z","iopub.status.idle":"2025-07-22T13:01:16.015457Z","shell.execute_reply.started":"2025-07-22T13:01:00.785204Z","shell.execute_reply":"2025-07-22T13:01:16.014836Z"},"papermill":{"duration":12.465599,"end_time":"2025-07-07T13:35:59.980816","exception":false,"start_time":"2025-07-07T13:35:47.515217","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 画像サイズとディレクトリの設定","metadata":{"papermill":{"duration":0.00565,"end_time":"2025-07-07T13:35:59.992729","exception":false,"start_time":"2025-07-07T13:35:59.987079","status":"completed"},"tags":[]}},{"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":{"execution":{"iopub.status.busy":"2025-07-22T13:01:16.016596Z","iopub.execute_input":"2025-07-22T13:01:16.016821Z","iopub.status.idle":"2025-07-22T13:01:16.727341Z","shell.execute_reply.started":"2025-07-22T13:01:16.016805Z","shell.execute_reply":"2025-07-22T13:01:16.726562Z"},"papermill":{"duration":0.010663,"end_time":"2025-07-07T13:36:00.009191","exception":false,"start_time":"2025-07-07T13:35:59.998528","status":"completed"},"tags":[],"trusted":true},"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-22T13:01:16.728244Z","iopub.execute_input":"2025-07-22T13:01:16.728459Z","iopub.status.idle":"2025-07-22T13:01:16.732470Z","shell.execute_reply.started":"2025-07-22T13:01:16.728442Z","shell.execute_reply":"2025-07-22T13:01:16.731662Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T13:01:16.733095Z","iopub.execute_input":"2025-07-22T13:01:16.733298Z","iopub.status.idle":"2025-07-22T13:01:17.009008Z","shell.execute_reply.started":"2025-07-22T13:01:16.733283Z","shell.execute_reply":"2025-07-22T13:01:17.008212Z"}},"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-22T13:01:17.009911Z","iopub.execute_input":"2025-07-22T13:01:17.010167Z","iopub.status.idle":"2025-07-22T13:01:19.980482Z","shell.execute_reply.started":"2025-07-22T13:01:17.010144Z","shell.execute_reply":"2025-07-22T13:01:19.979883Z"}},"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-22T13:01:19.981507Z","iopub.execute_input":"2025-07-22T13:01:19.981707Z","iopub.status.idle":"2025-07-22T13:01:19.985734Z","shell.execute_reply.started":"2025-07-22T13:01:19.981692Z","shell.execute_reply":"2025-07-22T13:01:19.984978Z"}},"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-22T13:01:19.987563Z","iopub.execute_input":"2025-07-22T13:01:19.987754Z","iopub.status.idle":"2025-07-22T14:28:32.876540Z","shell.execute_reply.started":"2025-07-22T13:01:19.987739Z","shell.execute_reply":"2025-07-22T14:28:32.875949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(history.history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T14:28:32.877448Z","iopub.execute_input":"2025-07-22T14:28:32.877948Z","iopub.status.idle":"2025-07-22T14:28:32.881965Z","shell.execute_reply.started":"2025-07-22T14:28:32.877920Z","shell.execute_reply":"2025-07-22T14:28:32.881248Z"}},"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-22T14:28:32.882772Z","iopub.execute_input":"2025-07-22T14:28:32.883039Z","iopub.status.idle":"2025-07-22T14:28:33.229003Z","shell.execute_reply.started":"2025-07-22T14:28:32.883018Z","shell.execute_reply":"2025-07-22T14:28:33.228255Z"}},"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])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-22T14:28:33.229846Z","iopub.execute_input":"2025-07-22T14:28:33.230183Z","iopub.status.idle":"2025-07-22T14:45:32.168210Z","shell.execute_reply.started":"2025-07-22T14:28:33.230163Z","shell.execute_reply":"2025-07-22T14:45:32.167547Z"}},"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-22T14:45:32.169153Z","iopub.execute_input":"2025-07-22T14:45:32.169438Z","iopub.status.idle":"2025-07-22T14:45:32.217688Z","shell.execute_reply.started":"2025-07-22T14:45:32.169414Z","shell.execute_reply":"2025-07-22T14:45:32.217056Z"}},"outputs":[],"execution_count":null}]}