{"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\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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import Input, models, layers, optimizers, metrics\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.applications import VGG16\nfrom keras.applications import xception\nfrom os import listdir, makedirs\nfrom os.path import join, exists, expanduser\nimport pandas as pd\nimport datetime as dt\nnp.random.seed(3)\ntf.compat.v1.set_random_seed(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls ../input/keras-pretrained-models/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start = dt.datetime.now()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cache_dir = expanduser(join('~', '.keras'))\nif not exists(cache_dir):\n    makedirs(cache_dir)\nmodels_dir = join(cache_dir, 'models')\nif not exists(models_dir):\n    makedirs(models_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp ../input/keras-pretrained-models/*notop* ~/.keras/models/\n!cp ../input/keras-pretrained-models/imagenet_class_index.json ~/.keras/models/\n!cp ../input/keras-pretrained-models/resnet50* ~/.keras/models/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls ~/.keras/models","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls ../input/dog-breed-identification","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"INPUT_SIZE = 224\nNUM_CLASSES = 5\nSEED = 1987\ndata_dir = '../input/dog-breed-identification'\nlabels = pd.read_csv(join(data_dir, 'labels.csv'))\nsample_submission = pd.read_csv(join(data_dir, 'sample_submission.csv'))\nprint(len(listdir(join(data_dir, 'train'))), len(labels))\nprint(len(listdir(join(data_dir, 'test'))), len(sample_submission))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_CLASSES = 20","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"selected_breed_list = list(labels.groupby('breed').count().sort_values(by='id', ascending=False).head(NUM_CLASSES).index)\nlabels = labels[labels['breed'].isin(selected_breed_list)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(selected_breed_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_path = os.path.join(data_dir,'train/')\nlabels = labels.assign(img_path = lambda x : img_path + x['id']+'.jpg')\nlabels = labels.assign(file_name = lambda x : x['id']+'.jpg')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(labels[['id','img_path','file_name']], labels['breed'], test_size=0.2, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.head())\nprint(y_train.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train = pd.DataFrame({\"X\":X_train['id'],\"X_path\":X_train['img_path'],\"Y\":y_train})\ntrain = pd.DataFrame({\"X\":X_train['id'],\"X_path\":X_train['img_path'],\"X_filename\":X_train['file_name'],\"Y\":y_train})\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.DataFrame({\"X\":X_test['id'],\"X_path\":X_test['img_path'],\"X_filename\":X_test['file_name'],\"Y\":y_test})\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./255,\n                                  horizontal_flip=True,\n                                   vertical_flip=True,                                   \n                                  width_shift_range=0.1,\n                                  height_shift_range=0.1,\n                                   rotation_range=5,\n                                   shear_range=0.7,\n                                   zoom_range=1.2,\n                                  fill_mode='nearest')\n\n# train_generator = train_datagen.flow_from_directory(\n#        '../input/dog-breed-identification/train',\n#        target_size=(150, 150),\n#        batch_size=50,\n#        class_mode='categorical')\n\ntrain_generator = train_datagen.flow_from_dataframe(train, x_col=\"X_path\",\n                                                    y_col=\"Y\",\n                                                    target_size=(299, 299),\n                                                    class_mode='categorical',\n                                                    batch_size=32,\n                                                    seed=33,\n                                                    interpolation='nearest',)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_dataframe(test, x_col=\"X_path\",\n                                                    y_col=\"Y\",\n                                                    target_size=(299, 299),\n                                                    class_mode='categorical',\n                                                    batch_size=32,\n                                                    seed=33,\n                                                    interpolation='nearest',)\n\n\n# test_generator = test_datagen.flow_from_directory(\n#        '../input/dog-breed-identification/test',\n#        target_size=(150, 150),\n#        batch_size=50,\n#        class_mode='categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_img(img_id, train_or_test, size):\n    \"\"\"Read and resize image.\n    # Arguments\n        img_id: string\n        train_or_test: string 'train' or 'test'.\n        size: resize the original image.\n    # Returns\n        Image as numpy array.\n    \"\"\"\n    img = image.load_img(join(data_dir, train_or_test, '%s.jpg' % img_id), target_size=size)\n    img = image.img_to_array(img)\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tqdm import tqdm\nfrom keras.preprocessing import image\nINPUT_SIZE = 299\nPOOLING = 'avg'\nx_train = np.zeros((len(labels), INPUT_SIZE, INPUT_SIZE, 3), dtype='float32')\nfor i, img_id in tqdm(enumerate(labels['id'])):\n    img = read_img(img_id, 'train', (INPUT_SIZE, INPUT_SIZE))\n    x = xception.preprocess_input(np.expand_dims(img.copy(), axis=0))\n    x_train[i] = x\nprint('Train Images shape: {} size: {:,}'.format(x_train.shape, x_train.size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels['target'] = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels_pivot = labels.pivot('id', 'breed', 'target').reset_index().fillna(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.random.seed(seed=SEED)\nrnd = np.random.random(len(labels))\ntrain_idx = rnd < 0.8\nvalid_idx = rnd >= 0.8\ny_train = labels_pivot[selected_breed_list].values\nytr = y_train[train_idx]\nyv = y_train[valid_idx]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Xtr = x_train[train_idx]\nXv = x_train[valid_idx]\nprint((Xtr.shape, Xv.shape, ytr.shape, yv.shape))\nxception_bottleneck = xception.Xception(weights='imagenet', include_top=False, pooling=POOLING)\ntrain_x_bf = xception_bottleneck.predict(Xtr, batch_size=32, verbose=1)\nvalid_x_bf = xception_bottleneck.predict(Xv, batch_size=32, verbose=1)\nprint('Xception train bottleneck features shape: {} size: {:,}'.format(train_x_bf.shape, train_x_bf.size))\nprint('Xception valid bottleneck features shape: {} size: {:,}'.format(valid_x_bf.shape, valid_x_bf.size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(Xtr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(Xv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(ytr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(yv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print((ytr * range(NUM_CLASSES)).sum(axis=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import log_loss, accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nlogreg = LogisticRegression(multi_class='multinomial', solver='lbfgs', random_state=SEED)\nlogreg.fit(train_x_bf, (ytr * range(NUM_CLASSES)).sum(axis=1))\nvalid_probs = logreg.predict_proba(valid_x_bf)\nvalid_preds = logreg.predict(valid_x_bf)\nprint('Validation Xception LogLoss {}'.format(log_loss(yv, valid_probs)))\nprint('Validation Xception Accuracy {}'.format(accuracy_score((yv * range(NUM_CLASSES)).sum(axis=1), valid_preds)))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import load_model\nimport pickle\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"saved_model = pickle.dumps(logreg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"log_from_pickle = pickle.loads(saved_model)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"log_from_pickle.predict(valid_x_bf)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"log_from_pickle.predict_proba(valid_x_bf)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import sklearn.external.joblib as extjoblib\nimport joblib","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"joblib.dump(logreg, 'god_log.pkl') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"log_from_joblib = joblib.load('god_log.pkl') \nlog_from_joblib.predict(valid_x_bf)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"crawling = pd.read_csv('../input/crawling-data1/fin_pure_data1_891.csv',encoding='cp949')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"crawling.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('../input/crawlingdata1/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import re","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"matchObj = re.search('\\d{4}-\\d{5}', '░°░φ╣°╚ú-┴ª┴╓-┴ª┴╓-2019-06205 ║╨╜╟╡╚╡┐╣░╗τ┴°.jpg')\nmatchObj.group()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"crawling.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"crawling[['notice_num']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"crawling['keys'] = crawling['notice_num'].str.slice(start=6, stop=16) # 인덱스 사이 값 반환","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"crawling.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_dir = '../input/img-renamed/crawling_photo/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_img(img_id, size):\n    \"\"\"Read and resize image.\n    # Arguments\n        img_id: string\n        train_or_test: string 'train' or 'test'.\n        size: resize the original image.\n    # Returns\n        Image as numpy array.\n    \"\"\"\n    img = image.load_img(join(data_dir, '%s.jpg' % img_id), target_size=size)\n    img = image.img_to_array(img)\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_pred = np.zeros((1, INPUT_SIZE, INPUT_SIZE, 3), dtype='float32')\n\nimg = read_img('2019-00108', (INPUT_SIZE, INPUT_SIZE))\n\nx = xception.preprocess_input(np.expand_dims(img.copy(), axis=0))\nx_pred[0] = x\nprint('Train Images shape: {} size: {:,}'.format(x_train.shape, x_train.size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_x_bf = xception_bottleneck.predict(x_pred, batch_size=32, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_dog = log_from_joblib.predict(train_x_bf)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"selected_breed_list[pred_dog[0].astype(int)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(crawling[crawling['keys']=='2019-00108'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_breeds = (yv * range(NUM_CLASSES)).sum(axis=1)\nerror_idx = (valid_breeds != valid_preds)\nfor img_id, breed, pred in zip(labels.loc[valid_idx, 'id'].values[error_idx],\n                                [selected_breed_list[int(b)] for b in valid_preds[error_idx]],\n                                [selected_breed_list[int(b)] for b in valid_breeds[error_idx]]):\n    fig, ax = plt.subplots(figsize=(5,5))\n    img = read_img(img_id, 'train', (299, 299))\n    ax.imshow(img / 255.)\n    ax.text(10, 250, 'Prediction: %s' % pred, color='w', backgroundcolor='r', alpha=0.8)\n    ax.text(10, 270, 'LABEL: %s' % breed, color='k', backgroundcolor='g', alpha=0.8)\n    ax.axis('off')\n    plt.show()                                                    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":4}