{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Import libraries required for file extraction, image preprocessing, model construction, and data handling.","metadata":{}},{"cell_type":"code","source":"import zipfile # zipファイルの解凍に必要\nimport tensorflow as tf # 機械学習に必要\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator # データの正規化に必要\nfrom tensorflow.keras import layers, models # レイヤークラス, 学習モデル\nfrom tensorflow.keras.preprocessing import image # 画像の前処理に必要\nimport shutil # クラス分けに必要\nimport glob # ファイルのソートに必要\nimport re","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Extract the contents of the train.zip file to the specified output directory.","metadata":{}},{"cell_type":"code","source":"file_path = '/kaggle/input/dogs-vs-cats/train.zip'\nout_path = '/kaggle/working'\n\nwith zipfile.ZipFile(file_path, 'r') as file:\n    file.extractall(out_path)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Create separate folders for cats and dogs, and move each image file into the appropriate folder based on its filename.","metadata":{}},{"cell_type":"code","source":"train_dir = '/kaggle/working/train'\ncat_dir = os.path.join(train_dir, 'cats')\ndog_dir = os.path.join(train_dir, 'dogs')\n\nos.makedirs(cat_dir, exist_ok=True)\nos.makedirs(dog_dir, exist_ok=True)\n\nfor filename in os.listdir(train_dir):\n    \n    file_path = os.path.join(train_dir, filename)\n    if not os.path.isfile(file_path):\n        continue\n    \n    if filename.lower().startswith('cat'):\n        shutil.move(os.path.join(train_dir, filename), os.path.join(cat_dir, filename))\n    elif filename.lower().startswith('dog'):\n        shutil.move(os.path.join(train_dir, filename), os.path.join(dog_dir, filename))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Extract the contents of the test1.zip file to the specified output directory.","metadata":{}},{"cell_type":"code","source":"file_path = '/kaggle/input/dogs-vs-cats/test1.zip'\nout_path = '/kaggle/working'\n\nwith zipfile.ZipFile(file_path, 'r') as file:\n    file.extractall(out_path)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Unzip test1.zip into the working directory.","metadata":{}},{"cell_type":"code","source":"file_path = '/kaggle/input/dogs-vs-cats/test1.zip'\nout_path = '/kaggle/working'\n\nwith zipfile.ZipFile(file_path, 'r') as file:\n    file.extractall(out_path)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Load and preprocess training images from directories, resizing them and assigning binary labels.","metadata":{}},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(\n    '/kaggle/working/train',\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary'\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Load and preprocess test images from directories, resizing them and assigning binary labels.","metadata":{}},{"cell_type":"code","source":"test_generator = test_datagen.flow_from_directory(\n    '/kaggle/working/test1',\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary'\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Build a CNN model for binary image classification using convolution, pooling, flattening, and dense layers.","metadata":{}},{"cell_type":"code","source":"model = models.Sequential([\n    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)), # 画像化から特徴を抽出する\n    layers.MaxPooling2D(2, 2), # 重要な情報を残しつつ、画像サイズを圧縮\n    layers.Conv2D(64, (3, 3), activation='relu'),\n    layers.MaxPooling2D(2, 2),\n    layers.Conv2D(128, (3, 3), activation='relu'),\n    layers.MaxPooling2D(2, 2),\n    layers.Flatten(), # 畳み込み層の出力を、1次元のベクトルに変換\n    layers.Dense(512, activation='relu'), # 中間特徴を学習し、分析精度を向上させる\n    layers.Dense(1, activation='sigmoid') # sigmoidにより0-1の確率を算出\n])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Compile the model with binary crossentropy loss, Adam optimizer, and accuracy as the evaluation metric.","metadata":{}},{"cell_type":"code","source":"model.compile(\n    loss='binary_crossentropy', # 損失関数\n    optimizer='adam', # 最適化アルゴリズム\n    metrics=['accuracy'] # 評価指標 accuracy：予測が正解だった割合\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Train the model on the training data for 10 epochs.","metadata":{}},{"cell_type":"code","source":"history = model.fit(\n    train_generator,\n    epochs=10, # 訓練データを10回学習する\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Save the trained model to a file for later use.","metadata":{}},{"cell_type":"code","source":"file_path = '/kaggle/working/cnn.h5'\n\nmodel.save(file_path)\n# model = load_model(file_path)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Get a sorted list of test image file paths in numerical order.","metadata":{}},{"cell_type":"code","source":"# ファイル一覧を所得\ntest_dir = '/kaggle/working/test1'\ntest_files = os.listdir(test_dir)\n\n# 数値順にソートする関数\ndef extract_number(filename):\n    match = re.search(r'\\d+', filename)\n    return int(match.group()) if match else -1\n\n# 数値順にソート\nsorted_files = sorted(test_files, key=extract_number)\n\n# 画像ファイルのフルパスリスト\nimage_path_list = [os.path.join(test_dir, image) for image in sorted_files]","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Preprocess test images and use the trained model to make predictions.","metadata":{}},{"cell_type":"code","source":"# 前処理\nimages = [image.img_to_array(image.load_img(path, target_size=(150, 150))) / 255.0 for path in image_path_list]\nbatch = np.array(images)\n\n# 推論\npreds = model.predict(batch)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Generate prediction labels with corresponding IDs and save them to a CSV file for submission.","metadata":{}},{"cell_type":"code","source":"# IDの取得\nids = [os.path.splitext(os.path.basename(path))[0] for path in image_path_list]\n\n# ラベルの取得\nlabels = [1 if p[0] > 0.5 else 0 for p in preds]\n\n# CSVで保存\ndf = pd.DataFrame({'id': ids, 'label': labels})\ndf.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}