{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom pandas import DataFrame, Series\nimport random\nfrom tqdm import tqdm\nimport os\nimport math\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\nimport cv2\nfrom keras.utils import to_categorical\nimport glob\nfrom matplotlib import pyplot as plt\nimport cv2\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, Flatten, MaxPool2D\nfrom keras.optimizers import adam\nfrom keras import regularizers\nfrom keras.utils import plot_model\nfrom keras.applications.vgg19 import VGG19\nfrom keras.layers import Input, Dense, Dropout\nfrom keras import backend as K\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train_path = '../input/train/*.jpg'\nx_train_adres = glob.glob(train_path)\n\nm_train = len(x_train_adres)\ny_train = np.zeros((m_train,1))\nfor i,ca in enumerate(x_train_adres):\n    if 'cat' in ca:\n        y_train[i] = 1\nprint(y_train.shape)\n  \n# print(y_train)\n# print(x_train_adres[m_train-1])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4aeae68b816dd579b7ca22b22aa2b4dd2b2359ee"},"cell_type":"code","source":"wid = 100\nn = wid*wid*3\nx_train = np.zeros((m_train, wid, wid, 3), dtype = np.float32)\n# for i in tqdm(range(5)):\nfor i in tqdm(range(len(x_train_adres))):\n    if i%1000 ==0:\n        print(i)\n    img = cv2.imread(x_train_adres[i])\n#     plt.imshow(img)\n#     plt.show()  \n#     print(y_train[i])\n    \n    img = (cv2.resize(cv2.cvtColor(img,cv2.COLOR_BGR2RGB),(wid,wid),interpolation=cv2.INTER_CUBIC))/255\n    x_train[i] = img\n#     print(x_train[i])\n    del img\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"779acecfd67d760ad16df0faec1bc0049363f407","scrolled":true,"collapsed":true},"cell_type":"code","source":"# img = cv2.resize(x_train[1000], (wid,wid))\n# plt.imshow(img)\n# plt.show()  \n# print(y_train[1000])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3dc6ddc265161dcb96c8b8ec6765aaa33a284622","scrolled":true},"cell_type":"code","source":"acc= []\nval_acc= []\nloss= []\nval_loss= []\n\nlamda = .0001\ninputs = Input(shape = (wid,wid,3))\n\nx = Conv2D(16, kernel_size=(3,3), activation = 'relu', kernel_regularizer=regularizers.l2(lamda))(inputs)\nx = MaxPool2D()(x)\nx = Conv2D(32, kernel_size=(3,3), activation = 'relu', kernel_regularizer=regularizers.l2(lamda))(x)\nx = MaxPool2D()(x)\nx = Conv2D(64, kernel_size=(3,3), activation = 'relu', kernel_regularizer=regularizers.l2(lamda))(x)\nx = MaxPool2D()(x)\nx = Conv2D(128, kernel_size=(3,3), activation = 'relu', kernel_regularizer=regularizers.l2(lamda))(x)\nx = MaxPool2D()(x)\nx = Conv2D(256, kernel_size=(3,3), activation = 'relu', kernel_regularizer=regularizers.l2(lamda))(x)\nx = MaxPool2D()(x)\n\nx = Flatten()(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(.5)(x)\n\nx = Dense(256, activation='relu')(x)\nx = Dropout(.5)(x)\n\nx = Dense(128, activation='relu')(x)\nx = Dropout(.5)(x)\n\noutput = Dense(1,  activation = 'sigmoid')(x)\n\nmodel = Model(inputs, output)\nopt = adam(lr=.001, beta_1=0.9, beta_2=0.999)\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer=opt,\n              metrics=['accuracy'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f86848d4efaadea00729c40d0249b2fb326bbbb0","scrolled":false},"cell_type":"code","source":"history = model.fit(x_train, y_train,\n              batch_size=64,\n              epochs=20,\n              validation_split = .1, \n              shuffle = True)\n\n\nacc += history.history['acc'] \nval_acc += history.history['val_acc'] \n\nplt.plot(acc)\nplt.plot(val_acc)\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n\nloss += history.history['loss'] \nval_loss += history.history['val_loss']\nplt.plot(loss)\nplt.plot(val_loss)\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"eb3215db1c44ef5055449c1cb1c021e438ea0b66","collapsed":true},"cell_type":"code","source":"# print(history.params)\n# history = model.fit(x_train, y_train,\n#               batch_size=64,\n#               epochs=50,\n#               validation_split = .1)\n\n\n# acc += history.history['acc'] \n# val_acc += history.history['val_acc'] \n\n# plt.plot(acc)\n# plt.plot(val_acc)\n# plt.title('model accuracy')\n# plt.ylabel('accuracy')\n# plt.xlabel('epoch')\n# plt.legend(['train', 'test'], loc='upper left')\n# plt.show()\n\n\n# loss += history.history['loss'] \n# val_loss += history.history['val_loss']\n# plt.plot(loss)\n# plt.plot(val_loss)\n# plt.title('model loss')\n# plt.ylabel('loss')\n# plt.xlabel('epoch')\n# plt.legend(['train', 'test'], loc='upper left')\n# plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"05d270f68333450b42528a4cf14ab69ddf3019ae","collapsed":true},"cell_type":"code","source":"model.save_weights('model_wieghts.h5')\nmodel.save('model_keras.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3e8ecad0bbe261cf14af5c0d40c694a3f1ef67bd","collapsed":true},"cell_type":"code","source":"#print(model.get_weights())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"daa15a35f3a9975654bf29a40c0359ee1622a3f2"},"cell_type":"code","source":"test_path = '../input/test/*.jpg'\nx_test_adres = glob.glob(test_path)\nprint(x_test_adres[0])\nm_test = len(x_test_adres)\ny_test = np.zeros((m_test,1))\n\nprint(y_test.shape)\n  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"eaa17f2aedbfbf7897dce719c5394dad63140852"},"cell_type":"code","source":"\nx_test = np.zeros((m_test, wid, wid, 3), dtype = np.float32)\n# for i in tqdm(range(5)):\nprint('Processing...')\n\nfor i, name in enumerate(x_test_adres):\n    if i%1000 ==0:\n        print(i)\n    \n    img = cv2.imread(x_test_adres[i])\n#     plt.imshow(img)\n#     plt.show()  \n\n    img = (cv2.resize(cv2.cvtColor(img,cv2.COLOR_BGR2RGB),(wid,wid),interpolation=cv2.INTER_CUBIC))/255\n    na = int(''.join([i for i in name if i.isdigit()]))\n#     print(na)\n    x_test[na-1] = img\n    del img\nprint('Predicting...')\ny_test = model.predict(x_test)\nprint(y_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"be0d36aa1481fc9018d6337651fcc7612bf4ee45","scrolled":true},"cell_type":"code","source":"plt.imshow(x_test[10005])\nplt.show() \nprint(y_test[10005])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"843315002918a51619a55b100f8965c2a1e2e82d","collapsed":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fed158df9facc9b12e4d97e1c8ae7bab4d97f046"},"cell_type":"code","source":"frame = pd.DataFrame({'label': y_test.T.squeeze()})\nframe = frame.reset_index(drop=True)\nframe.index += 1 \nframe.to_csv(\"Dogs Vs. Cats.csv\", index_label='id')\n\n# print(y_test[10000])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3676e90a060b28fb4927ca0b47084f991426fc20","collapsed":true},"cell_type":"code","source":"print(frame)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9e4d3a697ae083a5f3b766b3c47804263abf4de2","collapsed":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"bdd1bc16c6bc66730be6cfdce2ae733f302f0e6d"},"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}