{"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":31090,"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-24T04:19:17.716210Z","iopub.execute_input":"2025-07-24T04:19:17.716430Z","iopub.status.idle":"2025-07-24T04:19:18.684952Z","shell.execute_reply.started":"2025-07-24T04:19:17.716407Z","shell.execute_reply":"2025-07-24T04:19:18.684122Z"}},"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-24T04:19:18.686793Z","iopub.execute_input":"2025-07-24T04:19:18.687266Z","iopub.status.idle":"2025-07-24T04:19:32.127101Z","shell.execute_reply.started":"2025-07-24T04:19:18.687245Z","shell.execute_reply":"2025-07-24T04:19:32.126291Z"}},"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')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-24T04:19:32.130464Z","iopub.execute_input":"2025-07-24T04:19:32.130990Z","iopub.status.idle":"2025-07-24T04:19:44.733822Z","shell.execute_reply.started":"2025-07-24T04:19:32.130960Z","shell.execute_reply":"2025-07-24T04:19:44.733215Z"}},"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-24T04:19:44.734550Z","iopub.execute_input":"2025-07-24T04:19:44.734845Z","iopub.status.idle":"2025-07-24T04:19:45.462786Z","shell.execute_reply.started":"2025-07-24T04:19:44.734826Z","shell.execute_reply":"2025-07-24T04:19:45.462025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 設定\nimg_width, img_height = 224, 224\nbatch_size = 32\nepochs = 15\ntrain_dir = '/kaggle/working/train'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-24T04:19:45.463501Z","iopub.execute_input":"2025-07-24T04:19:45.463782Z","iopub.status.idle":"2025-07-24T04:19:45.467498Z","shell.execute_reply.started":"2025-07-24T04:19:45.463755Z","shell.execute_reply":"2025-07-24T04:19:45.466713Z"}},"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-24T04:19:45.469617Z","iopub.execute_input":"2025-07-24T04:19:45.469912Z","iopub.status.idle":"2025-07-24T04:19:45.704284Z","shell.execute_reply.started":"2025-07-24T04:19:45.469895Z","shell.execute_reply":"2025-07-24T04:19:45.703805Z"}},"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-24T04:19:45.704853Z","iopub.execute_input":"2025-07-24T04:19:45.705074Z","iopub.status.idle":"2025-07-24T04:19:48.677874Z","shell.execute_reply.started":"2025-07-24T04:19:45.705050Z","shell.execute_reply":"2025-07-24T04:19:48.677308Z"}},"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-24T04:19:48.678511Z","iopub.execute_input":"2025-07-24T04:19:48.678709Z","iopub.status.idle":"2025-07-24T04:19:48.682770Z","shell.execute_reply.started":"2025-07-24T04:19:48.678693Z","shell.execute_reply":"2025-07-24T04:19:48.682170Z"}},"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-24T04:19:48.683462Z","iopub.execute_input":"2025-07-24T04:19:48.683789Z","iopub.status.idle":"2025-07-24T05:26:00.398239Z","shell.execute_reply.started":"2025-07-24T04:19:48.683772Z","shell.execute_reply":"2025-07-24T05:26:00.397446Z"}},"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-24T05:26:00.399259Z","iopub.execute_input":"2025-07-24T05:26:00.399499Z","iopub.status.idle":"2025-07-24T05:26:00.714490Z","shell.execute_reply.started":"2025-07-24T05:26:00.399472Z","shell.execute_reply":"2025-07-24T05:26:00.713857Z"}},"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)[0][0]\n    image_id = int(os.path.basename(file).split('.')[0])\n    results.append([image_id, pred])","metadata":{"trusted":true},"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)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"最終訓練精度:\", history.history['accuracy'][-1])\nprint(\"最終検証精度:\", history.history['val_accuracy'][-1])","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}