{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"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","execution":{"iopub.status.busy":"2023-07-21T13:41:39.301837Z","iopub.execute_input":"2023-07-21T13:41:39.302454Z","iopub.status.idle":"2023-07-21T13:41:39.349225Z","shell.execute_reply.started":"2023-07-21T13:41:39.302414Z","shell.execute_reply":"2023-07-21T13:41:39.348078Z"},"trusted":true},"execution_count":1,"outputs":[{"name":"stdout","text":"/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv\n/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\n/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip\n","output_type":"stream"}]},{"cell_type":"code","source":"import zipfile\n\n# train.zipの展開\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/train')\n\n# test.zipの展開\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/test')","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:39.352072Z","iopub.execute_input":"2023-07-21T13:41:39.354429Z","iopub.status.idle":"2023-07-21T13:41:57.33835Z","shell.execute_reply.started":"2023-07-21T13:41:39.354358Z","shell.execute_reply":"2023-07-21T13:41:57.337256Z"},"trusted":true},"execution_count":2,"outputs":[]},{"cell_type":"code","source":"# 新しいディレクトリのパスを指定\ndirectory_path = [\n    \"/kaggle/working/data/train/dogs\",\n    \"/kaggle/working/data/train/cats\",\n    \"/kaggle/working/data/valid/dogs\",\n    \"/kaggle/working/data/valid/cats\",\n    \"/kaggle/working/data/test\",\n]\n\n# ディレクトリを作成\nfor path in directory_path:\n    os.makedirs(path, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:57.340049Z","iopub.execute_input":"2023-07-21T13:41:57.340415Z","iopub.status.idle":"2023-07-21T13:41:57.34701Z","shell.execute_reply.started":"2023-07-21T13:41:57.340381Z","shell.execute_reply":"2023-07-21T13:41:57.345487Z"},"trusted":true},"execution_count":3,"outputs":[]},{"cell_type":"code","source":"import shutil\nimport glob\n\nsource_directory = \"/kaggle/working/train/train\"\ndirectory = [\n    \"/kaggle/working/data/train/dogs\",\n    \"/kaggle/working/data/train/cats\",\n]\ntest_source_directory = \"/kaggle/working/test/test\"\ntest_directory = \"/kaggle/working/data/test/\"\n\nCATEGORIES = [\"dog.\", \"cat.\"]\n\n# 訓練(train)データの画像ファイルを所定の場所へを移動\nfor key,DIR in zip(CATEGORIES,directory):\n    files = [file for file in os.listdir(source_directory) if file.startswith(key)]\n    for file in files:\n        source_path = os.path.join(source_directory, file)\n        destination_path = os.path.join(DIR, file)\n        shutil.move(source_path, destination_path)\n\n# テスト(test)データの画像ファイルを所定の場所へを移動\nfiles = [file for file in os.listdir(test_source_directory) if file.endswith(\".jpg\")]\nfor file in files:\n    source_path = os.path.join(test_source_directory, file)\n    destination_path = os.path.join(test_directory, file)\n    shutil.move(source_path, destination_path)","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:57.348853Z","iopub.execute_input":"2023-07-21T13:41:57.349419Z","iopub.status.idle":"2023-07-21T13:41:58.918446Z","shell.execute_reply.started":"2023-07-21T13:41:57.349369Z","shell.execute_reply":"2023-07-21T13:41:58.917169Z"},"trusted":true},"execution_count":4,"outputs":[]},{"cell_type":"code","source":"dogs_directory = \"/kaggle/working/data/train/dogs\"\ncats_directory = \"/kaggle/working/data/train/cats\"\ntest_directory = \"/kaggle/working/data/test/\"\n\n# dogsディレクトリ内のファイルを表示\nprint(\"Dogs:\")\ndog_files = os.listdir(dogs_directory)\nprint(f'file number : {len(dog_files)}')\nfor file in dog_files[:5]:\n    print(file)\n\n# catsディレクトリ内のファイルを表示\nprint(\"\\nCats:\")\ncat_files = os.listdir(cats_directory)\nprint(f'file number : {len(cat_files)}')\nfor file in cat_files[:5]:\n    print(file)\n\n# dogsディレクトリ内のファイルを表示\nprint(\"\\ntest:\")\ntest_files = os.listdir(test_directory)\nprint(f'file number : {len(test_files)}')\nfor file in test_files[:5]:\n    print(file)","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:58.921572Z","iopub.execute_input":"2023-07-21T13:41:58.921936Z","iopub.status.idle":"2023-07-21T13:41:58.95609Z","shell.execute_reply.started":"2023-07-21T13:41:58.921906Z","shell.execute_reply":"2023-07-21T13:41:58.954926Z"},"trusted":true},"execution_count":5,"outputs":[{"name":"stdout","text":"Dogs:\nfile number : 12500\ndog.9214.jpg\ndog.7350.jpg\ndog.9374.jpg\ndog.2419.jpg\ndog.5617.jpg\n\nCats:\nfile number : 12500\ncat.8354.jpg\ncat.4814.jpg\ncat.2784.jpg\ncat.11153.jpg\ncat.12320.jpg\n\ntest:\nfile number : 12500\n7711.jpg\n2371.jpg\n9872.jpg\n4403.jpg\n4680.jpg\n","output_type":"stream"}]},{"cell_type":"code","source":"! pip install --upgrade tensorflow-io\nimport matplotlib.pyplot as plt\nimport cv2\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.utils import to_categorical","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:41:58.957704Z","iopub.execute_input":"2023-07-21T13:41:58.958176Z","iopub.status.idle":"2023-07-21T13:42:30.555371Z","shell.execute_reply.started":"2023-07-21T13:41:58.958141Z","shell.execute_reply":"2023-07-21T13:42:30.554092Z"},"trusted":true},"execution_count":6,"outputs":[{"name":"stdout","text":"Requirement already satisfied: tensorflow-io in /opt/conda/lib/python3.10/site-packages (0.31.0)\nCollecting tensorflow-io\n  Downloading tensorflow_io-0.32.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (28.0 MB)\n\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m28.0/28.0 MB\u001b[0m \u001b[31m35.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n\u001b[?25hCollecting tensorflow-io-gcs-filesystem==0.32.0 (from tensorflow-io)\n  Downloading tensorflow_io_gcs_filesystem-0.32.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.4 MB)\n\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.4/2.4 MB\u001b[0m \u001b[31m59.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m:00:01\u001b[0m\n\u001b[?25hInstalling collected packages: tensorflow-io-gcs-filesystem, tensorflow-io\n  Attempting uninstall: tensorflow-io-gcs-filesystem\n    Found existing installation: tensorflow-io-gcs-filesystem 0.31.0\n    Uninstalling tensorflow-io-gcs-filesystem-0.31.0:\n      Successfully uninstalled tensorflow-io-gcs-filesystem-0.31.0\n  Attempting uninstall: tensorflow-io\n    Found existing installation: tensorflow-io 0.31.0\n    Uninstalling tensorflow-io-0.31.0:\n      Successfully uninstalled tensorflow-io-0.31.0\nSuccessfully installed tensorflow-io-0.32.0 tensorflow-io-gcs-filesystem-0.32.0\n","output_type":"stream"},{"name":"stderr","text":"/opt/conda/lib/python3.10/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.5\n  warnings.warn(f\"A NumPy version >={np_minversion} and <{np_maxversion}\"\n","output_type":"stream"}]},{"cell_type":"code","source":"# -------------------------------------------------------------------\n# 定数の定義\n# -------------------------------------------------------------------\nDATADIR = \"/kaggle/working/data/train\"\n# MODEL_DIR = \"/content/drive/MyDrive\"\nCATEGORIES = [\"dogs\", \"cats\"]\n\n# -------------------------------------------------------------------\n# メイン処理（画像を読込み、犬猫データセットを設定）\n# -------------------------------------------------------------------\n#犬猫データセットを定義\nfeature_data = []\nlabel_data = []\n    \n# 平均画像サイズ\ntarget_size = (128, 128)\nprint(target_size)\n\n#画像を読込み、犬猫データセットを設定\n#（0:Dog、1:Cat)…class_numはCATEGORIESの配列index／categoryはCATEGORIESの中身　\nfor class_num, category in enumerate(CATEGORIES):\n    #ディレクトリを設定（ループ1回目：./PetImages/Dog　2回目：./PetImages/Cat)\n    path = os.path.join(DATADIR, category)\n    for image_name in os.listdir(path):\n        try:\n            img_file = cv2.imread(os.path.join(path, image_name))# 画像読み込み\n            gray_image = cv2.cvtColor(img_file, cv2.COLOR_BGR2GRAY)\n            resize_file = cv2.resize(gray_image, (target_size))# 画像のリサイズ\n            feature_data.append(resize_file)\n            label_data.append(class_num)# 画像データ(犬 or 猫)、ラベル情報(0 or 1)を追加\n        except Exception as e:\n            #画像の読込みエラーはスルー（スキップして次の画像へ）\n            print(\"skiped.\")\n            pass\n    print(f\"{category}finish.\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:42:30.556965Z","iopub.execute_input":"2023-07-21T13:42:30.557706Z","iopub.status.idle":"2023-07-21T13:43:45.171662Z","shell.execute_reply.started":"2023-07-21T13:42:30.557671Z","shell.execute_reply":"2023-07-21T13:43:45.170263Z"},"trusted":true},"execution_count":7,"outputs":[{"name":"stdout","text":"(128, 128)\ndogsfinish.\ncatsfinish.\n","output_type":"stream"}]},{"cell_type":"code","source":"train_x, valid_x, train_y, valid_y = train_test_split(feature_data, label_data, test_size=0.1)","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:43:45.173095Z","iopub.execute_input":"2023-07-21T13:43:45.173449Z","iopub.status.idle":"2023-07-21T13:43:45.198457Z","shell.execute_reply.started":"2023-07-21T13:43:45.173411Z","shell.execute_reply":"2023-07-21T13:43:45.197164Z"},"trusted":true},"execution_count":8,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf # TensorFlowライブラリをロード\n# データ変換(正規化とテンソル変換)\ndef convert_data(x,y):\n    batch,a,b = x.shape # データの形（シェイプ）を取得（32×28×28）\n    x = tf.reshape(x,(batch,a,b,1)) # 1チャンネル分増やし，4次元テンソルに変換\n    x = tf.cast(x,tf.float32) # float32に変換\n    x /= 255. # 正規化\n    return x, tf.cast(y,tf.int32)\n\n#\n# tf.Dataによるtf.Tensor変換\n#\n\ntrain_ds = tf.data.Dataset.from_tensor_slices((train_x,train_y)) # 訓練セットの入力と教師ラベルを合体させてTensorに変換\nvalid_ds = tf.data.Dataset.from_tensor_slices((valid_x,valid_y)) # 検証用も同様に処理\nAUTOTUNE = tf.data.experimental.AUTOTUNE # 自動チューニング設定 (おまじない)\n\ntrain_ds = train_ds.shuffle(len(train_x)) # 訓練データをシャッフルする\ntrain_ds = train_ds.repeat(1) # １epochで使われるデータの回数。１の場合１epochで１回しか使われない。引数を空欄にすると無限に使われる\ntrain_ds = train_ds.batch(32) # ミニパッチを作る。１パッチ３２個のデータ。\ntrain_ds = train_ds.map(lambda x, y: tf.py_function(convert_data, [x, y], Tout=[tf.float32, tf.int32]))\ntrain_ds = train_ds.prefetch(buffer_size=AUTOTUNE) # 訓練中に次のパッチを取り出すための処理\n\nvalid_ds = valid_ds.batch(32) # 検証データはシャッフルする必要がないので,パッチ化のみの処理\nvalid_ds = valid_ds.map(lambda x, y: tf.py_function(convert_data, [x, y], Tout=[tf.float32, tf.int32]))","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:43:45.199947Z","iopub.execute_input":"2023-07-21T13:43:45.200327Z","iopub.status.idle":"2023-07-21T13:45:29.844552Z","shell.execute_reply.started":"2023-07-21T13:43:45.200295Z","shell.execute_reply":"2023-07-21T13:45:29.843342Z"},"trusted":true},"execution_count":9,"outputs":[]},{"cell_type":"code","source":"# 入力層\ninput = tf.keras.layers.Input(shape=(128,128,1), name='input') # ⼊⼒層の定義\n# CNN 第一層\nh = tf.keras.layers.Conv2D(32, (9, 9), activation='relu', name='cnn01')(input)\nh = tf.keras.layers.MaxPooling2D((2, 2), name='pool01')(h)\n# CNN 第二層\nh = tf.keras.layers.Conv2D(32, (5, 5), activation='relu', name='cnn02')(h)\nh = tf.keras.layers.MaxPooling2D((2, 2), name='pool02')(h)\n# CNN 第三層\nh = tf.keras.layers.Conv2D(64, (5, 5), activation='relu', name='cnn03')(h)\nh = tf.keras.layers.MaxPooling2D((2, 2), name='pool03')(h)\n# CNN 第四層\nh = tf.keras.layers.Conv2D(64, (5, 5), activation='relu', name='cnn04')(h)\nh = tf.keras.layers.MaxPooling2D((2, 2), name='pool04')(h)\n# 1次元テンソルに変換する。フラット化。\nh = tf.keras.layers.Flatten(name='flatten')(h)\n# 全結合層 隠れ層のノードは 256\nh = tf.keras.layers.Dense(256, activation='relu', name='dense01')(h)\n# 出力層\noutput = tf.keras.layers.Dense(2, activation='softmax', name='output')(h) # 出⼒層\n# この処理でモデルを実体化する。⼊⼒層と出⼒層を渡すと⾃動的にネットワークを構築してくれる。\nmodel = tf.keras.Model(inputs=input, outputs=output)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:45:29.845905Z","iopub.execute_input":"2023-07-21T13:45:29.846279Z","iopub.status.idle":"2023-07-21T13:45:30.092673Z","shell.execute_reply.started":"2023-07-21T13:45:29.846247Z","shell.execute_reply":"2023-07-21T13:45:30.091528Z"},"trusted":true},"execution_count":10,"outputs":[{"name":"stdout","text":"Model: \"model\"\n_________________________________________________________________\n Layer (type)                Output Shape              Param #   \n=================================================================\n input (InputLayer)          [(None, 128, 128, 1)]     0         \n                                                                 \n cnn01 (Conv2D)              (None, 120, 120, 32)      2624      \n                                                                 \n pool01 (MaxPooling2D)       (None, 60, 60, 32)        0         \n                                                                 \n cnn02 (Conv2D)              (None, 56, 56, 32)        25632     \n                                                                 \n pool02 (MaxPooling2D)       (None, 28, 28, 32)        0         \n                                                                 \n cnn03 (Conv2D)              (None, 24, 24, 64)        51264     \n                                                                 \n pool03 (MaxPooling2D)       (None, 12, 12, 64)        0         \n                                                                 \n cnn04 (Conv2D)              (None, 8, 8, 64)          102464    \n                                                                 \n pool04 (MaxPooling2D)       (None, 4, 4, 64)          0         \n                                                                 \n flatten (Flatten)           (None, 1024)              0         \n                                                                 \n dense01 (Dense)             (None, 256)               262400    \n                                                                 \n output (Dense)              (None, 2)                 514       \n                                                                 \n=================================================================\nTotal params: 444,898\nTrainable params: 444,898\nNon-trainable params: 0\n_________________________________________________________________\n","output_type":"stream"}]},{"cell_type":"code","source":"# 学習のためのmodelの設定（楽する⽅法）\n# model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics='accuracy')\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])\nmodel.fit(train_ds,epochs=5,validation_data=valid_ds)","metadata":{"execution":{"iopub.status.busy":"2023-07-21T13:45:30.09438Z","iopub.execute_input":"2023-07-21T13:45:30.095223Z","iopub.status.idle":"2023-07-21T14:37:35.116045Z","shell.execute_reply.started":"2023-07-21T13:45:30.095178Z","shell.execute_reply":"2023-07-21T14:37:35.114456Z"},"trusted":true},"execution_count":11,"outputs":[{"name":"stdout","text":"Epoch 1/5\n704/704 [==============================] - 637s 902ms/step - loss: 0.6785 - sparse_categorical_accuracy: 0.5656 - val_loss: 0.6291 - val_sparse_categorical_accuracy: 0.6556\nEpoch 2/5\n704/704 [==============================] - 606s 861ms/step - loss: 0.5984 - sparse_categorical_accuracy: 0.6780 - val_loss: 0.5502 - val_sparse_categorical_accuracy: 0.7252\nEpoch 3/5\n704/704 [==============================] - 602s 856ms/step - loss: 0.5096 - sparse_categorical_accuracy: 0.7496 - val_loss: 0.4836 - val_sparse_categorical_accuracy: 0.7720\nEpoch 4/5\n704/704 [==============================] - 611s 868ms/step - loss: 0.4400 - sparse_categorical_accuracy: 0.7942 - val_loss: 0.4291 - val_sparse_categorical_accuracy: 0.8096\nEpoch 5/5\n704/704 [==============================] - 599s 851ms/step - loss: 0.3802 - sparse_categorical_accuracy: 0.8270 - val_loss: 0.4089 - val_sparse_categorical_accuracy: 0.8272\n","output_type":"stream"},{"execution_count":11,"output_type":"execute_result","data":{"text/plain":"<keras.callbacks.History at 0x7d19fc5e6080>"},"metadata":{}}]},{"cell_type":"code","source":"TESTDIR = \"/kaggle/working/data/test\"\n# MODEL_DIR = \"/content/drive/MyDrive\"\nCATEGORIES = [\"dogs\", \"cats\"]\n\n# -------------------------------------------------------------------\n# メイン処理（画像を読込み、犬猫データセットを設定）\n# -------------------------------------------------------------------\n#犬猫データセットを定義\nfeature_test_data = []\nlabel_test_data = []\n    \n# 平均画像サイズ\ntarget_size = (128, 128)\nprint(f'target_size = {target_size}')\n\n#画像を読込み、犬猫データセットを設定\nfor image_name in os.listdir(TESTDIR):\n    try:\n        img_file = cv2.imread(os.path.join(TESTDIR, image_name))# 画像読み込み\n        gray_image = cv2.cvtColor(img_file, cv2.COLOR_BGR2GRAY)\n        resize_file = cv2.resize(gray_image, (target_size))# 画像のリサイズ\n        feature_test_data.append(resize_file)\n        #label_test_data.append(class_num)# 画像データ(犬 or 猫)、ラベル情報(0 or 1)を追加\n    except Exception as e:\n        #画像の読込みエラーはスルー（スキップして次の画像へ）\n        print(\"skiped.\")\n        pass\nprint(f\"finish.\")","metadata":{"execution":{"iopub.status.busy":"2023-07-21T14:37:35.118862Z","iopub.execute_input":"2023-07-21T14:37:35.119296Z","iopub.status.idle":"2023-07-21T14:38:12.340604Z","shell.execute_reply.started":"2023-07-21T14:37:35.119262Z","shell.execute_reply":"2023-07-21T14:38:12.339401Z"},"trusted":true},"execution_count":12,"outputs":[{"name":"stdout","text":"target_size = (128, 128)\nfinish.\n","output_type":"stream"}]},{"cell_type":"code","source":"# テストデータの変換\n# X_test = X_test.reshape(X_test.shape[0], 28, 28)\n\ndef convert_data_test(x):\n    batch,a,b = x.shape # データの形（シェイプ）を取得（32×28×28）\n    x = tf.reshape(x,(batch,a,b,1)) # 1チャンネル分増やし，4次元テンソルに変換\n    x = tf.cast(x,tf.float32) # float32に変換\n    x /= 255. # 正規化\n    return x\n\ntest_ds = tf.data.Dataset.from_tensor_slices(feature_test_data) # 検証用も同様に処理\nAUTOTUNE = tf.data.experimental.AUTOTUNE # 自動チューニング設定 (おまじない)\n\ntest_ds = test_ds.batch(32) # 検証データはシャッフルする必要がないので,パッチ化のみの処理\ntest_ds = test_ds.map(lambda x: tf.py_function(convert_data_test, [x], Tout=[tf.float32]))\n\n#X_test, _ = convert_data(X_test, y_test)","metadata":{"execution":{"iopub.status.busy":"2023-07-21T14:38:12.342047Z","iopub.execute_input":"2023-07-21T14:38:12.342393Z","iopub.status.idle":"2023-07-21T14:39:05.923922Z","shell.execute_reply.started":"2023-07-21T14:38:12.342363Z","shell.execute_reply":"2023-07-21T14:39:05.922584Z"},"trusted":true},"execution_count":13,"outputs":[]},{"cell_type":"code","source":"# テストデータの予測\ny_pred = model.predict(test_ds)\n\n# 予測結果の正解率の計算\npredictions = tf.argmax(y_pred, axis=1)\npredictions","metadata":{"execution":{"iopub.status.busy":"2023-07-21T14:39:05.928603Z","iopub.execute_input":"2023-07-21T14:39:05.929047Z","iopub.status.idle":"2023-07-21T14:40:16.227072Z","shell.execute_reply.started":"2023-07-21T14:39:05.929008Z","shell.execute_reply":"2023-07-21T14:40:16.225771Z"},"trusted":true},"execution_count":14,"outputs":[{"name":"stdout","text":"391/391 [==============================] - 70s 178ms/step\n","output_type":"stream"},{"execution_count":14,"output_type":"execute_result","data":{"text/plain":"<tf.Tensor: shape=(12500,), dtype=int64, numpy=array([0, 1, 1, ..., 0, 1, 0])>"},"metadata":{}}]},{"cell_type":"code","source":"pred_pd = pd.DataFrame(y_pred)\n# id列を作成\npred_pd.insert(0, 'id', range(1, len(pred_pd) + 1))\npred_pd.columns\npred_pd = pred_pd.drop([0], axis=1)\npred_pd = pred_pd.rename(columns={1: 'label'})\npred_pd","metadata":{"execution":{"iopub.status.busy":"2023-07-21T14:40:16.229182Z","iopub.execute_input":"2023-07-21T14:40:16.229762Z","iopub.status.idle":"2023-07-21T14:40:16.280483Z","shell.execute_reply.started":"2023-07-21T14:40:16.229715Z","shell.execute_reply":"2023-07-21T14:40:16.279183Z"},"trusted":true},"execution_count":15,"outputs":[{"execution_count":15,"output_type":"execute_result","data":{"text/plain":"          id     label\n0          1  0.169974\n1          2  0.908299\n2          3  0.955247\n3          4  0.417103\n4          5  0.712660\n...      ...       ...\n12495  12496  0.998131\n12496  12497  0.418615\n12497  12498  0.031554\n12498  12499  0.870454\n12499  12500  0.045903\n\n[12500 rows x 2 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>label</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>0.169974</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>0.908299</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>3</td>\n      <td>0.955247</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>0.417103</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>5</td>\n      <td>0.712660</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>12495</th>\n      <td>12496</td>\n      <td>0.998131</td>\n    </tr>\n    <tr>\n      <th>12496</th>\n      <td>12497</td>\n      <td>0.418615</td>\n    </tr>\n    <tr>\n      <th>12497</th>\n      <td>12498</td>\n      <td>0.031554</td>\n    </tr>\n    <tr>\n      <th>12498</th>\n      <td>12499</td>\n      <td>0.870454</td>\n    </tr>\n    <tr>\n      <th>12499</th>\n      <td>12500</td>\n      <td>0.045903</td>\n    </tr>\n  </tbody>\n</table>\n<p>12500 rows × 2 columns</p>\n</div>"},"metadata":{}}]},{"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv') # ひな形ファイルを読み込む\nprint(sub.shape)\n# subのlabel列をtest_predictedのlabel列で上書きする\nsub['label'] = pred_pd['label']\n# 結果を表示\nsub\nsub.to_csv('submission.csv', index=False) # 変換したファイルを保存","metadata":{"execution":{"iopub.status.busy":"2023-07-21T14:40:16.282001Z","iopub.execute_input":"2023-07-21T14:40:16.282354Z","iopub.status.idle":"2023-07-21T14:40:16.36029Z","shell.execute_reply.started":"2023-07-21T14:40:16.282325Z","shell.execute_reply":"2023-07-21T14:40:16.358905Z"},"trusted":true},"execution_count":16,"outputs":[{"name":"stdout","text":"(12500, 2)\n","output_type":"stream"}]}]}