{"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-10T14:33:08.873829Z","iopub.execute_input":"2023-07-10T14:33:08.874234Z","iopub.status.idle":"2023-07-10T14:33:08.911958Z","shell.execute_reply.started":"2023-07-10T14:33:08.874200Z","shell.execute_reply":"2023-07-10T14:33:08.910673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# zipファイル解凍","metadata":{}},{"cell_type":"code","source":"!rm -r /kaggle/working/train\n!rm -r /kaggle/working/test\n!unzip /kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\n!unzip /kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import scipy.io\nfrom PIL import Image\nimport numpy as np\nfrom torchvision import transforms\nimport torch\nimport torch.utils.data as data\nimport os\nimport sys\nimport torch.optim as optim\nfrom tqdm import tqdm\nimport torch.nn as nn\nfrom glob import glob\nimport re\nimport csv\nfrom torch.nn import functional as F\nimport pandas as pd","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"class ImageTransform:\n    '''\n    画像の前処理を行う\n    画像のリサイズ，色の標準化\n    '''\n\n    def __init__(self, resize, mean, std):\n        self.data_transform = transforms.Compose(\n            [\n                transforms.Resize(resize),  # 短辺をの長さをresizeに\n                transforms.CenterCrop(resize),  # 画面中央を大きさresizeに切り取り\n                transforms.ToTensor(),  # テンソルに変換\n                transforms.Normalize(mean, std),  # 色情報の標準化\n            ]\n        )\n\n    def __call__(self, img):\n        return self.data_transform(img)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class AnimalList:\n    '''\n    画像とラベルからリストを作成\n    \"train\"指定 : 前半７割のデータ\n    \"val指定 : 後半３割のデータ\n    '''\n\n    def __init__(self):\n        self.m_path = []  # 画像パス\n        self.m_label = []  # ラベル\n        \n        folder_path = \"/kaggle/working/train/\"\n        \n        files = glob(folder_path + \"*.jpg\")\n\n        for file_name in files:\n            # 画像パス と ラベル\n            self.m_path.append(file_name)\n            if file_name.split('.')[-3].split('/')[-1] == \"cat\":\n                self.m_label.append(0)\n            elif file_name.split('.')[-3].split('/')[-1] == \"dog\":\n                self.m_label.append(1)\n\n        # 学習・評価データの区切り\n        self.partition = int(len(self.m_path) * 0.7)\n\n    def __call__(self, phase):\n        if phase == \"train\":\n            return self.m_path[:self.partition], self.m_label[:self.partition]\n        elif phase == \"val\":\n            return self.m_path[self.partition:], self.m_label[self.partition:]\n        else:\n            print(\"Error: GenderList required 'train' or 'val'\", file=sys.stderr)\n            sys.exit(1)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class AnimalDataset(data.Dataset):\n    '''\n    犬猫のDatasetを生成\n    '''\n\n    def __init__(self, file_list, label_list, transform=None):\n        self.file_list = file_list  # 画像ファイルパス\n        self.label_list = label_list  # ラベル\n        self.transform = transform  # 前処理のインスタンス\n\n    def __len__(self):\n        '''\n        画像枚数を返す\n        '''\n        return len(self.file_list)\n\n    def __getitem__(self, index):\n        '''\n        前処理した画像のテンソル形式のデータを取得\n        '''\n\n        # 画像をロード\n        img_path = self.file_list[index]\n        img = Image.open(img_path)\n\n        # 前処理\n        img_t = self.transform(img)\n\n        return img_t, int(self.label_list[index])","metadata":{"execution":{"iopub.status.busy":"2023-07-14T08:03:45.803703Z","iopub.execute_input":"2023-07-14T08:03:45.804395Z","iopub.status.idle":"2023-07-14T08:04:10.739664Z","shell.execute_reply.started":"2023-07-14T08:03:45.804355Z","shell.execute_reply":"2023-07-14T08:04:10.738256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import scipy.io\nfrom PIL import Image\nimport numpy as np\nfrom torchvision import transforms\nimport torch\nimport torch.utils.data as data\nimport os\nimport sys\nimport torch.optim as optim\nfrom tqdm import tqdm\nimport torch.nn as nn\nfrom glob import glob\nimport re\nimport csv\nfrom torch.nn import functional as F\nimport pandas as pd","metadata":{"execution":{"iopub.status.busy":"2023-07-14T08:08:50.020994Z","iopub.execute_input":"2023-07-14T08:08:50.021490Z","iopub.status.idle":"2023-07-14T08:08:53.778460Z","shell.execute_reply.started":"2023-07-14T08:08:50.021438Z","shell.execute_reply":"2023-07-14T08:08:53.777372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ImageTransform:\n    '''\n    画像の前処理を行う\n    画像のリサイズ，色の標準化\n    '''\n\n    def __init__(self, resize, mean, std):\n        self.data_transform = transforms.Compose(\n            [\n                transforms.Resize(resize),  # 短辺をの長さをresizeに\n                transforms.CenterCrop(resize),  # 画面中央を大きさresizeに切り取り\n                transforms.ToTensor(),  # テンソルに変換\n                transforms.Normalize(mean, std),  # 色情報の標準化\n            ]\n        )\n\n    def __call__(self, img):\n        return self.data_transform(img)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"class AnimalList:\n    '''\n    画像とラベルからリストを作成\n    \"train\"指定 : 前半７割のデータ\n    \"val指定 : 後半３割のデータ\n    '''\n\n    def __init__(self):\n        self.m_path = []  # 画像パス\n        self.m_label = []  # ラベル\n        \n        folder_path = \"/kaggle/working/train/\"\n        \n        files = glob(folder_path + \"*.jpg\")\n\n        for file_name in files:\n            # 画像パス と ラベル\n            self.m_path.append(file_name)\n            if file_name.split('.')[-3].split('/')[-1] == \"cat\":\n                self.m_label.append(0)\n            elif file_name.split('.')[-3].split('/')[-1] == \"dog\":\n                self.m_label.append(1)\n\n        # 学習・評価データの区切り\n        self.partition = int(len(self.m_path) * 0.7)\n        \n    def __call__(self, phase):\n        if phase == \"train\":\n            return self.m_path[:self.partition], self.m_label[:self.partition]\n        elif phase == \"val\":\n            return self.m_path[self.partition:], self.m_label[self.partition:]\n        else:\n            print(\"Error: GenderList required 'train' or 'val'\", file=sys.stderr)\n            sys.exit(1)","metadata":{"execution":{"iopub.status.busy":"2023-07-14T08:11:28.876820Z","iopub.execute_input":"2023-07-14T08:11:28.877227Z","iopub.status.idle":"2023-07-14T08:11:28.887873Z","shell.execute_reply.started":"2023-07-14T08:11:28.877199Z","shell.execute_reply":"2023-07-14T08:11:28.886783Z"},"trusted":true},"execution_count":null,"outputs":[]}]}