{"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 the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\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":"os.listdir(\"../\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not os.path.exists(\"../train\"):\n    os.mkdir(\"../train\")\nif not os.path.exists(\"../train/dog\"):\n    os.mkdir(\"../train/dog\")\nif not os.path.exists(\"../train/cat\"):\n    os.mkdir(\"../train/cat\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import shutil\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in tqdm(os.listdir(\"../input/train/train\")):\n#     print(i)\n    if i.split(\".\")[0] == \"dog\":\n        shutil.copy2(os.path.join(\"../input/train/train\",i),os.path.join(\"../train/dog\",i))\n    elif i.split(\".\")[0] == \"cat\":\n        shutil.copy2(os.path.join(\"../input/train/train\",i),os.path.join(\"../train/cat\",i))\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not os.path.exists(\"../test\"):\n    os.mkdir(\"../test\")\nif not os.path.exists(\"../test/dog\"):\n    os.mkdir(\"../test/dog\")\nif not os.path.exists(\"../test/cat\"):\n    os.mkdir(\"../test/cat\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in tqdm(os.listdir(\"../train/dog\")[:3000]):\n    shutil.move(os.path.join(\"../train/dog\",i),os.path.join(\"../test/dog\",i)) \nfor i in tqdm(os.listdir(\"../train/cat\")[:3000]):\n    shutil.move(os.path.join(\"../train/cat\",i),os.path.join(\"../test/cat\",i)) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras import optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(\"../train\")","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"trdata = ImageDataGenerator()\ntraindata = trdata.flow_from_directory(directory=\"../train\",target_size=(224,224))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tsdata = ImageDataGenerator()\ntestdata = tsdata.flow_from_directory(directory=\"../test\", target_size=(224,224))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications.vgg16 import VGG16","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vggmodel = VGG16(weights='imagenet', include_top=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vggmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for layers in (vggmodel.layers)[:19]:\n    print(layers)\n    layers.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X= vggmodel.layers[-2].output","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = Dense(2, activation=\"softmax\")(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_final = Model(input = vggmodel.input, output = predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_final.compile(loss = \"categorical_crossentropy\", optimizer = optimizers.SGD(lr=0.0001, momentum=0.9), metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_final.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(\"../\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpoint = ModelCheckpoint(\"vgg16_1.h5\", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)\nearly = EarlyStopping(monitor='val_acc', min_delta=0, patience=40, verbose=1, mode='auto')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist = model_final.fit_generator(generator= traindata, steps_per_epoch= 2, epochs= 100, validation_data= testdata, validation_steps=1, callbacks=[checkpoint,early])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_final.save_weights(\"vgg16_1.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\ndf=pd.read_csv(\"../input/sampleSubmission.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(df[\"label\"][0])\npd.options.mode.chained_assignment = None  # default='warn'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for e,i in enumerate(os.listdir(\"../input/test1/test1\")):\n    print(i)\n    output=[]\n    img = image.load_img(os.path.join(\"../input/test1/test1\",i),target_size=(224,224))\n    img = np.asarray(img)\n    img = np.expand_dims(img, axis=0)\n    output = model_final.predict(img)\n    if output[0][0] > output[0][1]:\n#         print(\"cat\")\n        df[\"id\"][e]=i\n        df[\"label\"][e]=\"cat\"\n    else:\n#         print('dog')\n        df[\"id\"][e]=i\n        df[\"label\"][e]=\"dog\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}