{"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":"none","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-05-23T05:53:39.204109Z","iopub.execute_input":"2024-05-23T05:53:39.204498Z","iopub.status.idle":"2024-05-23T05:53:40.227256Z","shell.execute_reply.started":"2024-05-23T05:53:39.204466Z","shell.execute_reply":"2024-05-23T05:53:40.226115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Week3. 고양이 vs 강아지 분류하기\n- 참고 사이트: https://velog.io/@freesky/Kaggle-cats-vs-dogs\n1. Data 불러와 정리하기\n2. 이미지 제네레이터 이용\n3. 모델 정의","metadata":{}},{"cell_type":"markdown","source":"## 1. Data 불러와 정리하기","metadata":{}},{"cell_type":"code","source":"!unzip -q -o /kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\n!unzip -q -o /kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:01:05.234303Z","iopub.execute_input":"2024-05-23T06:01:05.235086Z","iopub.status.idle":"2024-05-23T06:01:25.742509Z","shell.execute_reply.started":"2024-05-23T06:01:05.235033Z","shell.execute_reply":"2024-05-23T06:01:25.741017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import glob\nglob.glob('train/*')[:5]","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:01:29.143823Z","iopub.execute_input":"2024-05-23T06:01:29.144612Z","iopub.status.idle":"2024-05-23T06:01:29.220665Z","shell.execute_reply.started":"2024-05-23T06:01:29.144566Z","shell.execute_reply":"2024-05-23T06:01:29.219794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nImage.open('train/cat.5978.jpg')","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:01:55.958504Z","iopub.execute_input":"2024-05-23T06:01:55.95896Z","iopub.status.idle":"2024-05-23T06:01:56.081283Z","shell.execute_reply.started":"2024-05-23T06:01:55.958917Z","shell.execute_reply":"2024-05-23T06:01:56.079914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.DataFrame({\"path\": glob.glob(\"train/*\")})\ndf_train","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:03:17.70725Z","iopub.execute_input":"2024-05-23T06:03:17.708322Z","iopub.status.idle":"2024-05-23T06:03:17.803941Z","shell.execute_reply.started":"2024-05-23T06:03:17.708279Z","shell.execute_reply":"2024-05-23T06:03:17.802586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# path 속성 값에서 /을 기준으로 나눈 것의 맨 오른쪽 요소를\n# .을 기준으로 나눈 것의 맨 왼쪽 요소를 label 컬럼에 넣는다.\ndf_train['label'] = df_train['path'].\\\napply(lambda x:x.split('/')[-1].split('.')[0])\ndf_train","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:06:02.100258Z","iopub.execute_input":"2024-05-23T06:06:02.100994Z","iopub.status.idle":"2024-05-23T06:06:02.130626Z","shell.execute_reply.started":"2024-05-23T06:06:02.100957Z","shell.execute_reply":"2024-05-23T06:06:02.129478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. 이미지 제너레이터","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nidg = ImageDataGenerator()\n\ntrain_generator = idg.flow_from_dataframe(\n    df_train, # 사용 데이터 프레임\n    x_col = 'path', # 파일 위치 열이름\n    y_col = 'label', # 클래스 열 이름\n    batch_size = 64, # batch_size 단위로 나누어 진행함\n    target_size = (100, 100)) # 이미지 사이즈","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:09:53.968968Z","iopub.execute_input":"2024-05-23T06:09:53.96946Z","iopub.status.idle":"2024-05-23T06:09:54.215965Z","shell.execute_reply.started":"2024-05-23T06:09:53.969425Z","shell.execute_reply":"2024-05-23T06:09:54.214597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. 모델 정의","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import *\nfrom tensorflow.keras.layers import *\n\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\n\n# 레이어를 선형으로 연결하여 구성\n# 레이어 인스턴스를 생성자에게 넘겨줌\nmodel = Sequential()\n\n# 48개 계층으로 구성된 CNN\niv = InceptionV3(\n    # 네트워크 마지막 계층, 맨 위 완전 연결 계층을 포함할지 여부\n    # 기본값은 True\n    include_top = False,\n    # include_top이 False인 경우, 기능 추출을 위한 선택적 풀링 모드\n    # 기본값 None, 모델 출력이 마지막 컨벌루션 블록의 4D 텐서 출력이 됨\n    # avg인 경우, 글로벌 평균 풀링이 마지막 컨볼루션 블록 출력에 적용되므로\n        # 모델 출력이 2D 텐서가 됨\n    # max인 경우, 글로벌 최대 풀링이 적용됨\n    pooling = 'avg')\n\nmodel.add(iv)\n# Dense: units 양의 정수, 출력 공간의 차원, activation 사용할 활성화 기능\n# 지정하지 않으면 활성화 적용되지 않는다.\nmodel.add(Dense(2, activation = 'softmax'))\n# softmax: 입력받은 값을 0~1 사이의 값으로 모두 정규화하여 출력\n    # 출력값들의 총합은 항상 1이 됨","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:12:19.386387Z","iopub.execute_input":"2024-05-23T06:12:19.387174Z","iopub.status.idle":"2024-05-23T06:12:24.488662Z","shell.execute_reply.started":"2024-05-23T06:12:19.387139Z","shell.execute_reply":"2024-05-23T06:12:24.487514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    metrics = 'acc',\n    loss = 'categorical_crossentropy',\n    optimizer = 'adam')\n\nmodel.fit(train_generator)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T06:19:14.903351Z","iopub.execute_input":"2024-05-23T06:19:14.903804Z","iopub.status.idle":"2024-05-23T06:19:14.959957Z","shell.execute_reply.started":"2024-05-23T06:19:14.903738Z","shell.execute_reply":"2024-05-23T06:19:14.958384Z"},"trusted":true},"execution_count":null,"outputs":[]}]}