{"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":"markdown","source":"<a id='start'></a>\n# 目次\n* [学習データとテストデータのダウンロード](#download)\n * [ダウンロードデータの確認](#show_img)\n\n * [データ拡張](#aug)\n* [分類学習](#train)\n * [モデル構築](#build)\n   * [事前学習済みモデル](#trained)\n   * [CNNモデル](#cnn)\n* [submit データの作成](#submit)","metadata":{"_uuid":"9dbdc935-9c65-47bb-b2d3-826e0ca1446d","_cell_guid":"97b55fb2-e235-4d74-ac1e-4fdd36c89ef0","trusted":true}},{"cell_type":"markdown","source":"<a id=\"download\"></a>\n# 学習データとテストデータのダウンロード\n「ogs-vs-cats-redux-kernels-edition」を Input に設置して，train.zip と test.zip を解凍．  \nOutput に解凍結果を train と test　のディレクトリに保存\n\n[戻る](#start)","metadata":{"_uuid":"13570322-6a2f-48ed-9dd9-8b70e56fa0b1","_cell_guid":"b46ce821-7d7e-4861-a74d-ec524d55ac87","trusted":true}},{"cell_type":"markdown","source":"Kaggleの環境で提供されたZIPファイルを展開し，学習データとテストデータのファイルパスを取得している．その後，これらのファイルパスを使用して画像データを読み込んだり，データの前処理やモデルの学習に使用することができる．","metadata":{"_uuid":"6bfb26dd-9412-42ff-af55-c4c0aca1773c","_cell_guid":"d02237f0-7c13-4b05-8a31-e74745d59419","trusted":true}},{"cell_type":"code","source":"import zipfile\nimport glob\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\n\ntrain_dir = 'train'\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip', 'r') as train_zip:\n    train_zip.extractall('')\n\ntrain_list = glob.glob(os.path.join(train_dir,'*.jpg'))\nprint(f\"Train Data: {len(train_list)}\")\n\nbase_dir = '/kaggle/working'\ntrain_dir = os.path.join(base_dir, 'train')\n\ntest_dir = 'test'\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip', 'r') as test_zip:\n    test_zip.extractall('')\n\ntest_list = glob.glob(os.path.join(test_dir,'*.jpg'))\nprint(f\"Test Data: {len(test_list)}\")\n\nbase_dir = '/kaggle/working'\ntest_dir = os.path.join(base_dir, 'test')","metadata":{"_uuid":"67d35125-60df-4897-9c4d-7392da7b4468","_cell_guid":"b417729d-580a-44e2-a42b-653510c299e0","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:25:13.409693Z","iopub.execute_input":"2023-07-21T07:25:13.410083Z","iopub.status.idle":"2023-07-21T07:25:29.216195Z","shell.execute_reply.started":"2023-07-21T07:25:13.410052Z","shell.execute_reply":"2023-07-21T07:25:29.215193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"25000個の学習データ，12500個のテストデータを用意しています．","metadata":{"_uuid":"53ef35b4-2328-4139-8c9d-b108ab388533","_cell_guid":"7ac9d664-8d17-45ad-a6a0-d33d3a59daa9","trusted":true}},{"cell_type":"markdown","source":"<a id='show_img'></a>\n## ダウンロードデータの確認\n学習データとテストデータの数と最初のデータ1つを確認","metadata":{"_uuid":"dddb6c7a-3e89-41b8-a546-c6515f83581a","_cell_guid":"c26912c8-2386-4d9c-831f-9059f15acd0c","trusted":true}},{"cell_type":"code","source":"print(f'学習データ数：{len(train_list)}', f'先頭のデータ：{train_list[0]}')\nprint(f'テストデータ数：{len(test_list)}', f'先頭のデータ：{test_list[0]}')","metadata":{"_uuid":"67277250-7108-4bb6-b747-960c973bfd42","_cell_guid":"5e366e2a-8086-4115-89e1-6833cbdfa258","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:25:29.219580Z","iopub.execute_input":"2023-07-21T07:25:29.219893Z","iopub.status.idle":"2023-07-21T07:25:29.229109Z","shell.execute_reply.started":"2023-07-21T07:25:29.219857Z","shell.execute_reply":"2023-07-21T07:25:29.228178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id='aug'></a>\n## データ拡張","metadata":{"_uuid":"246bfbfb-dd36-4d0d-b143-7b61cc29bbde","_cell_guid":"cca99bda-74ac-4a08-959c-6891ed94ff22","trusted":true}},{"cell_type":"markdown","source":"学習データとテストデータの画像を適切なサイズにリサイズし，データとラベルのペアを作成する．これらのデータは，後続の処理で機械学習モデルの学習や予測に使用することができる．","metadata":{"_uuid":"6db93f66-f17c-413a-ae65-a071f4dcd3fe","_cell_guid":"ba9b4356-7504-4e76-ad39-aa8b87ad0b41","trusted":true}},{"cell_type":"code","source":"!pip install 'numpy<1.23.0'\n\nfrom PIL import Image\nimport os, glob\n#　osモジュールはファイルおよびディレクトリの操作に使用され，globモジュールはファイルパスのパターンマッチングに使用される．\nimport numpy as np\nfrom PIL import ImageFile\nfrom sklearn.model_selection import train_test_split\n\nclasses = {'dog':0, 'cat':1}\nimage_size = 64\n#image_size = 64 # CNN\n\nX_train = []\ny_train = []\nX_val = []\ny_val = []\n\ntrain_labels = [path.split('/')[-1].split('.')[0] for path in train_list]\n\n#'''\nfor shuffle in [train_list, train_labels] :\n    np.random.seed(1)\n    np.random.shuffle(shuffle)\n#'''\n\nfor i, img in enumerate(train_list) :\n    if (i+1) / (len(train_list)+1) < 0.7 :\n        image = Image.open(img)\n        image = image.convert(\"RGB\")\n        image = image.resize((image_size, image_size))\n        data = np.asarray(image)\n        X_train.append(data)\n        y_train.append(classes[train_labels[i]])\n\n        # FLIP_LEFT_RIGHT　は 左右反転の画像も学習データに追加\n        img_trains = image.transpose(Image.FLIP_LEFT_RIGHT)\n        data = np.asarray(img_trains)\n        X_train.append(data)\n        y_train.append(classes[train_labels[i]])\n\n        for angle in [90, 180] :\n            img_r = image.rotate(angle)\n            data = np.asarray(img_r)\n            X_train.append(data)\n            y_train.append(classes[train_labels[i]])\n        \n    else :\n        image = Image.open(img)\n        image = image.convert(\"RGB\")\n        image = image.resize((image_size, image_size))\n        data = np.asarray(image)\n        X_val.append(data)\n        y_val.append(classes[train_labels[i]])\n#　70%の確率で訓練データに追加し，30%の確率でバリデーションデータに追加する．画像はリサイズされ，numpy配列に変換された後，対応するリストに追加される．\n\nX_train = np.array(X_train)\ny_train = np.array(y_train)\nX_val = np.array(X_val)\ny_val = np.array(y_val)\n\nX_test  = []\n\nfor i, img in enumerate(test_list) :\n    image = Image.open(img)\n    image = image.convert(\"RGB\")\n    image = image.resize((image_size, image_size))\n    data = np.asarray(image)\n    X_test.append(data)\n    \nX_test  = np.array(X_test)","metadata":{"_uuid":"badee436-61f0-4533-953c-d2732a1c51e2","_cell_guid":"55d7358e-336d-478f-a9e1-d57de364978a","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:25:29.231590Z","iopub.execute_input":"2023-07-21T07:25:29.232299Z","iopub.status.idle":"2023-07-21T07:27:33.908836Z","shell.execute_reply.started":"2023-07-21T07:25:29.232263Z","shell.execute_reply":"2023-07-21T07:27:33.907633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#'''\nprint('学習・検証・テストデータ')\nprint(f'学習データ数：{len(X_train)} 検証データ数:{len(X_val)} テストデータ数：{len(X_test)}')\nprint(f'学習ラベル数：{len(y_train)} 検証ラベル数:{len(y_val)}')\nprint('1つのデータ')\nprint(f'学習の次元数：{X_train[0].shape} 検証の次元数：{X_val[0].shape} テストの次元数：{X_test[0].shape}')\nprint(f'学習ラベル：{y_train[0]} 検証ラベル：{y_val[0]}')\n#'''","metadata":{"_uuid":"c2cdef67-fc05-44dd-a596-511a0ecc4a65","_cell_guid":"8b611d3f-9a47-4150-bc69-2ccae08bf8e2","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:27:33.910529Z","iopub.execute_input":"2023-07-21T07:27:33.910888Z","iopub.status.idle":"2023-07-21T07:27:33.919997Z","shell.execute_reply.started":"2023-07-21T07:27:33.910850Z","shell.execute_reply":"2023-07-21T07:27:33.918981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id='train'></a>\n# 分類学習\n\n[戻る](#start)","metadata":{"_uuid":"44b0c7c7-73ab-4d7f-be8e-533e9484428a","_cell_guid":"38133acb-f17b-4dfc-ba78-eff1516b0509","trusted":true}},{"cell_type":"markdown","source":"CNNモデルを構築するために必要なモジュールとクラスをインポートする．","metadata":{"_uuid":"a1b5bfec-a49d-4e38-9f2e-deb4b43b1c69","_cell_guid":"c7c718f7-ecc2-4578-a573-7cee1cbb25db","trusted":true}},{"cell_type":"code","source":"from keras.models import Sequential ,Model\nfrom keras.layers import Conv2D, MaxPooling2D\n#　畳み込み層、プーリング層\nfrom keras.layers import Input, Activation, Dropout, Flatten, Dense\n#　入力層、活性化関数、ドロップアウト層、平坦化層、全結合層\nfrom keras.optimizers import RMSprop\n#　RMSprop：勾配の大きさに応じて学習率を調整するようにして，振動を抑制\nimport tensorflow as tf\n\nimport keras\nimport numpy as np","metadata":{"_uuid":"d6b2df66-f05c-4cbb-91c5-76536ec4f0af","_cell_guid":"1dee3957-8469-43a8-8c6a-8849d14d6002","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:27:33.923698Z","iopub.execute_input":"2023-07-21T07:27:33.924777Z","iopub.status.idle":"2023-07-21T07:27:42.398786Z","shell.execute_reply.started":"2023-07-21T07:27:33.924744Z","shell.execute_reply":"2023-07-21T07:27:42.397665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id='cnn'></a>\n#### CNN で構築\nスコア0.60ぐらい","metadata":{"_uuid":"bb058f91-f8af-4fa0-a7d4-898b337fe7ab","_cell_guid":"a3601c13-90a9-4b3c-aaf6-e961fd219817","trusted":true}},{"cell_type":"markdown","source":"画像分類のためのニューラルネットワークモデルを定義している．","metadata":{"_uuid":"f0a9d673-7eb9-4020-b908-f5c45155b76c","_cell_guid":"768a3e7d-6ae4-49e8-a414-e72705099377","jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T06:59:31.884951Z","iopub.execute_input":"2023-07-21T06:59:31.886455Z","iopub.status.idle":"2023-07-21T06:59:31.894155Z","shell.execute_reply.started":"2023-07-21T06:59:31.886416Z","shell.execute_reply":"2023-07-21T06:59:31.891753Z"}}},{"cell_type":"code","source":"#'''\ndef model_classify(X) :\n    model = Sequential() # モデルを生成するためのモジュール\n\n    # Xは(1200, 64, 64, 3)\n    # X.shape[1:]とすることで、(64, 64, 3)となり、入力にすることが可能です。\n    model.add(Conv2D(32,(3,3), padding='same',input_shape=X.shape[1:])) # 2次元畳み込み層のモジュール\n    model.add(Activation('relu')) # 活性化関数モジュール\n    model.add(Conv2D(32,(3,3))) # 2次元畳み込み層のモジュール\n    model.add(Activation('relu')) # 活性化関数モジュール\n    model.add(MaxPooling2D(pool_size=(2,2))) # 2次元最大プーリング層のモジュール\n    model.add(Dropout(0.1)) # ドロップアウトモジュール\n\n    model.add(Conv2D(64,(3,3), padding='same')) # 2次元畳み込み層のモジュール\n    model.add(Activation('relu')) # 活性化関数モジュール\n    model.add(Conv2D(64,(3,3))) # 2次元畳み込み層のモジュール\n    model.add(Activation('relu')) # 活性化関数モジュール\n    model.add(MaxPooling2D(pool_size=(2,2))) # 2次元最大プーリング層のモジュール\n    model.add(Dropout(0.25)) # ドロップアウトモジュール\n\n    model.add(Flatten()) # 入力を平滑化するモジュール\n    model.add(Dense(512)) # 全結合層のレイヤモジュール\n    model.add(Activation('relu')) # 活性化関数モジュール\n    model.add(Dropout(0.45)) # ドロップアウトモジュール\n    model.add(Dense(2)) # # 全結合層のレイヤモジュール(犬と猫を識別するため、２クラス分類のため2を指定)\n    model.add(Activation('softmax')) # 活性化関数モジュール\n\n    # 最適化アルゴリズムにRMSpropを利用\n    model.compile(\n        optimizer = tf.keras.optimizers.Adam(learning_rate = 5e-5),\n        loss = \"sparse_categorical_crossentropy\",\n        metrics=['accuracy']\n    )\n    \n    return model\n#'''","metadata":{"_uuid":"8462fe3f-1d82-4aa6-baaf-995b7cd7b089","_cell_guid":"c2ae594f-e972-496c-87dc-85af10e596c7","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:27:42.400563Z","iopub.execute_input":"2023-07-21T07:27:42.401710Z","iopub.status.idle":"2023-07-21T07:27:42.412946Z","shell.execute_reply.started":"2023-07-21T07:27:42.401673Z","shell.execute_reply":"2023-07-21T07:27:42.412008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"モデルをトレーニングし、最良の重みを保存するためのコードスニペット","metadata":{"_uuid":"18202fbf-cf47-4f08-a2b0-08f48cdd0235","_cell_guid":"802963fa-0453-48b7-a713-b0fd5bcfa80e","trusted":true}},{"cell_type":"code","source":"#'''\nmodel = model_classify(X_train)\ncheckpoint = tf.keras.callbacks.ModelCheckpoint(\n    \"best_weight.h5\",     # ファイル名\n    #monitor = \"val_loss\", # 参照するloss\n    monitor = \"loss\", # 参照するloss\n    mode = \"min\",         # monitorが最小のときに保存\n    save_best_only = True,\n    save_weights_only = True\n)\nmodel.summary()\n#'''","metadata":{"_uuid":"3a95361c-0c45-41f6-8841-0d7b2ab0eaa7","_cell_guid":"3700a303-6d6f-43f3-be98-ebf215b1cce4","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:27:42.415999Z","iopub.execute_input":"2023-07-21T07:27:42.416269Z","iopub.status.idle":"2023-07-21T07:27:46.943177Z","shell.execute_reply.started":"2023-07-21T07:27:42.416246Z","shell.execute_reply":"2023-07-21T07:27:46.942348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"学習データセットとテストデータセットがバッチサイズで分割され、学習データセットがシャッフルされます。また、最初のバッチが取得され、その形状が表示されます。これにより、データセットの準備が整い、モデルの学習や評価に使用する準備が整います。","metadata":{"_uuid":"0bf841f8-e596-4df8-a2f7-c180339507fc","_cell_guid":"1498fb6a-4ac4-448e-90c1-c977df62407a","trusted":true}},{"cell_type":"code","source":"#'''\ntrain_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))\ntest_dataset = tf.data.Dataset.from_tensor_slices((X_val, y_val))\n#　X_trainとy_trainをペアとして学習データセットを作成し、X_valとy_valをペアとしてテストデータセットを作成します。\n\ntrain_dataset = train_dataset.batch(28)\ntest_dataset = test_dataset.batch(28)\n#　学習データセットとテストデータセットをバッチサイズ28に設定します。バッチサイズを指定することで、モデルの学習や評価を効率的に行うことができます。\ntrain_dataset = train_dataset.shuffle(1024 * 50)\n#　学習データセットをシャッフルします。シャッフルは訓練データの順序をランダムにすることで、モデルの学習の効果を向上させるための一般的な手法です。\n\nbatch = next(iter(train_dataset))\nprint(batch[0].shape)\nprint(batch[1].shape)\n#'''","metadata":{"_uuid":"9e490f8e-f7fd-4ec3-873f-cef7738e5675","_cell_guid":"6b32bc7f-449a-4765-8815-2333b4833069","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:27:46.944254Z","iopub.execute_input":"2023-07-21T07:27:46.944774Z","iopub.status.idle":"2023-07-21T07:27:50.187434Z","shell.execute_reply.started":"2023-07-21T07:27:46.944747Z","shell.execute_reply":"2023-07-21T07:27:50.186413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"28×2500個のデータ","metadata":{"_uuid":"eeead415-1bf7-4a68-ac16-c443941772f3","_cell_guid":"58e4f3be-4dcc-4558-8554-81bb8d15cd02","trusted":true}},{"cell_type":"markdown","source":"モデルを訓練するためのfitメソッドを使用しています。訓練データセットを使用してモデルを学習し、バリデーションデータセットを使用してモデルの性能を評価する．","metadata":{"_uuid":"c6e1e981-9ecd-4872-aab7-a0cdd1abeee4","_cell_guid":"6c44cdf0-9896-4656-b1a2-58d78d708864","trusted":true}},{"cell_type":"code","source":"history = model.fit(train_dataset, validation_data = test_dataset, epochs=5, callbacks = [checkpoint])\n#　model.fitメソッドを呼び出して、モデルの訓練を開始します。\n#　train_datasetを訓練データセットとして指定します。このデータセットを使用してモデルを学習します。\n#　validation_data=test_datasetを指定して、バリデーションデータセットを設定します。モデルの学習中にバリデーションデータセットを使用してモデルの性能を評価します。\n#　epochs=40を指定して、40エポックの訓練を行います。1つのエポックは訓練データセット全体の1回の学習を意味します。\n#　model.fitメソッドを実行することで、モデルが訓練データセットを使用して学習され、バリデーションデータセットを使用して性能が評価されます。","metadata":{"_uuid":"2aff55f7-14b9-4a38-9206-742a6123f2a5","_cell_guid":"6c3f57de-d627-4bfb-bb93-3a041db9432f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:27:50.190048Z","iopub.execute_input":"2023-07-21T07:27:50.190670Z","iopub.status.idle":"2023-07-21T07:30:56.820731Z","shell.execute_reply.started":"2023-07-21T07:27:50.190633Z","shell.execute_reply":"2023-07-21T07:30:56.819615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Epoch　繰り返す数（後のグラフに反映）　　　loss：損失関数　　accuracy：正解率","metadata":{"_uuid":"410c3464-2e2c-4748-991f-568220e3e6c3","_cell_guid":"1eb9a0da-65e1-453e-b288-b4a0b1ed987e","trusted":true}},{"cell_type":"markdown","source":"事前に保存された最良の重みをロードしてモデルの評価を行っている．","metadata":{"_uuid":"dffe01ff-5792-48ea-bd7f-8264490f4067","_cell_guid":"d1095c33-85f8-4703-b65d-5c0c81101fb1","trusted":true}},{"cell_type":"code","source":"model.load_weights(\"best_weight.h5\")\nscore = model.evaluate(X_val, y_val, batch_size=28)","metadata":{"_uuid":"f1eebbb6-9674-430d-a479-fec2551a3a73","_cell_guid":"0d421a47-ef92-4ba2-8422-260d9f31f0f9","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:30:56.822338Z","iopub.execute_input":"2023-07-21T07:30:56.822727Z","iopub.status.idle":"2023-07-21T07:30:58.415947Z","shell.execute_reply.started":"2023-07-21T07:30:56.822691Z","shell.execute_reply":"2023-07-21T07:30:58.415013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"モデルの形を保存　　モデルの精度を評価","metadata":{"_uuid":"737661c8-f067-482f-9f80-705db2dda344","_cell_guid":"5211a068-90ea-4861-be3a-34ff4111f236","trusted":true}},{"cell_type":"markdown","source":"訓練データとバリデーションデータの損失の推移が可視化されます。損失が減少していくことは望ましい結果であり、訓練データとバリデーションデータの損失の間に大きな差がないことも重要です。プロットを通じて、モデルの学習の進捗や過学習の傾向を把握することができます。","metadata":{"_uuid":"7cd5afc7-6929-4c7e-b04c-0417786355bc","_cell_guid":"fe0dda44-90f7-4f87-bdbb-f409c3a7804f","trusted":true}},{"cell_type":"code","source":"#'''\nplt.plot(history.history[\"loss\"], label = \"train\")\nplt.plot(history.history[\"val_loss\"], label = \"valid\")\nplt.legend()\nplt.show()\n#'''","metadata":{"_uuid":"a895717b-c387-4e26-9847-dbfd56adbff8","_cell_guid":"b0e1d3a0-57fd-4f8f-a1cb-6bc6cec80b9f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:30:58.419242Z","iopub.execute_input":"2023-07-21T07:30:58.419530Z","iopub.status.idle":"2023-07-21T07:30:58.757060Z","shell.execute_reply.started":"2023-07-21T07:30:58.419505Z","shell.execute_reply":"2023-07-21T07:30:58.756005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id='submit'></a>\n# submit データの作成\n\n[戻る](#start)","metadata":{"_uuid":"e4aa861f-ff18-4c7e-bd82-4642451c76b7","_cell_guid":"0d322576-4314-451c-8f7f-2a270e34a3a5","execution":{"iopub.status.busy":"2023-07-09T16:57:09.941619Z","iopub.execute_input":"2023-07-09T16:57:09.941946Z","iopub.status.idle":"2023-07-09T16:57:09.946959Z","shell.execute_reply.started":"2023-07-09T16:57:09.941919Z","shell.execute_reply":"2023-07-09T16:57:09.945485Z"},"trusted":true}},{"cell_type":"markdown","source":"CNN で作成","metadata":{"_uuid":"33ee51e8-756d-4199-857d-ae0d0556da96","_cell_guid":"ededb45e-03d3-4ff0-9c14-dbc29d01f7f1","trusted":true}},{"cell_type":"markdown","source":"テストデータの予測結果をDataFrameに変換し、CSVファイルとして保存している．","metadata":{"_uuid":"86cce5b6-f30e-4e28-8387-b79795445a26","_cell_guid":"97a8d9fa-a2a2-4dad-b152-2f515b1a411b","trusted":true}},{"cell_type":"code","source":"#'''\npred = model.predict(X_test)\n\nimport pandas as pd\n\ndf1 = pd.DataFrame(pred, columns=['dog', 'cat'])\n\nids = [path.split('/')[-1].split('.')[0] for path in test_list]\nsubmit = list(zip(ids, df1['dog'].to_list()))\ndf2 = pd.DataFrame(submit, columns=['id', 'label'])\nprint(df2.head())\ndf2.to_csv('submit_cnn.csv', index=False)\n#'''","metadata":{"_uuid":"f468c5c1-1a6d-43e6-bac4-ecc8a664c465","_cell_guid":"f16dde7f-43dc-455a-bc11-ca0987178d35","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:30:58.758400Z","iopub.execute_input":"2023-07-21T07:30:58.759282Z","iopub.status.idle":"2023-07-21T07:31:00.900118Z","shell.execute_reply.started":"2023-07-21T07:30:58.759231Z","shell.execute_reply":"2023-07-21T07:31:00.898982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"各画像が犬である確率（'dog'列）と猫である確率（'cat'列）","metadata":{"_uuid":"21fb161a-5ff0-4269-bec6-52e3c249ad1f","_cell_guid":"704f5128-cb09-4e1f-95a0-690ec7768229","trusted":true}},{"cell_type":"code","source":"df1","metadata":{"_uuid":"f1929d92-ea0a-4049-aaee-86a48ab31cdd","_cell_guid":"cbc4b679-27eb-4a6e-a959-6dae4174c61b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:31:00.901856Z","iopub.execute_input":"2023-07-21T07:31:00.902351Z","iopub.status.idle":"2023-07-21T07:31:00.919438Z","shell.execute_reply.started":"2023-07-21T07:31:00.902312Z","shell.execute_reply":"2023-07-21T07:31:00.918351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"モデルの予測確率","metadata":{"_uuid":"ed281b92-9b87-4186-afdd-0282655a3879","_cell_guid":"f34f1a0b-8edd-4460-a628-37877eb8a17d","trusted":true}},{"cell_type":"markdown","source":"犬である写真，モデルが犬と予測した確率（12500個）","metadata":{"_uuid":"06406340-66a2-401e-a604-5303f5d4ed6b","_cell_guid":"e06228cc-57ab-4a12-9615-476891b60b3c","trusted":true}},{"cell_type":"code","source":"submit","metadata":{"_uuid":"ff9eacfc-a5dd-4201-aeac-f69a7b37cd1b","_cell_guid":"d137f363-b803-473d-a78c-d56357fb3ded","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:31:00.924312Z","iopub.execute_input":"2023-07-21T07:31:00.925122Z","iopub.status.idle":"2023-07-21T07:31:00.982319Z","shell.execute_reply.started":"2023-07-21T07:31:00.925075Z","shell.execute_reply":"2023-07-21T07:31:00.981295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#'''\ndf = pd.read_csv('submit_cnn.csv')\ndf.head()\n#'''","metadata":{"_uuid":"6a46274c-dd83-4236-9fb6-6539de908cdc","_cell_guid":"bcf6f810-4ae3-40eb-b96c-ee4e199e9589","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-07-21T07:31:00.983867Z","iopub.execute_input":"2023-07-21T07:31:00.984526Z","iopub.status.idle":"2023-07-21T07:31:01.005510Z","shell.execute_reply.started":"2023-07-21T07:31:00.984486Z","shell.execute_reply":"2023-07-21T07:31:01.003918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"事前学習済みモデルで作成","metadata":{"_uuid":"164c61f5-5d6f-4a02-a328-183ad92ae009","_cell_guid":"2100b122-b441-4646-86d5-93a63c7a887e","trusted":true}}]}