{"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":"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":"2024-07-20T11:25:47.519590Z","iopub.execute_input":"2024-07-20T11:25:47.520261Z","iopub.status.idle":"2024-07-20T11:25:48.827663Z","shell.execute_reply.started":"2024-07-20T11:25:47.520234Z","shell.execute_reply":"2024-07-20T11:25:48.826724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-20T11:25:48.829462Z","iopub.execute_input":"2024-07-20T11:25:48.829949Z","iopub.status.idle":"2024-07-20T11:25:56.068060Z","shell.execute_reply.started":"2024-07-20T11:25:48.829916Z","shell.execute_reply":"2024-07-20T11:25:56.067048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"パラメータの設定","metadata":{}},{"cell_type":"code","source":"size = 224 #画像サイズ\nmean = (0.485, 0.456, 0.406) #ImageNetデータセットの平均値\nstd = (0.229, 0.224, 0.225)  #ImageNetデータセットの標準偏差\nbatch_size = 32 #バッチサイズ\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nnum_epoch = 10 #学習回数","metadata":{"execution":{"iopub.status.busy":"2024-07-20T11:25:56.069548Z","iopub.execute_input":"2024-07-20T11:25:56.070629Z","iopub.status.idle":"2024-07-20T11:25:56.128864Z","shell.execute_reply.started":"2024-07-20T11:25:56.070587Z","shell.execute_reply":"2024-07-20T11:25:56.127678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"データの初期化","metadata":{}},{"cell_type":"code","source":"# データを初期化\n!rm -rf ../data","metadata":{"execution":{"iopub.status.busy":"2024-07-20T11:25:56.131540Z","iopub.execute_input":"2024-07-20T11:25:56.132271Z","iopub.status.idle":"2024-07-20T11:25:57.150087Z","shell.execute_reply.started":"2024-07-20T11:25:56.132234Z","shell.execute_reply":"2024-07-20T11:25:57.148954Z"},"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# 学習データの解凍\nwith zipfile.ZipFile(os.path.join(base_dir, 'train.zip')) as train_zip:\n    train_zip.extractall('../data')\n    \n#推論データの解凍\nwith zipfile.ZipFile(os.path.join(base_dir, 'test.zip')) as test_zip:\n    test_zip.extractall('../data')\n\n\ntrain_list = glob.glob(os.path.join(train_dir, '*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\n\n# 学習データから検証データを分割(8:2)\ntrain_list, val_list = train_test_split(train_list, test_size=0.2)","metadata":{"execution":{"iopub.status.busy":"2024-07-20T11:25:57.151764Z","iopub.execute_input":"2024-07-20T11:25:57.152142Z","iopub.status.idle":"2024-07-20T11:26:14.301501Z","shell.execute_reply.started":"2024-07-20T11:25:57.152107Z","shell.execute_reply":"2024-07-20T11:26:14.300501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.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-20T11:26:14.302786Z","iopub.execute_input":"2024-07-20T11:26:14.303114Z","iopub.status.idle":"2024-07-20T11:26:14.310340Z","shell.execute_reply.started":"2024-07-20T11:26:14.303090Z","shell.execute_reply":"2024-07-20T11:26:14.309382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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': #ファイル名がdogであれば 1\n            label = 1\n        elif label == 'cat':#ファイル名がcatであれば 0\n            label = 0\n\n        return img_transformed, label","metadata":{"execution":{"iopub.status.busy":"2024-07-20T11:26:14.311570Z","iopub.execute_input":"2024-07-20T11:26:14.311893Z","iopub.status.idle":"2024-07-20T11:26:14.332165Z","shell.execute_reply.started":"2024-07-20T11:26:14.311863Z","shell.execute_reply":"2024-07-20T11:26:14.331276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-20T11:26:14.333197Z","iopub.execute_input":"2024-07-20T11:26:14.333462Z","iopub.status.idle":"2024-07-20T11:26:14.348516Z","shell.execute_reply.started":"2024-07-20T11:26:14.333434Z","shell.execute_reply":"2024-07-20T11:26:14.347764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"モデルの定義","metadata":{}},{"cell_type":"code","source":"use_pretrained = True\n# 事前学習済みのvgg16\nnet = models.vgg16(pretrained=use_pretrained)\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 #更新しない","metadata":{"execution":{"iopub.status.busy":"2024-07-20T11:26:14.349519Z","iopub.execute_input":"2024-07-20T11:26:14.350050Z","iopub.status.idle":"2024-07-20T11:26:19.387762Z","shell.execute_reply.started":"2024-07-20T11:26:14.350026Z","shell.execute_reply":"2024-07-20T11:26:19.386983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-20T11:26:19.390534Z","iopub.execute_input":"2024-07-20T11:26:19.390842Z","iopub.status.idle":"2024-07-20T11:26:19.406937Z","shell.execute_reply.started":"2024-07-20T11:26:19.390818Z","shell.execute_reply":"2024-07-20T11:26:19.406056Z"},"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-20T11:26:19.408355Z","iopub.execute_input":"2024-07-20T11:26:19.408783Z","iopub.status.idle":"2024-07-20T11:59:13.721949Z","shell.execute_reply.started":"2024-07-20T11:26:19.408721Z","shell.execute_reply":"2024-07-20T11:59:13.721010Z"},"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-20T11:59:13.723496Z","iopub.execute_input":"2024-07-20T11:59:13.723880Z","iopub.status.idle":"2024-07-20T11:59:14.257304Z","shell.execute_reply.started":"2024-07-20T11:59:13.723846Z","shell.execute_reply":"2024-07-20T11:59:14.256372Z"},"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) #データフレームの表示","metadata":{"execution":{"iopub.status.busy":"2024-07-20T11:59:14.258581Z","iopub.execute_input":"2024-07-20T11:59:14.258890Z","iopub.status.idle":"2024-07-20T12:01:43.965274Z","shell.execute_reply.started":"2024-07-20T11:59:14.258863Z","shell.execute_reply":"2024-07-20T12:01:43.964343Z"},"trusted":true},"execution_count":null,"outputs":[]}]}