{"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-30T03:29:25.725069Z","iopub.execute_input":"2023-07-30T03:29:25.725868Z","iopub.status.idle":"2023-07-30T03:29:25.746069Z","shell.execute_reply.started":"2023-07-30T03:29:25.725832Z","shell.execute_reply":"2023-07-30T03:29:25.745042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 01 下準備\n\n機械学習やディープラーニングのオープンソースライブラリであるtensorflowを取り入れ、過学習を避けるため、機械学習モデルの訓練と検証のためにデータを分割する、画像ファイルを読み込む作業を行う","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom PIL import Image\nimport glob\nimport matplotlib.pyplot as plt\nimport random\nimport matplotlib.image as mpimg\nimport shutil\n","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:25.748812Z","iopub.execute_input":"2023-07-30T03:29:25.749594Z","iopub.status.idle":"2023-07-30T03:29:25.755717Z","shell.execute_reply.started":"2023-07-30T03:29:25.749560Z","shell.execute_reply":"2023-07-30T03:29:25.754800Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 02 Zip ファイルの展開\nZipファイルを解凍して、中のデータを取り出す処理を行う。","metadata":{}},{"cell_type":"code","source":"base_dir = \"../input/dogs-vs-cats\"\ntrain_dir = os.path.join(base_dir, \"train.zip\")\ntest_dir = os.path.join(base_dir, \"test1.zip\")\n\nimport zipfile\nwith zipfile.ZipFile(train_dir,\"r\") as z:\n    z.extractall()\n\nwith zipfile.ZipFile(test_dir,\"r\") as z:\n    z.extractall()\n\nos.listdir(\"/kaggle/working/\") #dir確認\n\nos.getcwd()\n\ntrain_path = '/kaggle/working/train/' #trainデータ\ntest1_path = '/kaggle/working/test1/' #testデータ\n","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:25.757531Z","iopub.execute_input":"2023-07-30T03:29:25.758336Z","iopub.status.idle":"2023-07-30T03:29:39.016071Z","shell.execute_reply.started":"2023-07-30T03:29:25.758303Z","shell.execute_reply":"2023-07-30T03:29:39.014985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 03 猫と犬のディレクトリに分ける\nここでは、与えられたディレクトリの中の画像ファイルをcatsとdogsのそれぞれのディレクトリに分類する処理を行う。","metadata":{}},{"cell_type":"code","source":"\"\"\"\nos.mkdir(train_path + 'cats')\ncat_dir = ('/kaggle/working/train/cats/')\nos.mkdir(train_path + 'dogs')\ndog_dir = ('/kaggle/working/train/dogs/')\n\ndirs = [each for each in os.listdir(train_path)]\n\nfor file in dirs:\n    folder = file.split(\".\")[0]\n    if folder == 'cat':\n        shutil.move(train_path+file, cat_dir)\n    elif folder == 'dog':\n        shutil.move(train_path+file, dog_dir)\n\"\"\"\n","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.018504Z","iopub.execute_input":"2023-07-30T03:29:39.018855Z","iopub.status.idle":"2023-07-30T03:29:39.027991Z","shell.execute_reply.started":"2023-07-30T03:29:39.018824Z","shell.execute_reply":"2023-07-30T03:29:39.027100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 04 画像の前処理\ncatsとdogsという2つの群の画像ファイルを読み込んで、それらの画像データと対応するようにラベル配列XとYに格納する処理を行う。","metadata":{}},{"cell_type":"code","source":"\"\"\"\nfolder = ['cats','dogs']\nimage_size = 224 #インプット画像のサイズ\nX = []\nY = []\nfor index, name in enumerate(folder): #ディレクトリの種類、画像ファイル名を繰返し取得する\n    dir = train_path + name\n    files = glob.glob(dir + \"/*.jpg\") #ファイル名の取得\n    for i, file in enumerate(files): #各画像へ↓の処理を繰返し実施する\n        image = Image.open(file) #画像の読み込み\n        image = image.convert(\"RGB\") #RGBに変換\n        image = image.resize((image_size, image_size)) #サイズ変更\n        data = np.asarray(image) #画像データを配列へ変更\n        X.append(data) #画像データを繰返し追加\n        Y.append(index) #cat:0, dog:1の値を繰返し追加\nX = np.array(X)\nY = np.array(Y)\n\"\"\"\n","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.029738Z","iopub.execute_input":"2023-07-30T03:29:39.030633Z","iopub.status.idle":"2023-07-30T03:29:39.040734Z","shell.execute_reply.started":"2023-07-30T03:29:39.030599Z","shell.execute_reply":"2023-07-30T03:29:39.039779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 05 正解ラベルの形式を変換\n数値のラベルをOne-hotエンコーディングに変換","metadata":{}},{"cell_type":"code","source":"\"\"\"\n#正解ラベルの形式を変換\nY = to_categorical(Y, 2)\nprint(Y)\n\"\"\"\n","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.042301Z","iopub.execute_input":"2023-07-30T03:29:39.043038Z","iopub.status.idle":"2023-07-30T03:29:39.057743Z","shell.execute_reply.started":"2023-07-30T03:29:39.043007Z","shell.execute_reply":"2023-07-30T03:29:39.056773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 06 ファイルの判別\n画像ファイルのファイル名からdogまたはcatのどちらに属するか判別する。","metadata":{}},{"cell_type":"code","source":"filenames = os.listdir(train_path) #dog123~~~,cat1234~~など\ncategories = [] #リスト初期化\nfor filename in filenames: #filenames(dog123~~~,cat1234~~)を一つずつfilenameに入れてforループ\n    category = filename.split('.')[0]#filenameは(dog.4784.jpg)この形なのでsplitを用いることにより[dog,4784,jpg]に分けられるこれの[0]をとることで[dog,cat]を受け取れる\n    if category == 'dog':\n        categories.append(1)#dog = 1,cat = 0をcnnでの判定で用いる。\n    else:\n        categories.append(0)\ndata = pd.DataFrame({'filename' : filenames , 'category' : categories})#dataframe型でdataに代入する(filename = dog.4784.jpg,category = 1(dog))\ndata.head()\n","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.059268Z","iopub.execute_input":"2023-07-30T03:29:39.059866Z","iopub.status.idle":"2023-07-30T03:29:39.119632Z","shell.execute_reply.started":"2023-07-30T03:29:39.059833Z","shell.execute_reply":"2023-07-30T03:29:39.118527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 07 Category列のカウント\nDataFrameの中からcategory列を取り出し、犬と猫の各値の出現率をカウントする","metadata":{}},{"cell_type":"code","source":"data['category'].value_counts()#確認(dogとcatの数)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.123517Z","iopub.execute_input":"2023-07-30T03:29:39.123955Z","iopub.status.idle":"2023-07-30T03:29:39.134439Z","shell.execute_reply.started":"2023-07-30T03:29:39.123921Z","shell.execute_reply":"2023-07-30T03:29:39.133413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 08 category1列の追加\ncategory列のバイナリ変数を0のときは猫、1のときは犬に表示されるようにする","metadata":{}},{"cell_type":"code","source":"data['category1'] = data['category'].apply(lambda x: 'cat' if x== 0 else 'dog')#datafram型にcategory1(dog,cat)を追加する\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.135960Z","iopub.execute_input":"2023-07-30T03:29:39.136712Z","iopub.status.idle":"2023-07-30T03:29:39.161017Z","shell.execute_reply.started":"2023-07-30T03:29:39.136678Z","shell.execute_reply":"2023-07-30T03:29:39.160068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 09 category1の内容をcategoryに置き換える\ncategoryで犬か猫をバイナリ変数で表示していたが、表示を「犬」と「猫」に変換したため、列名をcategory1をcategoryに置き換える","metadata":{}},{"cell_type":"code","source":"data.drop(['category'] , inplace = True , axis = 1)#category(1,0)を削除する\ndata.rename(columns  = {'category1' : 'category'} , inplace =True)#category1(dog,cat)をcategoryに名前を変える\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.162321Z","iopub.execute_input":"2023-07-30T03:29:39.163230Z","iopub.status.idle":"2023-07-30T03:29:39.187996Z","shell.execute_reply.started":"2023-07-30T03:29:39.163197Z","shell.execute_reply":"2023-07-30T03:29:39.186859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 10 データの分割\nデータを訓練データと検証データに分割する処理を行う\n（訓練データを80%、検証データを20%を分割する）","metadata":{}},{"cell_type":"code","source":"train_df , val_df = train_test_split(data , test_size = 0.2 , random_state = 42)#traindataをtrainとval(確認用)に分けるsizeはtrainが80%valが20%,seed値(random_state)を設定することで毎回同じデータに分けることが可能\ntrain_df = train_df.reset_index(drop = True)#splitをすることでindexがランダムになるので初期化する\nval_df = val_df.reset_index(drop = True)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.190206Z","iopub.execute_input":"2023-07-30T03:29:39.191427Z","iopub.status.idle":"2023-07-30T03:29:39.207708Z","shell.execute_reply.started":"2023-07-30T03:29:39.191337Z","shell.execute_reply":"2023-07-30T03:29:39.205779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 11 データをランダムにシャッフルして指定した割合で分割する","metadata":{}},{"cell_type":"code","source":"\"\"\"\n#学習用データとテストデータへ分割\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.20)\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.209378Z","iopub.execute_input":"2023-07-30T03:29:39.210298Z","iopub.status.idle":"2023-07-30T03:29:39.217151Z","shell.execute_reply.started":"2023-07-30T03:29:39.210261Z","shell.execute_reply":"2023-07-30T03:29:39.216019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 12 変数ｘを削除しえメモリを解放する","metadata":{}},{"cell_type":"code","source":"\"\"\"\ndel X #メモリ削減\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.218604Z","iopub.execute_input":"2023-07-30T03:29:39.219543Z","iopub.status.idle":"2023-07-30T03:29:39.229515Z","shell.execute_reply.started":"2023-07-30T03:29:39.219510Z","shell.execute_reply":"2023-07-30T03:29:39.228549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 13 画像の編集\n画像データの配列やサイズを変更する","metadata":{}},{"cell_type":"code","source":"image_size = 224#画像サイズ一辺\nImage_size = (image_size,image_size)#縦,横(224,224)\nbatch_size = 128#まとまり\nepochs = 10#iteration","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.230836Z","iopub.execute_input":"2023-07-30T03:29:39.231618Z","iopub.status.idle":"2023-07-30T03:29:39.239418Z","shell.execute_reply.started":"2023-07-30T03:29:39.231587Z","shell.execute_reply":"2023-07-30T03:29:39.238432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 14 画像データの拡張と前処理の設定\nより良いディープラーニングモデルの学習に重要な手続きとなる","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# 画像データの拡張と前処理の設定\ntrain_datagen = ImageDataGenerator(\n    rescale=1.0/255,#0~1に正規化\n    rotation_range=45,#回転,-45~45\n    shear_range = 0.1,#シアー強度\n    zoom_range = 0.2 , #ズーム\n    horizontal_flip = True , #左右反転\n    width_shift_range = 0.1 , #水平シフト\n    height_shift_range = 0.1 #垂直シフト\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.240717Z","iopub.execute_input":"2023-07-30T03:29:39.241419Z","iopub.status.idle":"2023-07-30T03:29:39.255442Z","shell.execute_reply.started":"2023-07-30T03:29:39.241265Z","shell.execute_reply":"2023-07-30T03:29:39.251344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 15 ジェネレータの作成\nデータをリアルタイムでバッチごとに提供することができ、便利なデータの流れを生成する","metadata":{}},{"cell_type":"code","source":"# ジェネレータの作成\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, #dataframe\n    train_path, #trainデータへのパス('/kaggle/working/train/')\n    x_col='filename',#特徴量\n    y_col='category',#category(0,1)\n    target_size=Image_size,#size\n    class_mode='categorical',#返すラベルの配列の形を決定する\n    batch_size=batch_size\n)  ","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.256870Z","iopub.execute_input":"2023-07-30T03:29:39.257841Z","iopub.status.idle":"2023-07-30T03:29:39.553923Z","shell.execute_reply.started":"2023-07-30T03:29:39.257810Z","shell.execute_reply":"2023-07-30T03:29:39.552938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 16 前過程を適用しながら、データをバッチごとに生成して学習に使用する","metadata":{}},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale = 1./255)\nval_generator = validation_datagen.flow_from_dataframe(\n    val_df, \n    train_path, \n    x_col='filename',\n    y_col='category',\n    target_size=Image_size,\n    class_mode='categorical',\n    batch_size=batch_size\n)  ","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.555340Z","iopub.execute_input":"2023-07-30T03:29:39.555788Z","iopub.status.idle":"2023-07-30T03:29:39.627633Z","shell.execute_reply.started":"2023-07-30T03:29:39.555753Z","shell.execute_reply":"2023-07-30T03:29:39.626584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 17 ResNet50をインポート","metadata":{}},{"cell_type":"code","source":"#CNNモデル（ResNet50）のライブラリをインポート\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Input, Flatten, Dense, Conv2D , MaxPooling2D , Dropout, Activation , BatchNormalization\n\n#input画像の定義\ninput_tensor = tf.keras.Input(shape=(image_size, image_size, 3))\n#ResNet50モデルの呼出し。ここでweights=\"imagenet\"とすることで学習済の重みを使うことができる\n#include_top=Falseとすることで出力層だけを今回の学習に合わせた形で書き換えます\nResNet50 = tf.keras.applications.ResNet50(include_top=False, weights=\"imagenet\", \n                                          input_tensor=input_tensor,classes=2,)\n#出力層の書換え。今回は2種類の画像分類のモデルを作成。\ntop_model = Sequential()\ntop_model.add(Flatten(input_shape = ResNet50.output_shape[1:]))\ntop_model.add(Dense(2, activation = 'sigmoid'))\nmodel = Model(inputs=ResNet50.inputs, outputs=top_model(ResNet50.outputs))","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:39.629415Z","iopub.execute_input":"2023-07-30T03:29:39.629766Z","iopub.status.idle":"2023-07-30T03:29:41.393521Z","shell.execute_reply.started":"2023-07-30T03:29:39.629734Z","shell.execute_reply":"2023-07-30T03:29:41.392524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 18 定義されたモデルに対して、最適化アルゴリズム、損失関数および評価メトリクスを設定","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.optimizers import Adam \nadam = Adam(learning_rate=0.0001)\nmodel.compile(optimizer= adam, loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:41.395103Z","iopub.execute_input":"2023-07-30T03:29:41.395486Z","iopub.status.idle":"2023-07-30T03:29:41.415352Z","shell.execute_reply.started":"2023-07-30T03:29:41.395451Z","shell.execute_reply":"2023-07-30T03:29:41.414390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 19 モデル概要","metadata":{}},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:41.421151Z","iopub.execute_input":"2023-07-30T03:29:41.422127Z","iopub.status.idle":"2023-07-30T03:29:41.821716Z","shell.execute_reply.started":"2023-07-30T03:29:41.422092Z","shell.execute_reply":"2023-07-30T03:29:41.820874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 20 学習の改善\n学習中にモデルの改善を監視し、学習率を適切に把握するよう設定する","metadata":{}},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau\nearlystop = EarlyStopping(patience = 10)\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\ncallbacks = [earlystop , learning_rate_reduction]","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:41.822927Z","iopub.execute_input":"2023-07-30T03:29:41.823582Z","iopub.status.idle":"2023-07-30T03:29:41.832420Z","shell.execute_reply.started":"2023-07-30T03:29:41.823546Z","shell.execute_reply":"2023-07-30T03:29:41.831590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 21　モデルの学習開始","metadata":{}},{"cell_type":"code","source":"# モデルの学習\nhistory = model.fit_generator(\n    train_generator , \n    epochs = epochs , \n    validation_data=val_generator,\n    validation_steps=val_df.shape[0]//batch_size,\n    steps_per_epoch=train_df.shape[0]//batch_size,\n    callbacks=callbacks\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T03:29:41.833476Z","iopub.execute_input":"2023-07-30T03:29:41.833837Z","iopub.status.idle":"2023-07-30T04:34:01.561111Z","shell.execute_reply.started":"2023-07-30T03:29:41.833803Z","shell.execute_reply":"2023-07-30T04:34:01.560030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 22 保存","metadata":{}},{"cell_type":"code","source":"model.save_weights('model.1')","metadata":{"execution":{"iopub.status.busy":"2023-07-30T04:34:01.563129Z","iopub.execute_input":"2023-07-30T04:34:01.563737Z","iopub.status.idle":"2023-07-30T04:34:03.212640Z","shell.execute_reply.started":"2023-07-30T04:34:01.563702Z","shell.execute_reply":"2023-07-30T04:34:03.211533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 23 モデルから予測を行う\nテストデータを読み込みテストデータの総サンプル数を計算","metadata":{}},{"cell_type":"code","source":"test_filenames = os.listdir(test1_path)\ntest = pd.DataFrame({'filename' : test_filenames})\nnb_samples = test.shape[0]","metadata":{"execution":{"iopub.status.busy":"2023-07-30T04:34:03.213905Z","iopub.execute_input":"2023-07-30T04:34:03.214310Z","iopub.status.idle":"2023-07-30T04:34:03.233612Z","shell.execute_reply.started":"2023-07-30T04:34:03.214271Z","shell.execute_reply":"2023-07-30T04:34:03.232502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 24 画像テストデータ読み込み\nテストデータ画像をバッチごとに読み込み、前処理の設定を行う","metadata":{}},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test , \n    test1_path ,\n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=(image_size,image_size),\n    batch_size=batch_size,\n    shuffle=False\n    )","metadata":{"execution":{"iopub.status.busy":"2023-07-30T04:34:03.234842Z","iopub.execute_input":"2023-07-30T04:34:03.235517Z","iopub.status.idle":"2023-07-30T04:34:03.373498Z","shell.execute_reply.started":"2023-07-30T04:34:03.235480Z","shell.execute_reply":"2023-07-30T04:34:03.372578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 25 予測開始\ntest_generatorを使用して、訓練されたモデルであるmodel1からテストデータの予測を行う","metadata":{}},{"cell_type":"code","source":"predict = model.predict_generator(test_generator , steps = np.ceil(nb_samples/batch_size))\ntest['category'] = np.argmax(predict  , axis= -1)\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T04:34:03.374982Z","iopub.execute_input":"2023-07-30T04:34:03.375548Z","iopub.status.idle":"2023-07-30T04:34:49.533052Z","shell.execute_reply.started":"2023-07-30T04:34:03.375513Z","shell.execute_reply":"2023-07-30T04:34:49.531628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 26 新しいデータフレームの作成","metadata":{}},{"cell_type":"code","source":"submission_df = test.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-07-30T04:34:49.538159Z","iopub.execute_input":"2023-07-30T04:34:49.543323Z","iopub.status.idle":"2023-07-30T04:34:49.585190Z","shell.execute_reply.started":"2023-07-30T04:34:49.543235Z","shell.execute_reply":"2023-07-30T04:34:49.584021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 27 保存\nテストデータの予測結果を提出用のCSVファイルとして保存する処理を行う。","metadata":{}},{"cell_type":"code","source":"submission_df.drop(['filename' , 'category'] , axis = 1 , inplace = True)\nsubmission_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-07-30T04:34:49.587061Z","iopub.execute_input":"2023-07-30T04:34:49.587497Z","iopub.status.idle":"2023-07-30T04:34:49.629174Z","shell.execute_reply.started":"2023-07-30T04:34:49.587459Z","shell.execute_reply":"2023-07-30T04:34:49.628138Z"},"trusted":true},"execution_count":null,"outputs":[]}]}