{"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":5441,"databundleVersionId":38425,"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,"execution":{"iopub.status.busy":"2025-07-11T07:28:01.546394Z","iopub.execute_input":"2025-07-11T07:28:01.546745Z","iopub.status.idle":"2025-07-11T07:28:01.557963Z","shell.execute_reply.started":"2025-07-11T07:28:01.546719Z","shell.execute_reply":"2025-07-11T07:28:01.556910Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Zipファイルの展開","metadata":{}},{"cell_type":"code","source":"import zipfile\n\n# zipファイルのパス\nzip_train_path = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'\nzip_test_path = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'\n# 展開先のパス\nextract_train_path = '/kaggle/working'\nextract_test_path = '/kaggle/working'\n# 展開処理\nwith zipfile.ZipFile(zip_train_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_train_path)\nwith zipfile.ZipFile(zip_test_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_test_path)\nprint(\"ファイル展開完了\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:28:01.559638Z","iopub.execute_input":"2025-07-11T07:28:01.559945Z","iopub.status.idle":"2025-07-11T07:28:14.063363Z","shell.execute_reply.started":"2025-07-11T07:28:01.559909Z","shell.execute_reply":"2025-07-11T07:28:14.062542Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# trainデータのラベル付け","metadata":{}},{"cell_type":"code","source":"train_dir = '/kaggle/working/train'  # 展開された画像の場所\n\nfilenames = os.listdir(train_dir)\nlabels = ['dog' if 'dog' in fname else 'cat' for fname in filenames]\nprint(\"ラベル付け完了\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:28:14.064186Z","iopub.execute_input":"2025-07-11T07:28:14.064452Z","iopub.status.idle":"2025-07-11T07:28:14.089417Z","shell.execute_reply.started":"2025-07-11T07:28:14.064430Z","shell.execute_reply":"2025-07-11T07:28:14.087560Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# データセットのデータフレーム化","metadata":{}},{"cell_type":"code","source":"# trainファイルのフルパス\ntrain_filepaths = [os.path.join(train_dir, fname) for fname in filenames]\n\n# train DataFrame作成\ntrain_df = pd.DataFrame({\n    'filename': filenames,\n    'filepath': train_filepaths,\n    'label': labels\n})\nprint(\"trainDF作成完了\")\n\n# testファイルのパス\ntest_dir = '/kaggle/working/test'\ntest_filenames = os.listdir(test_dir)\ntest_filepaths = [os.path.join(test_dir, fname) for fname in test_filenames]\n\n# test DataFrame作成\ntest_df = pd.DataFrame({\n    'filename': test_filenames,\n    'filepath': test_filepaths\n})\nprint(\"testDF作成完了\")\n\n# 確認（ラベルはtrainのみ）\nprint(train_df.head())\nprint(test_df.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:28:14.092352Z","iopub.execute_input":"2025-07-11T07:28:14.092807Z","iopub.status.idle":"2025-07-11T07:28:14.156329Z","shell.execute_reply.started":"2025-07-11T07:28:14.092770Z","shell.execute_reply":"2025-07-11T07:28:14.155225Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# データセットを128×128にリサイズ","metadata":{}},{"cell_type":"code","source":"from PIL import Image\n\n# 保存先ディレクトリ作成\ntrain_resized_dir = '/kaggle/working/train_128'\ntest_resized_dir = '/kaggle/working/test_128'\nos.makedirs(train_resized_dir, exist_ok=True)\nos.makedirs(test_resized_dir, exist_ok=True)\n\n# ----------- train画像のリサイズ -----------\nfor fname in train_df['filename']:\n    src_path = os.path.join(train_dir, fname)\n    dst_path = os.path.join(train_resized_dir, fname)\n    with Image.open(src_path) as img:\n        img_resized = img.resize((128, 128))\n        img_resized.save(dst_path)\n\n# filepathを更新\ntrain_df['filepath'] = train_df['filename'].apply(lambda x: os.path.join(train_resized_dir, x))\nprint(\"trainのリサイズ完了\")\n\n# ----------- test画像のリサイズ -----------\nfor fname in test_df['filename']:\n    src_path = os.path.join(test_dir, fname)\n    dst_path = os.path.join(test_resized_dir, fname)\n    with Image.open(src_path) as img:\n        img_resized = img.resize((128, 128))\n        img_resized.save(dst_path)\n\n# filepathを更新\ntest_df['filepath'] = test_df['filename'].apply(lambda x: os.path.join(test_resized_dir, x))\nprint(\"testのリサイズ完了\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:28:14.157041Z","iopub.execute_input":"2025-07-11T07:28:14.157324Z","iopub.status.idle":"2025-07-11T07:30:21.478607Z","shell.execute_reply.started":"2025-07-11T07:28:14.157279Z","shell.execute_reply":"2025-07-11T07:30:21.477536Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# データセットのサイズ確認","metadata":{}},{"cell_type":"code","source":"# ----------- train_128のサイズ確認 -----------\ncorrect_train_size = 0\nfor path in train_df['filepath']:\n    with Image.open(path) as img:\n        if img.size == (128, 128):\n            correct_train_size += 1\n\nprint(f\"128x128に正しくリサイズされたtrain画像：{correct_train_size} / {len(train_df)}\")\n\n# ----------- test_128のサイズ確認 -----------\ncorrect_test_size = 0\nfor path in test_df['filepath']:\n    with Image.open(path) as img:\n        if img.size == (128, 128):\n            correct_test_size += 1\n\nprint(f\"128x128に正しくリサイズされたtest画像：{correct_test_size} / {len(test_df)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:30:21.480154Z","iopub.execute_input":"2025-07-11T07:30:21.480718Z","iopub.status.idle":"2025-07-11T07:30:24.230383Z","shell.execute_reply.started":"2025-07-11T07:30:21.480670Z","shell.execute_reply":"2025-07-11T07:30:24.228979Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ----------- train画像のリサイズとグレースケール化確認-----------\nfor fname in train_df['filepath']:\n    src_path = os.path.join(train_dir, fname)\n    dst_path = os.path.join(train_resized_dir, fname)\n    with Image.open(src_path) as img:\n        # リサイズ後にグレースケールへ変換し、保存する\n        img_converted = img.resize((128, 128)).convert('L')\n        img_converted.save(dst_path)\n\nprint(\"train画像のグレースケール化完了\")\n# ----------- test画像のグレースケール化確認 -----------\nfor fname in test_df['filepath']:\n    src_path = os.path.join(test_dir, fname)\n    dst_path = os.path.join(test_resized_dir, fname)\n    with Image.open(src_path) as img:\n        # リサイズ後にグレースケールへ変換し、保存する\n        img_converted = img.resize((128, 128)).convert('L')\n        img_converted.save(dst_path)\n\nprint(\"test画像のグレースケール化完了\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:43:39.052855Z","iopub.execute_input":"2025-07-11T07:43:39.053227Z","iopub.status.idle":"2025-07-11T07:43:58.189292Z","shell.execute_reply.started":"2025-07-11T07:43:39.053194Z","shell.execute_reply":"2025-07-11T07:43:58.188228Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nimport os\n\n# 確認したい画像が保存されているフォルダ\n# test_128 フォルダも同様に確認できます\ntarget_dir = '/kaggle/working/train_128'\n\n# フォルダ内のファイル名リストを取得\ntry:\n    file_list = os.listdir(target_dir)\n\n    # 最初の5枚だけをサンプルとして確認する\n    for fname in file_list[:5]:\n        image_path = os.path.join(target_dir, fname)\n        with Image.open(image_path) as img:\n            print(f\"ファイル名: {fname}, 画像モード: {img.mode}\")\n            if img.mode == 'L':\n                print(\"✅ 正しくグレースケール化されています。\")\n            else:\n                print(f\"❌ グレースケールではありません。(モード: {img.mode})\")\n            print(\"-\" * 20) # 区切り線\n\nexcept FileNotFoundError:\n    print(f\"エラー: {target_dir} が見つかりません。\")\nexcept IndexError:\n    print(f\"エラー: {target_dir} にファイルがありません。\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:52:09.133507Z","iopub.execute_input":"2025-07-11T07:52:09.133848Z","iopub.status.idle":"2025-07-11T07:52:09.156789Z","shell.execute_reply.started":"2025-07-11T07:52:09.133822Z","shell.execute_reply":"2025-07-11T07:52:09.155662Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nimport os\nimport random # randomライブラリをインポート\n\n# 確認したい画像が保存されているフォルダ\ntarget_dir = '/kaggle/working/train_128'\n\ntry:\n    file_list = os.listdir(target_dir)\n\n    # リストの中からランダムに5つのファイルを選ぶ\n    # ファイル数が5未満の場合は、存在するすべてのファイルを選ぶ\n    num_samples = min(5, len(file_list))\n    if num_samples > 0:\n        sample_files = random.sample(file_list, num_samples)\n    else:\n        sample_files = [] # ファイルがない場合は空のリスト\n\n    if not sample_files:\n        print(f\"フォルダ {target_dir} にファイルがありません。\")\n\n    # サンプル画像をチェック\n    for fname in sample_files:\n        image_path = os.path.join(target_dir, fname)\n        with Image.open(image_path) as img:\n            print(f\"ファイル名: {fname}, 画像モード: {img.mode}\")\n            if img.mode == 'L':\n                print(\"✅ 正しくグレースケール化されています。\")\n            else:\n                print(f\"❌ グレースケールではありません。(モード: {img.mode})\")\n            print(\"-\" * 20) # 区切り線\n\nexcept FileNotFoundError:\n    print(f\"エラー: {target_dir} が見つかりません。\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T07:52:21.466164Z","iopub.execute_input":"2025-07-11T07:52:21.466542Z","iopub.status.idle":"2025-07-11T07:52:21.490897Z","shell.execute_reply.started":"2025-07-11T07:52:21.466517Z","shell.execute_reply":"2025-07-11T07:52:21.489874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom PIL import Image\nimport os\nimport random\n\n# --- 準備：確認用の画像を選ぶ ---\ntarget_dir = '/kaggle/working/train_128'\ntry:\n    # ランダムに1枚選ぶ\n    fname = random.choice(os.listdir(target_dir))\n    image_path = os.path.join(target_dir, fname)\n    print(f\"確認するファイル: {image_path}\")\n\n    # 1. 画像をグレースケールで開く\n    with Image.open(image_path) as img:\n        # 2. 画像をNumPy配列に変換\n        pixel_array = np.array(img)\n\n    # 3. 正規化前のデータを確認\n    print(f\"\\n--- 正規化前 ---\")\n    print(f\"データ型: {pixel_array.dtype}\")\n    print(f\"形状 (高さ, 幅): {pixel_array.shape}\")\n    print(f\"最大値: {pixel_array.max()}, 最小値: {pixel_array.min()}\")\n\n    # 4. 正規化を実行\n    #    255.0で割ることで、データ型が自動的に浮動小数点数(float)になる\n    normalized_array = pixel_array / 255.0\n\n    # 5. 正規化後のデータを確認\n    print(f\"\\n--- 正規化後 ---\")\n    print(f\"データ型: {normalized_array.dtype}\")\n    print(f\"形状 (高さ, 幅): {normalized_array.shape}\")\n    print(f\"最大値: {normalized_array.max()}, 最小値: {normalized_array.min()}\")\n\nexcept (FileNotFoundError, IndexError):\n    print(f\"エラー: {target_dir} に確認できるファイルがありません。\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T08:22:24.915710Z","iopub.execute_input":"2025-07-11T08:22:24.916077Z","iopub.status.idle":"2025-07-11T08:22:24.943242Z","shell.execute_reply.started":"2025-07-11T08:22:24.916053Z","shell.execute_reply":"2025-07-11T08:22:24.942331Z"}},"outputs":[],"execution_count":null}]}