{"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 \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n#import os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n       # print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"라이브러리 로드"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\n#from imutils import paths\nimport numpy as np\n#import imutils \nimport cv2 \nimport os\nimport glob\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"학습 데이터 준비"},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_train = \"/kaggle/input/2019-fall-pr-project/train/train/\"\n#forder_path = \"/content/input2/train/train/*.jpg\"\nforder_path = \"/content/input2/test1/test1/*.jpg\"\n\nimgs_train = []\nlabel_train = []\n\nfor img_path in os.listdir(dataset_train):\n  if str.find(img_path, 'cat'):\n    label_train.append(0)\n  else:\n    label_train.append(1)\n  img = cv2.imread(dataset_train+img_path)\n  #print(dataset_train+img_path)\n  #img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n  data = cv2.resize(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY), (32, 32))\n  data = np.reshape(data, -1)\n  imgs_train.append(data)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"데이터 셋 서브 샘플링 & Train-Validation 나누기"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import StandardScaler, MinMaxScaler\n\n#x_train, x_test, y_train, y_test = train_test_split(imgs_train, label_train, test_size=0.25, random_state=42)\nx_train, x_test, y_train, y_test = train_test_split(imgs_train, label_train, test_size=0.10, random_state=42)\n\nscaler = StandardScaler()\n#scaler = MinMaxScaler\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.fit_transform(x_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"학습 기반 분류기 설계"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import classification_report\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import GridSearchCV\n\nclf = SVC(kernel='rbf', class_weight='balanced', random_state=42)\n\n\nparam_grid = {'C':[0.01, 0.1, 0.5, 1, 5, 10], 'gamma':[0.01, 0.1,1, 5,10, 50]}\n\nclf = GridSearchCV(clf, param_grid, cv=3)\n\n#clf.fit(x_train, y_train)\nclf.fit(x_test, y_test)\n\n\nmodel = clf.best_estimator_\n\nprint(clf.best_params_)\n\n\ny_predict = model.predict(x_test)\n\nscore = classification_report(y_test, y_predict)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"테스트 데이터 준비"},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_test = \"/kaggle/input/2019-fall-pr-project/test1/test1/\"\n\nimgs_test = []\ntest_id = []\n\nfor img_path in os.listdir(dataset_test):\n  iid, _ = img_path.split('.')\n  iid = int(iid)\n  test_id.append(iid)\n  img = cv2.imread(dataset_test+img_path)\n  data = cv2.resize(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY), (32, 32))\n  data = np.reshape(data, -1)\n  imgs_test.append(data)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"학습한 모델을 이용하여 테스트 데이터의 라벨 구하기"},{"metadata":{"trusted":true},"cell_type":"code","source":"result = model.predict(imgs_test)\nresult\nprint(score)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"결과 파일로 저장하여 Kaggle 제출 "},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nresult = result\nprint(result.shape)\nprint(result)\ndf = pd.DataFrame(result)\ndf.index = df.index+1\n#df = pd.DataFrame(columns=['id', 'label'])\ndf = df.replace('dog',1)\ndf = df.replace('cat',0)\n\nprint(df)\nf = ['label']\ndf2 = pd.DataFrame(f,index=['id'])\n\nprint(df2)\ndf3 = df2.append(df)\nprint(df3)\n#df= df3\ndf3.to_csv('results-sm-v6.csv',index=True, header=False)\n! kaggle competitions submit -c 2019-fall-pr-project -f results-sm-v6.csv -m \"smwi-1102\"","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}