{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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-24T04:10:59.726159Z","iopub.execute_input":"2023-07-24T04:10:59.726484Z","iopub.status.idle":"2023-07-24T04:10:59.74069Z","shell.execute_reply.started":"2023-07-24T04:10:59.72646Z","shell.execute_reply":"2023-07-24T04:10:59.739455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# データの準備\n\n- zipファイルを展開する\n- 学習で使用するディレクトリを作る\n- 学習で使用するディレクトリに画像ファイルを移動させる","metadata":{}},{"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')\n","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:10:59.747371Z","iopub.execute_input":"2023-07-24T04:10:59.748317Z","iopub.status.idle":"2023-07-24T04:11:14.646011Z","shell.execute_reply.started":"2023-07-24T04:10:59.748284Z","shell.execute_reply":"2023-07-24T04:11:14.645054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ディレクトリの作成","metadata":{}},{"cell_type":"code","source":"import os\n\n# 新しいディレクトリのパスを指定\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)\n","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:11:14.647334Z","iopub.execute_input":"2023-07-24T04:11:14.650035Z","iopub.status.idle":"2023-07-24T04:11:14.655896Z","shell.execute_reply.started":"2023-07-24T04:11:14.649984Z","shell.execute_reply":"2023-07-24T04:11:14.654792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## データの移動","metadata":{}},{"cell_type":"code","source":"import os\nimport 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-24T04:11:14.659506Z","iopub.execute_input":"2023-07-24T04:11:14.660474Z","iopub.status.idle":"2023-07-24T04:11:19.082452Z","shell.execute_reply.started":"2023-07-24T04:11:14.660441Z","shell.execute_reply":"2023-07-24T04:11:19.081442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 確認用","metadata":{}},{"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)\n","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:11:19.083984Z","iopub.execute_input":"2023-07-24T04:11:19.084347Z","iopub.status.idle":"2023-07-24T04:11:19.115611Z","shell.execute_reply.started":"2023-07-24T04:11:19.084314Z","shell.execute_reply":"2023-07-24T04:11:19.114528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 学習の準備","metadata":{}},{"cell_type":"markdown","source":"## 使用するライブラリのインポート","metadata":{}},{"cell_type":"code","source":"# -------------------------------------------------------------------\n# 各種ライブラリのインポート\n# -------------------------------------------------------------------\n! pip install --upgrade tensorflow-io\nimport matplotlib.pyplot as plt\nimport glob\nimport cv2\nimport pandas as pd\nimport numpy as np\nimport random           #乱数生成\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\nfrom keras import backend as K\n\n# random_int = np.random.randint(1, 100000001)  # 1~1億の中からランダムで選ぶ\n# print(\"Random integer:\", random_int)\n\ntf.config.threading.set_intra_op_parallelism_threads(1)\ntf.config.threading.set_inter_op_parallelism_threads(1)\n\ndef seed_everything(seed): #再現性の為に乱数シードを固定する為の関数\n    random.seed(seed) #乱数のシード\n    os.environ['PYTHONHASHSEED'] = str(seed) #osのシード\n    np.random.seed(seed) #npの乱数シード\n    tf.random.set_seed(seed) #tfの乱数シード\n\nseed_everything(88710077) ","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:11:19.117208Z","iopub.execute_input":"2023-07-24T04:11:19.11772Z","iopub.status.idle":"2023-07-24T04:11:35.710596Z","shell.execute_reply.started":"2023-07-24T04:11:19.117688Z","shell.execute_reply":"2023-07-24T04:11:35.70953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## モデルに入力出来るようにデータの形を変形","metadata":{}},{"cell_type":"code","source":"# -------------------------------------------------------------------\n# 定数の定義\n# -------------------------------------------------------------------\nDATADIR = \"/kaggle/working/data/train\"\n# MODEL_DIR = \"/content/drive/MyDrive\"\nCATEGORIES = [\"cats\", \"dogs\"]\n\n# -------------------------------------------------------------------\n# メイン処理（画像を読込み、犬猫データセットを設定）\n# -------------------------------------------------------------------\n#犬猫データセットを定義\nfeature_data = []\nlabel_data = []\n    \n# 平均画像サイズ\ntarget_size = (128, 128)\nprint(target_size)\n\n#画像を読込み、犬猫データセットを設定\n#（0:Cat、1:Dog)…class_numはCATEGORIESの配列index／categoryはCATEGORIESの中身　\nfor class_num, category in enumerate(CATEGORIES):\n    #ディレクトリを設定（ループ1回目：./PetImages/Cat　2回目：./PetImages/Dog)\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-24T04:11:35.712269Z","iopub.execute_input":"2023-07-24T04:11:35.713025Z","iopub.status.idle":"2023-07-24T04:12:36.961732Z","shell.execute_reply.started":"2023-07-24T04:11:35.712972Z","shell.execute_reply":"2023-07-24T04:12:36.960698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 訓練データと検証データに分割","metadata":{}},{"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-24T04:12:36.963397Z","iopub.execute_input":"2023-07-24T04:12:36.963773Z","iopub.status.idle":"2023-07-24T04:12:36.984534Z","shell.execute_reply.started":"2023-07-24T04:12:36.963739Z","shell.execute_reply":"2023-07-24T04:12:36.983652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## モデルに入力出来るようにデータの形を変形（最終調整）","metadata":{}},{"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-24T04:12:36.986045Z","iopub.execute_input":"2023-07-24T04:12:36.986397Z","iopub.status.idle":"2023-07-24T04:14:05.986327Z","shell.execute_reply.started":"2023-07-24T04:12:36.986365Z","shell.execute_reply":"2023-07-24T04:14:05.98537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 確認用","metadata":{}},{"cell_type":"code","source":"train_ds","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:14:05.987659Z","iopub.execute_input":"2023-07-24T04:14:05.989523Z","iopub.status.idle":"2023-07-24T04:14:05.99739Z","shell.execute_reply.started":"2023-07-24T04:14:05.989488Z","shell.execute_reply":"2023-07-24T04:14:05.996462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## モデルの作成","metadata":{}},{"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-24T04:14:05.998806Z","iopub.execute_input":"2023-07-24T04:14:05.999422Z","iopub.status.idle":"2023-07-24T04:14:06.147582Z","shell.execute_reply.started":"2023-07-24T04:14:05.999388Z","shell.execute_reply":"2023-07-24T04:14:06.146858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## モデルの設定","metadata":{}},{"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()])","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:14:06.148603Z","iopub.execute_input":"2023-07-24T04:14:06.148941Z","iopub.status.idle":"2023-07-24T04:14:06.181612Z","shell.execute_reply.started":"2023-07-24T04:14:06.148898Z","shell.execute_reply":"2023-07-24T04:14:06.180681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## モデルを学習","metadata":{}},{"cell_type":"code","source":"history = model.fit(train_ds,epochs=25,validation_data=valid_ds)","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:14:06.18632Z","iopub.execute_input":"2023-07-24T04:14:06.186893Z","iopub.status.idle":"2023-07-24T04:17:59.177938Z","shell.execute_reply.started":"2023-07-24T04:14:06.186861Z","shell.execute_reply":"2023-07-24T04:17:59.176688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 検証用データで正解率を予測","metadata":{}},{"cell_type":"code","source":"# # 予測結果の正解率の計算\n# valid_pd = pd.DataFrame(valid_ds)\n\n# VALID = valid_pd.drop(['label'], axis=1, inplace=True)\n# VALID_LABEL = valid_pd['label'] # 予測する特徴量\n# Predictions = tf.argmax(VALID, axis=1)\n# Predictions\n# valid_accuracy = tf.reduce_mean(tf.cast(Predictions == VALID_LABEL, tf.float32))\n# print(\"Valid Accuracy:\", valid_accuracy.numpy())\n\nimport matplotlib.pyplot as plt\n\n# 学習曲線の描画\nplt.figure(figsize=(12, 4))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.legend()\nplt.grid()\nplt.title('Loss evolution')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['sparse_categorical_accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_sparse_categorical_accuracy'], label='Validation Accuracy')\nplt.legend()\nplt.grid()\nplt.title('Accuracy evolution')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:17:59.180055Z","iopub.execute_input":"2023-07-24T04:17:59.180417Z","iopub.status.idle":"2023-07-24T04:17:59.679851Z","shell.execute_reply.started":"2023-07-24T04:17:59.180372Z","shell.execute_reply":"2023-07-24T04:17:59.678949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Train Accuracy:\", history.history['sparse_categorical_accuracy'][-1])\nprint(\"Validation Accuracy:\", history.history['val_sparse_categorical_accuracy'][-1])\nprint(len(train_x),len(valid_x))","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:17:59.680834Z","iopub.execute_input":"2023-07-24T04:17:59.681192Z","iopub.status.idle":"2023-07-24T04:17:59.68834Z","shell.execute_reply.started":"2023-07-24T04:17:59.681151Z","shell.execute_reply":"2023-07-24T04:17:59.687405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# テストデータの準備","metadata":{}},{"cell_type":"code","source":"# -------------------------------------------------------------------\n# 定数の定義\n# -------------------------------------------------------------------\nTESTDIR = \"/kaggle/working/data/test\"\n# MODEL_DIR = \"/content/drive/MyDrive\"\nCATEGORIES = [\"cats\", \"dogs\"]\n\n# -------------------------------------------------------------------\n# メイン処理（画像を読込み、犬猫データセットを設定）\n# -------------------------------------------------------------------\n#犬猫データセットを定義\nfeature_test_data = []\nlabel_test_data = []\nfeature = []\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-24T04:17:59.690136Z","iopub.execute_input":"2023-07-24T04:17:59.690996Z","iopub.status.idle":"2023-07-24T04:18:30.094684Z","shell.execute_reply.started":"2023-07-24T04:17:59.690949Z","shell.execute_reply":"2023-07-24T04:18:30.093667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## モデルに入力出来るようにデータの形を変形（最終調整）","metadata":{}},{"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-24T04:18:30.096295Z","iopub.execute_input":"2023-07-24T04:18:30.096901Z","iopub.status.idle":"2023-07-24T04:19:13.571763Z","shell.execute_reply.started":"2023-07-24T04:18:30.096865Z","shell.execute_reply":"2023-07-24T04:19:13.570779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 確認用","metadata":{}},{"cell_type":"code","source":"test_ds","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:19:13.573311Z","iopub.execute_input":"2023-07-24T04:19:13.573642Z","iopub.status.idle":"2023-07-24T04:19:13.580272Z","shell.execute_reply.started":"2023-07-24T04:19:13.573609Z","shell.execute_reply":"2023-07-24T04:19:13.579355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<_PrefetchDataset element_spec=(TensorSpec(shape=<unknown>, dtype=tf.float32, name=None), TensorSpec(shape=<unknown>, dtype=tf.int32, name=None))>","metadata":{}},{"cell_type":"markdown","source":"# データを予測","metadata":{}},{"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-24T04:19:13.581633Z","iopub.execute_input":"2023-07-24T04:19:13.58222Z","iopub.status.idle":"2023-07-24T04:19:15.820971Z","shell.execute_reply.started":"2023-07-24T04:19:13.582187Z","shell.execute_reply":"2023-07-24T04:19:15.819935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(predictions)","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:19:15.822787Z","iopub.execute_input":"2023-07-24T04:19:15.823573Z","iopub.status.idle":"2023-07-24T04:19:15.829113Z","shell.execute_reply.started":"2023-07-24T04:19:15.823535Z","shell.execute_reply":"2023-07-24T04:19:15.828074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 内容確認","metadata":{}},{"cell_type":"code","source":"y_pred","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:19:15.830737Z","iopub.execute_input":"2023-07-24T04:19:15.831516Z","iopub.status.idle":"2023-07-24T04:19:15.841199Z","shell.execute_reply.started":"2023-07-24T04:19:15.831473Z","shell.execute_reply":"2023-07-24T04:19:15.840202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 結果を提出出来る形に修正","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\n","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:19:15.842895Z","iopub.execute_input":"2023-07-24T04:19:15.8437Z","iopub.status.idle":"2023-07-24T04:19:15.866913Z","shell.execute_reply.started":"2023-07-24T04:19:15.843662Z","shell.execute_reply":"2023-07-24T04:19:15.866041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"1000\n0010\n1011\n1111","metadata":{}},{"cell_type":"code","source":"pred_pd[:16]","metadata":{"execution":{"iopub.status.busy":"2023-07-24T04:19:15.868468Z","iopub.execute_input":"2023-07-24T04:19:15.869179Z","iopub.status.idle":"2023-07-24T04:19:15.88122Z","shell.execute_reply.started":"2023-07-24T04:19:15.869146Z","shell.execute_reply":"2023-07-24T04:19:15.879944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 結果を保存","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-24T04:19:15.882754Z","iopub.execute_input":"2023-07-24T04:19:15.883502Z","iopub.status.idle":"2023-07-24T04:19:15.943986Z","shell.execute_reply.started":"2023-07-24T04:19:15.883465Z","shell.execute_reply":"2023-07-24T04:19:15.942985Z"},"trusted":true},"execution_count":null,"outputs":[]}]}