{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## ライブラリのインポート","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport os, glob, time, copy, zipfile\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\nimport torch.nn.functional as F\nfrom torchvision import models, transforms","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:24.455635Z","iopub.execute_input":"2024-07-22T07:06:24.456100Z","iopub.status.idle":"2024-07-22T07:06:31.786082Z","shell.execute_reply.started":"2024-07-22T07:06:24.456075Z","shell.execute_reply":"2024-07-22T07:06:31.785311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## パラメータの設定","metadata":{}},{"cell_type":"code","source":"size = 224\nmean = (0.485, 0.456, 0.406)\nstd = (0.229, 0.224, 0.225)\nbatch_size = 64 \ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")  #gpuの使用を優先\nnum_epoch = 5","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:31.787709Z","iopub.execute_input":"2024-07-22T07:06:31.788094Z","iopub.status.idle":"2024-07-22T07:06:31.841994Z","shell.execute_reply.started":"2024-07-22T07:06:31.788069Z","shell.execute_reply":"2024-07-22T07:06:31.841159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"size...VGG16(学習済みモデル)は224×224の画像サイズを前提としている.   \nmean,std...画像のRGBの平均と標準偏差．　正規化の際に使用.  \nbatch...一度に処理するサンプルの数.(大きいほど早いがメモリの使用量も増)  \ndevice...GPUの利用を優先しなければCPU.  \nepoch...データセット全体をVGG16に適用する回数.(多いと過学習のリスク増)  ","metadata":{}},{"cell_type":"markdown","source":"## 初期化","metadata":{}},{"cell_type":"code","source":"!rm -rf ../data","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:31.842970Z","iopub.execute_input":"2024-07-22T07:06:31.843233Z","iopub.status.idle":"2024-07-22T07:06:32.864649Z","shell.execute_reply.started":"2024-07-22T07:06:31.843209Z","shell.execute_reply":"2024-07-22T07:06:32.863472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## データの解凍","metadata":{}},{"cell_type":"code","source":"# ディレクトリを設定\nbase_dir = '../input/dogs-vs-cats-redux-kernels-edition'\ntrain_dir = '../data/train'\ntest_dir = '../data/test'\n\nos.makedirs('../data', exist_ok=True)\n\n# train dataの解凍\nwith zipfile.ZipFile(os.path.join(base_dir, 'train.zip')) as train_zip:\n    train_zip.extractall('../data')\n    \n# test dataの解凍\nwith zipfile.ZipFile(os.path.join(base_dir, 'test.zip')) as test_zip:\n    test_zip.extractall('../data')\n\ntrain_list = glob.glob(os.path.join(train_dir, '*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\n\n# train dataとvalidation dataを8:2に分割\ntrain_list, val_list = train_test_split(train_list, test_size=0.2)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:32.867275Z","iopub.execute_input":"2024-07-22T07:06:32.867646Z","iopub.status.idle":"2024-07-22T07:06:54.344397Z","shell.execute_reply.started":"2024-07-22T07:06:32.867618Z","shell.execute_reply":"2024-07-22T07:06:54.343628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"train...訓練用でデータ.  \nval...検証用データ.  \nこれにより過学習を防ぐ.","metadata":{}},{"cell_type":"markdown","source":"# 画像変換のクラスの定義","metadata":{}},{"cell_type":"code","source":"class ImageTransform():\n    \n    def __init__(self, resize, mean, std):\n        self.data_transform = {\n            'train': transforms.Compose([\n                transforms.Resize((resize, resize)),  # 画像サイズを224にリサイズ\n                transforms.RandomAffine(degrees=0, shear=0.2), # Affine変換\n                transforms.RandomHorizontalFlip(),    # ランダム水平反転\n                transforms.RandomVerticalFlip(),      # ランダム垂直反転\n                transforms.ToTensor(),                # テンソルに変換\n                transforms.Normalize(mean, std)       # 正規化\n            ]),\n            'val': transforms.Compose([\n                transforms.Resize((resize, resize)),  # 画像サイズを224にリサイズ\n                transforms.ToTensor(),                # テンソルに変換\n                transforms.Normalize(mean, std)       # 正規化\n            ])\n        }\n        \n    def __call__(self, img, phase):\n        return self.data_transform[phase](img)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:54.345373Z","iopub.execute_input":"2024-07-22T07:06:54.345666Z","iopub.status.idle":"2024-07-22T07:06:54.355186Z","shell.execute_reply.started":"2024-07-22T07:06:54.345640Z","shell.execute_reply":"2024-07-22T07:06:54.353695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"VGG16に適用するための画像の前処理.  \n特に訓練用データに対してはアフィン変換(回転,拡大縮小,平行移動)や反転でデータ拡張.  \nこれにより多くのバリエーションのデータで訓練でき過学習を防ぐ.","metadata":{}},{"cell_type":"markdown","source":"# データセットのクラスの定義","metadata":{}},{"cell_type":"code","source":"class ImageDataset(data.Dataset):\n    \n    def __init__(self, file_list, transform=None, phase='train'):    \n        self.file_list = file_list\n        self.transform = transform\n        self.phase = phase\n        \n    def __len__(self):\n        return len(self.file_list)\n    \n    def __getitem__(self, idx):\n        \n        img_path = self.file_list[idx]\n        img = Image.open(img_path)\n        \n        img_transformed = self.transform(img, self.phase)\n        \n        # ファイル名からラベルを取得\n        label = img_path.split('/')[-1].split('.')[0]\n        if label == 'dog':\n            label = 1\n        elif label == 'cat':\n            label = 0\n\n        return img_transformed, label","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:54.356745Z","iopub.execute_input":"2024-07-22T07:06:54.357126Z","iopub.status.idle":"2024-07-22T07:06:54.377221Z","shell.execute_reply.started":"2024-07-22T07:06:54.357075Z","shell.execute_reply":"2024-07-22T07:06:54.376180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"画像の読み込みや前処理を実施.  \nファイル名からラベル(dog，cat)を取得し，数値(1,0)に変換.  \nおおまかにいうとデータを扱いやすい形に整え，モデルのトレーニングや評価に使えるようにするクラス.  ","metadata":{}},{"cell_type":"markdown","source":"# データローダーの作成","metadata":{}},{"cell_type":"code","source":"# 前処理\ntrain_dataset = ImageDataset(train_list, transform=ImageTransform(size, mean, std), phase='train')\nval_dataset = ImageDataset(val_list, transform=ImageTransform(size, mean, std), phase='val')\n\n# データの読み込み\ntrain_dataloader = data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\nval_dataloader = data.DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\n\ndataloader_dict = {'train': train_dataloader, 'val': val_dataloader}","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:54.378254Z","iopub.execute_input":"2024-07-22T07:06:54.378548Z","iopub.status.idle":"2024-07-22T07:06:54.389418Z","shell.execute_reply.started":"2024-07-22T07:06:54.378520Z","shell.execute_reply":"2024-07-22T07:06:54.388410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"訓練用データはシャッフルし，検証用データは順序を保持.","metadata":{}},{"cell_type":"markdown","source":"## モデルの定義","metadata":{}},{"cell_type":"code","source":"use_pretrained = True\n# 事前学習済みのvgg16\nnet = models.vgg16(weights=models.VGG16_Weights.DEFAULT if use_pretrained else None)\n# 線形層の置き換え\nnet.classifier[6] = nn.Linear(in_features=4096, out_features=2)\n\nparams_to_update = [] # 学習パラメータの初期化\n\nupdate_params_name = ['classifier.6.weight', 'classifier.6.bias'] # 更新するパラメータの指定\n\nfor name, param in net.named_parameters():\n    if name in update_params_name: # 更新するパラメータ\n        param.requires_grad = True\n        params_to_update.append(param) # 更新するパラメータの追加\n    else: # 更新しないパラメータ\n        param.requires_grad = False\n","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:54.390548Z","iopub.execute_input":"2024-07-22T07:06:54.390843Z","iopub.status.idle":"2024-07-22T07:06:59.530041Z","shell.execute_reply.started":"2024-07-22T07:06:54.390820Z","shell.execute_reply":"2024-07-22T07:06:59.529054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"VGG16の出力層は1000クラスの出力があるが2値(dog,cat)に変更.  ","metadata":{}},{"cell_type":"markdown","source":"## モデルの学習の定義","metadata":{}},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss() #損失関数\noptimizer = optim.Adam(params=params_to_update, lr=0.0001)\n\ndef train_model(net, dataloader_dict, criterion, optimizer, num_epoch):\n    \n    since = time.time() #学習開始時刻を記録\n    best_model_wts = copy.deepcopy(net.state_dict()) #最良モデルの初期化\n    best_acc = 0.0 #最良精度の初期化\n    \n     # 損失と精度の履歴\n    history = {'train_loss': [], 'val_loss': [], 'train_acc': [], 'val_acc': []}\n    \n    net = net.to(device) #モデルをGPUに転送\n    print('training started')\n    for epoch in range(num_epoch): #各エポックの進捗\n        print('Epoch {}/{}'.format(epoch + 1, num_epoch))\n        print('-'*20)\n        \n        for phase in ['train', 'val']:\n            #学習と検証を交互に行う\n            if phase == 'train':\n                net.train() #学習フェーズ\n            else:\n                net.eval() #検証フェーズ\n                \n            epoch_loss = 0.0\n            epoch_corrects = 0\n            \n            for inputs, labels in tqdm(dataloader_dict[phase]):\n                inputs = inputs.to(device)\n                labels = labels.to(device)\n                optimizer.zero_grad()\n                \n                with torch.set_grad_enabled(phase == 'train'):\n                    outputs = net(inputs) #出力を算出\n                    _, preds = torch.max(outputs, 1) #予測値の取得\n                    loss = criterion(outputs, labels) #損失の計算\n                    \n                    if phase == 'train':\n                        loss.backward() #逆伝播で学習\n                        optimizer.step()\n                        \n                    #バッチごとの損失と精度を累積    \n                    epoch_loss += loss.item() * inputs.size(0) \n                    epoch_corrects += torch.sum(preds == labels.data)\n            \n            #エポックごとの損失と精度の計算\n            epoch_loss = epoch_loss / len(dataloader_dict[phase].dataset)\n            epoch_acc = epoch_corrects.double() / len(dataloader_dict[phase].dataset)\n            \n            print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n            \n            # 履歴に保存\n            history[f'{phase}_loss'].append(epoch_loss)\n            history[f'{phase}_acc'].append(epoch_acc.cpu().numpy())\n            \n            # 最良モデルの保存\n            if phase == 'val' and epoch_acc > best_acc:\n                best_acc = epoch_acc\n                best_model_wts = copy.deepcopy(net.state_dict())\n                \n    time_elapsed = time.time() - since #学習の総時間を計算\n    print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n    print('Best val Acc: {:4f}'.format(best_acc))\n\n    # 最良の重みを読み込む\n    net.load_state_dict(best_model_wts)\n    return net, history","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:59.531723Z","iopub.execute_input":"2024-07-22T07:06:59.532179Z","iopub.status.idle":"2024-07-22T07:06:59.549719Z","shell.execute_reply.started":"2024-07-22T07:06:59.532143Z","shell.execute_reply":"2024-07-22T07:06:59.548715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## モデルの学習","metadata":{}},{"cell_type":"code","source":"net, history = train_model(net, dataloader_dict, criterion, optimizer, num_epoch)","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:06:59.553094Z","iopub.execute_input":"2024-07-22T07:06:59.553383Z","iopub.status.idle":"2024-07-22T07:24:17.393217Z","shell.execute_reply.started":"2024-07-22T07:06:59.553360Z","shell.execute_reply":"2024-07-22T07:24:17.391899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 損失の可視化","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n# 損失のプロット\nplt.figure(figsize=(12, 5))\nplt.subplot(1, 2, 1)\nplt.plot(history['train_loss'], label='Train Loss')\nplt.plot(history['val_loss'], label='Val Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.title('Loss over epochs')\nplt.legend()\n\n# 精度のプロット\nplt.subplot(1, 2, 2)\nplt.plot(history['train_acc'], label='Train Accuracy')\nplt.plot(history['val_acc'], label='Val Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.title('Accuracy over epochs')\nplt.legend()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:24:17.394452Z","iopub.execute_input":"2024-07-22T07:24:17.394825Z","iopub.status.idle":"2024-07-22T07:24:17.910242Z","shell.execute_reply.started":"2024-07-22T07:24:17.394790Z","shell.execute_reply":"2024-07-22T07:24:17.909340Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 推論","metadata":{}},{"cell_type":"code","source":"# 変数の初期化\nid_list = []\npred_list = []\n\nwith torch.no_grad():\n    for test_path in tqdm(test_list):\n        img = Image.open(test_path) #画像読み込み\n        _id = int(test_path.split('/')[-1].split('.')[0]) #ID抽出\n\n        transform = ImageTransform(size, mean, std)\n        img = transform(img, phase='val') #画像変換\n        img = img.unsqueeze(0) #バッチ次元の追加\n        img = img.to(device) #画像をGPUに転送\n\n        net.eval() #モデルを評価モードに設定\n\n        outputs = net(img) #モデルによる推論\n        preds = F.softmax(outputs, dim=1)[:, 1].tolist() #クラス1(dog)の確率を算出\n        \n        id_list.append(_id) #IDをリストに追加\n        pred_list.append(preds[0]) #予測値をリストに追加\n    \n    \nres = pd.DataFrame({'id': id_list, 'label': pred_list}) #IDと予測値からデータフレームを作成\n\n\nres.sort_values(by='id', inplace=True) #ID順に並び替え\nres.reset_index(drop=True, inplace=True)\n\nres.to_csv('/kaggle/working/submission.csv', index=False) #データフレームをCSVファイルに保存\n\n# print(res) #データフレームの表示\n","metadata":{"execution":{"iopub.status.busy":"2024-07-22T07:24:17.911344Z","iopub.execute_input":"2024-07-22T07:24:17.911651Z","iopub.status.idle":"2024-07-22T07:26:48.958188Z","shell.execute_reply.started":"2024-07-22T07:24:17.911618Z","shell.execute_reply":"2024-07-22T07:26:48.957280Z"},"trusted":true},"execution_count":null,"outputs":[]}]}