{"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":"from zipfile import ZipFile\nimport cv2\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import array_to_img, img_to_array, load_img, ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nfrom PIL import Image\nfrom tensorflow.keras.backend import flatten\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.layers import Conv2D,UpSampling2D,Dropout,Input,MaxPooling2D,concatenate,Input,BatchNormalization,Conv2DTranspose,Flatten,Dense,Reshape\nfrom tensorflow.keras import Sequential,Model\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.losses import binary_crossentropy, categorical_crossentropy\nimport tensorflow as tf\nfrom sklearn.cluster import KMeans","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('../input/dogs-vs-cats')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":false},"cell_type":"code","source":"zip_file_name = '../input/dogs-vs-cats/train.zip'\nwith ZipFile(zip_file_name, 'r') as zip: \n    # printing all the contents of the zip file \n    # extracting all the files \n    print('Extracting all the files now...') \n    zip.extractall() \n    print('Done!')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('./')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=17\nk = img_to_array(load_img('train/'+train[i]))\nfig,arr = plt.subplots(1,1)\nfig.set_figheight(5)\nfig.set_figwidth(5)\narr.imshow(k/255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train[0].split('.')[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Subset of training data\ntrain_sub,_ = train_test_split(train,train_size=0.4)\nlen(train_sub)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#training and validation split\ntrain_images,val_images = train_test_split(train_sub,train_size=0.8)\nlen(train_images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_gen(dir_path_img,imgs,dims,batch_size):\n    while True:\n        idx = np.random.choice(np.arange(len(imgs)),batch_size)\n        images =[]\n        for i in idx:\n            img = Image.open(dir_path_img+imgs[i])\n            images.append(np.array(img.resize(dims))/255)\n            \n        yield np.array(images),np.array(images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gen = data_gen('train/',train_images,(256,256),20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Testing generator\nimg,_ = next(gen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=5\nplt.imshow(img[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dim = (256,256)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dim","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Encoder\ninp = Input((dim[0],dim[1],3))\nenc = Conv2D(64,(3,3),activation='relu',padding='same')(inp)\nenc = MaxPooling2D((2,2))(enc)\nenc = Conv2D(128,(3,3),activation='relu',padding='same')(enc)\nenc = MaxPooling2D((2,2))(enc)\nenc = Conv2D(256,(3,3),activation='relu',padding='same')(enc)\nenc = MaxPooling2D((2,2))(enc)\nenc = Conv2D(512,(3,3),activation='relu',padding='same')(enc)\nenc = MaxPooling2D((2,2))(enc)\nenc = Conv2D(512,(3,3),activation='relu',padding='same')(enc)\nlatent = Flatten()(enc)\nlatent = Dense(192,activation = 'softmax')(latent)\n\n#Decoder\ndec = Reshape((8,8,3))(latent)\ndec = Conv2DTranspose(512,(3,3),strides = 2,activation = 'relu',padding='same')(dec)\ndec = BatchNormalization()(dec)\ndec = Conv2DTranspose(512,(3,3),strides = 2,activation = 'relu',padding='same')(dec)\ndec = BatchNormalization()(dec)\ndec = Conv2DTranspose(256,(3,3),strides = 2,activation = 'relu',padding='same')(dec)\ndec = BatchNormalization()(dec)\ndec = Conv2DTranspose(128,(3,3),strides = 2,activation = 'relu',padding='same')(dec)\ndec = BatchNormalization()(dec)\ndec = Conv2DTranspose(64,(3,3),strides = 2,activation = 'relu',padding='same')(dec)\ndecoded = Conv2D(3,(3,3),activation='sigmoid',padding='same')(dec)\n\n#Autoencoder\nae = Model(inp,decoded)\nae.compile(optimizer = Adam(lr = 1e-5), loss = 'mse')\nae.summary()\n#Adam(lr = 1e-2)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 20\nspe = len(train_images)//batch_size\ngen_train = data_gen('train/',train_images,(dim[0],dim[1]),batch_size)\ngen_val = data_gen('train/',val_images,(dim[0],dim[1]),batch_size)\n#early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)\nae.fit(gen_train,steps_per_epoch=spe,epochs=10 )\n#, validation_data = gen_val, validation_steps=len(val_images)//batch_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gen = data_gen('train/',val_images,(256,256),20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data,_ = next(gen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res = ae.predict(test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=7\nfig=plt.figure()\nfig.add_subplot(1,2,1)\nplt.imshow(res[i])\nfig.add_subplot(1,2,2)\nplt.imshow(test_data[i])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.sum(res[0]!=res[3])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"9*9*3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"encoder = Model(inputs=ae.input,outputs=ae.get_layer('dense_4').output)\nencoder.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create the new nodes for each layer in the path\\\nidx = 12\nlayer_input=Input(shape=192)\nx = layer_input\nfor layer in ae.layers[idx:]:\n    x = layer(x)\n\n# create the model\ndecoder = Model(layer_input, x)\ndecoder.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"encoder.save('enc.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gen = data_gen('train/',val_images,(256,256),500)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_data_full,_ = next(gen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = encoder.predict(val_data_full)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"kmeans =  KMeans(n_clusters=2, max_iter=1000,n_init=20)\nkmeans.fit(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"k_lab = kmeans.labels_","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grp1,grp2 = val_data_full[k_lab==1],val_data_full[k_lab==0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig=plt.figure(figsize=(20, 10))\ncolumns = 6\nrows = 1\nfor i in range(1, columns*rows +1):\n    img = grp1[i]\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(img)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"w=20\nh=10\nfig=plt.figure(figsize=(20, 10))\ncolumns = 6\nrows = 1\nfor i in range(1, columns*rows +1):\n    img = grp2[i]\n    fig.add_subplot(rows, columns, i)\n    plt.imshow(img)\nplt.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}