{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"isSourceIdPinned":false,"sourceType":"competition"}],"dockerImageVersionId":31089,"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-11T06:27:08.527098Z","iopub.execute_input":"2025-07-11T06:27:08.527496Z","iopub.status.idle":"2025-07-11T06:27:08.535867Z","shell.execute_reply.started":"2025-07-11T06:27:08.527469Z","shell.execute_reply":"2025-07-11T06:27:08.534865Z"}},"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-11T06:27:08.537393Z","iopub.execute_input":"2025-07-11T06:27:08.537691Z","iopub.status.idle":"2025-07-11T06:27:08.582445Z","shell.execute_reply.started":"2025-07-11T06:27:08.537671Z","shell.execute_reply":"2025-07-11T06:27:08.580683Z"}},"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-11T06:27:08.5833Z","iopub.status.idle":"2025-07-11T06:27:08.583624Z","shell.execute_reply.started":"2025-07-11T06:27:08.583469Z","shell.execute_reply":"2025-07-11T06:27:08.583482Z"}},"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-11T06:27:08.584749Z","iopub.status.idle":"2025-07-11T06:27:08.585135Z","shell.execute_reply.started":"2025-07-11T06:27:08.584935Z","shell.execute_reply":"2025-07-11T06:27:08.584954Z"}},"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-11T06:27:08.586438Z","iopub.status.idle":"2025-07-11T06:27:08.586755Z","shell.execute_reply.started":"2025-07-11T06:27:08.586605Z","shell.execute_reply":"2025-07-11T06:27:08.586617Z"}},"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-11T06:27:08.588152Z","iopub.status.idle":"2025-07-11T06:27:08.588413Z","shell.execute_reply.started":"2025-07-11T06:27:08.588294Z","shell.execute_reply":"2025-07-11T06:27:08.588305Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport zipfile\n\n# Zipファイルへのパス\nzip_file_path = '/kaggle/input/dogs-vs-cats/train.zip' # zipファイル名が異なる場合は調整してください\nextract_dir = '/kaggle/working/train_data' # ファイルを解凍するための一時ディレクトリ\n\n# 解凍ディレクトリが存在しない場合は作成します\nos.makedirs(extract_dir, exist_ok=True)\n\n# ファイルを解凍します\nwith zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_dir)\n\nfilepaths = []\n# 解凍されたディレクトリを反復処理します\nfor fname in os.listdir(extract_dir):\n    if fname.endswith('.jpg'):\n        filepaths.append(f'{extract_dir}/{fname}')\n\nprint(f\"見つかった画像ファイルの数: {len(filepaths)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T06:27:08.714057Z","iopub.execute_input":"2025-07-11T06:27:08.714459Z","iopub.status.idle":"2025-07-11T06:27:16.675171Z","shell.execute_reply.started":"2025-07-11T06:27:08.714433Z","shell.execute_reply":"2025-07-11T06:27:16.67425Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nprint(\"--- /kaggle/input/ 以下のファイル一覧 ---\")\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        full_path = os.path.join(dirname, filename)\n        print(full_path)\nprint(\"------------------------------------------\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T06:27:16.676787Z","iopub.execute_input":"2025-07-11T06:27:16.67708Z","iopub.status.idle":"2025-07-11T06:27:16.683945Z","shell.execute_reply.started":"2025-07-11T06:27:16.677059Z","shell.execute_reply":"2025-07-11T06:27:16.683053Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport zipfile\n\nzip_file_path = '/kaggle/input/dogs-vs-cats/train.zip' # ★ os.walkの結果に合わせてパスを調整\nextract_dir = '/kaggle/working/train_data_unzipped' # 解凍先ディレクトリ。Kaggleでは'/kaggle/working/'以下が書き込み可能\n\n# 解凍先ディレクトリを作成 (既に存在する場合は何もしない)\nos.makedirs(extract_dir, exist_ok=True)\n\n# ZIPファイルを解凍\nprint(f\"'{zip_file_path}' を '{extract_dir}' に解凍中...\")\nwith zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_dir)\nprint(\"解凍完了！\")\n\n# 解凍されたディレクトリ内の画像ファイルを探索\nfilepaths = []\n# os.walkを使って、解凍されたディレクトリのサブディレクトリも探索します\nfor root, _, files in os.walk(extract_dir):\n    for file in files:\n        if file.lower().endswith('.jpg'): # 拡張子は大文字・小文字両方に対応\n            filepaths.append(os.path.join(root, file))\n\nprint(f\"見つかった画像ファイルの数 (解凍後): {len(filepaths)}\")\n# 最初の5つのパスを表示して確認\nif len(filepaths) > 0:\n    print(\"最初の5つの画像ファイルパス:\")\n    for i in range(min(5, len(filepaths))):\n        print(filepaths[i])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T06:27:16.684748Z","iopub.execute_input":"2025-07-11T06:27:16.684963Z","iopub.status.idle":"2025-07-11T06:27:24.660456Z","shell.execute_reply.started":"2025-07-11T06:27:16.684947Z","shell.execute_reply":"2025-07-11T06:27:24.65958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nimport zipfile\n\n# --- 1. データセットの解凍 (まだ解凍されていない場合) ---\nzip_file_path = '/kaggle/input/dogs-vs-cats/train.zip'\nextract_dir = '/kaggle/working/train_data_unzipped' # ここに以前解凍しました\n\n# 解凍先ディレクトリを作成 (既に存在する場合は何もしない)\nos.makedirs(extract_dir, exist_ok=True)\n\n# ターゲットディレクトリが空の場合、または存在しない場合にのみファイルを解凍\n# これにより、ノートブックが再実行されたときに再解凍されるのを防ぎます\nif not os.path.exists(os.path.join(extract_dir, 'train')) or not os.listdir(os.path.join(extract_dir, 'train')):\n    print(f\"'{zip_file_path}' を '{extract_dir}' に解凍中...\")\n    with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n        zip_ref.extractall(extract_dir)\n    print(\"解凍完了！\")\nelse:\n    print(\"データは既に解凍されています。\")\n\n# --- 2. ファイル名とラベルの抽出 (解凍されたパスを使用) ---\n# 'train' ディレクトリは 'train_data_unzipped' の中にあります\ndata_directory = os.path.join(extract_dir, 'train') # 解凍された 'train' フォルダへの正しいパス\n\nfilepaths = []\nlabels = []\n\n# os.listdirを使用して、指定されたディレクトリ内のファイルを取得します\n# このデータセットのtrainフォルダは直下に画像があるため、これで十分です\nfor fname in os.listdir(data_directory):\n    if fname.lower().endswith('.jpg'): # 拡張子は大文字・小文字両方に対応\n        filepaths.append(os.path.join(data_directory, fname))\n        labels.append('dog' if 'dog' in fname else 'cat')\n\ndf = pd.DataFrame({'filename': filepaths, 'class': labels})\n\nprint(f\"データフレームに {len(df)} 件のファイルパスとラベルを読み込みました。\")\nprint(df.head()) # 確認のためにDataFrameの先頭を表示\n\n# --- 3. ImageDataGeneratorとflow_from_dataframe ---\ndatagen = ImageDataGenerator(rescale=1./255)\n\ngenerator = datagen.flow_from_dataframe(\n    dataframe=df,\n    x_col='filename',\n    y_col='class',\n    target_size=(150, 150),\n    class_mode='binary',\n    batch_size=32\n)\n\n# --- 4. 正規化の確認 ---\nimages, labels_batch = next(generator) # 'labels'は既に変数名として使われているので'labels_batch'に変更\nprint(\"\\n正規化の確認:\")\nprint(\"min:\", images.min(), \"max:\", images.max())\nprint(\"dtype:\", images.dtype)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-11T06:29:30.015689Z","iopub.execute_input":"2025-07-11T06:29:30.016444Z","iopub.status.idle":"2025-07-11T06:29:30.377109Z","shell.execute_reply.started":"2025-07-11T06:29:30.016417Z","shell.execute_reply":"2025-07-11T06:29:30.376363Z"}},"outputs":[],"execution_count":null}]}