{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport keras\nfrom keras.applications.vgg19 import VGG19\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Flatten\nimport matplotlib.pyplot as plt #그림을 그려주는 라이브러리\n\n\nimport os\nfrom tqdm import tqdm #돌고있는 내용을 보여주는\nfrom sklearn import preprocessing #데이터분석 라이브러리\nfrom sklearn.model_selection import train_test_split\nimport cv2\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"!ls ../input","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv('../input/labels.csv')\ndf_test = pd.read_csv('../input/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.head(5)\n# 아래를 보면 one hot 형식으로 되어있음을 알 수 있다.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"targets_series = pd.Series(df_train['breed']) \n#breed와 index를 Series구조화\n\none_hot = pd.get_dummies(targets_series, sparse = True) \n# spare data(밀도가 낮은 데이터)? - https://blog.naver.com/qbxlvnf11/221429203293\n# get_dummies는 위와 같이 one hot 형식으로 나타내게 해주는 함수(one hot encoding) - https://homeproject.tistory.com/4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"one_hot_labels = np.asarray(one_hot)\n#one hot형식으로 인코딩 한 내용을 다시 어레이 형태로 변환","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* * * * **이제부터 이미지를 불러온다!**"},{"metadata":{"trusted":true},"cell_type":"code","source":"im_size = 128\n#224로 하면 RAM부족 ㅠㅠ\n\nx_train = []\ny_train = []\nx_test = []","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i = 0 \nfor f, breed in tqdm(df_train.values): #tqdm은 반복문의 진행상황을 알려준다.\n    img = cv2.imread('../input/train/{}.jpg'.format(f))\n    label = one_hot_labels[i]\n    x_train.append(cv2.resize(img, (im_size, im_size)))\n    y_train.append(label)\n    i += 1###############################????","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"위에서 x_train과 y_train set을 만들었다."},{"metadata":{"trusted":true},"cell_type":"code","source":"for f in tqdm(df_test['id'].values):\n    img = cv2.imread('../input/test/{}.jpg'.format(f))\n    x_test.append(cv2.resize(img, (im_size, im_size)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"위에서 x_test set을 만들었다.\n>>>df(____).values는 value값을 가져와서 array형태로 만든다.(딕셔너리 함수)"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train_raw = np.array(y_train, np.uint8)\n#리스트 형태를 넘파이 ndarray형태로\nx_train_raw = np.array(x_train, np.float32) / 255.\nx_test  = np.array(x_test, np.float32) / 255. \n##255로 나누는 것은 RGB값","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(x_train_raw.shape)\nprint(y_train_raw.shape)\nprint(x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"위의 코드 결과를 보면 <br>\nTRAIN SET은 10222개이고 224 x 224 사이즈 3채널(RGB) / Y는 120 breeds <br>\nTEST SET은 10357개이고 224 x 224 사이즈 3채널(RGB) <br>\n<h2>--> 원하는 데이터 형태!</h2>"},{"metadata":{"trusted":true},"cell_type":"code","source":"num_class = 120\n# 120 breeds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_valid, Y_train, Y_valid = train_test_split(x_train_raw, y_train_raw, test_size=0.3, random_state=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"위의 코드 중 train_test_split 함수는 data를 나눠주는 함수이다. 아래 링크 참조 <br>\nhttps://blog.naver.com/siniphia/221396370872\n\n------------------------------------------------\n이제부터 CNN 구조를 모델링한다!!"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Create the base pre-trained model\n# Can't download weights in the kernel\nbase_model = VGG19(#weights='imagenet',\n    weights = None, \n    include_top=False, input_shape=(im_size, im_size, 3))\n##Dense layer(fully connected layers)는 모두 연결되어 있어 include_top=False를 하고 input_shape를 변경해야한다.\n##참고링크(https://rarena.tistory.com/entry/keras-%ED%8A%B9%EC%A0%95-%EB%AA%A8%EB%8D%B8%EB%A1%9C%EB%93%9C%ED%95%98%EC%97%AC-%EB%82%B4-%EB%A0%88%EC%9D%B4%EC%96%B4)\n\n# 내가 붙일 레이어 2개를 기존의 VGG19모델에 붙여 넣는다.\n\nx = base_model.output\nx = Flatten()(x)\npredictions = Dense(num_class, activation='softmax')(x)\n\n# 우리가 트레인 시킬 모델 완성!\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\n# First: train only the top layers (which were randomly initialized)\nfor layer in base_model.layers:\n    layer.trainable = False\n\nmodel.compile(loss='categorical_crossentropy', \n              optimizer='adam', \n              metrics=['accuracy'])\n\ncallbacks_list = [ #keras.callbacks.EarlyStopping(monitor='val_acc', patience=10, verbose=1),\n                 keras.callbacks.ModelCheckpoint('my_model.h5', monitor='val_loss', verbose=1, save_best_only=True)]\nmodel.summary()\n\n##MaxPooling에 관한 설명 (https://blog.naver.com/pgh7092/221106015450)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist = model.fit(X_train, Y_train, epochs=50, validation_data=(X_valid, Y_valid), verbose=1, callbacks=callbacks_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#  모델 학습 과정 표시하기\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nfig, loss_ax = plt.subplots()\n\nacc_ax = loss_ax.twinx()\n\nloss_ax.plot(hist.history['loss'], 'y', label='train loss')\nloss_ax.plot(hist.history['val_loss'], 'r', label='val loss')\n\nacc_ax.plot(hist.history['acc'], 'b', label='train acc')\nacc_ax.plot(hist.history['val_acc'], 'g', label='val acc')\n\nloss_ax.set_xlabel('epoch')\nloss_ax.set_ylabel('loss')\nacc_ax.set_ylabel('accuray')\n\nloss_ax.legend(loc='upper left')\nacc_ax.legend(loc='lower left')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.predict(x_test, verbose=1)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":1}