{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## PreTrained Model : VGG16\n\n\n\nKeras library also provides the pre-trained model in which one can load the saved model weights, and use them for different purposes : transfer learning, image feature extraction, and object detection. We can load the model architecture given in the library, and then add all the weights to the respective layers. \n\nBefore using the pretrained models, lets write a few functions which will be used to make some predictions. First, load some images and preprocess them. ","metadata":{"_uuid":"42faa0d2e466c898a2dafaeb92295a95ac10583e"}},{"cell_type":"code","source":"from keras.applications.vgg16 import preprocess_input\nfrom keras.preprocessing import image\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten\nimport cv2\nimport glob as glob\nimport matplotlib.pyplot as plt \nfrom PIL import Image \nimport seaborn as sns\nimport pandas as pd \nimport numpy as np \nimport os \nfrom keras.layers.core import Dropout\nfrom keras.applications.vgg16 import VGG16\nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator","metadata":{"_uuid":"99d88f29ec0337fbcf9c778a0bceaa92dca4ee04","execution":{"iopub.status.busy":"2022-06-07T16:46:08.778667Z","iopub.execute_input":"2022-06-07T16:46:08.778979Z","iopub.status.idle":"2022-06-07T16:46:08.786757Z","shell.execute_reply.started":"2022-06-07T16:46:08.778929Z","shell.execute_reply":"2022-06-07T16:46:08.785553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Now, we can perform following steps : \n1. import VGG16 architecture from keras.applications  \n2. Add the saved weights to the architecture \n3. Use model to perform predictions ","metadata":{"_uuid":"0f3387ea97c3ad83a7a5d8ebc650e2a42f493066"}},{"cell_type":"code","source":"","metadata":{"_uuid":"b003c6f9d5fc09f142c6cff8714e165d3a542fbe","execution":{"iopub.status.busy":"2022-06-07T16:46:12.979934Z","iopub.execute_input":"2022-06-07T16:46:12.980501Z","iopub.status.idle":"2022-06-07T16:46:12.984293Z","shell.execute_reply.started":"2022-06-07T16:46:12.980206Z","shell.execute_reply":"2022-06-07T16:46:12.983392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg16 = Sequential()\nvgg16.add(VGG16(weights='imagenet',include_top=False,input_shape=(224, 224, 3)))\nvgg16.add(Flatten())\nvgg16.add(Dense(2, activation='sigmoid'))\n\nvgg16.layers[0].trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-06-07T16:46:15.764372Z","iopub.execute_input":"2022-06-07T16:46:15.764992Z","iopub.status.idle":"2022-06-07T16:46:16.559528Z","shell.execute_reply.started":"2022-06-07T16:46:15.764939Z","shell.execute_reply":"2022-06-07T16:46:16.558568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg16.compile(optimizer='Adam', \n                     loss='binary_crossentropy', \n                     metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-06-07T16:46:19.557807Z","iopub.execute_input":"2022-06-07T16:46:19.558359Z","iopub.status.idle":"2022-06-07T16:46:19.629783Z","shell.execute_reply.started":"2022-06-07T16:46:19.558283Z","shell.execute_reply":"2022-06-07T16:46:19.628068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nimage_size = 224\nepochs = 2\ndata_generator = ImageDataGenerator(preprocessing_function=preprocess_input)\n\n\ntrain_generator = data_generator.flow_from_directory(\n        '../input/modirahul/train/',\n        target_size=(image_size, image_size),\n        class_mode='categorical')\n\nvalidation_generator = data_generator.flow_from_directory(\n        '../input/modirahul/val/',\n        target_size=(image_size, image_size),\n        class_mode='categorical')\n\nhistory=vgg16.fit_generator(\n        train_generator,epochs=epochs,steps_per_epoch=3,\n        validation_data=validation_generator,validation_steps=1)","metadata":{"execution":{"iopub.status.busy":"2022-06-07T16:46:33.488273Z","iopub.execute_input":"2022-06-07T16:46:33.488704Z","iopub.status.idle":"2022-06-07T16:48:00.612595Z","shell.execute_reply.started":"2022-06-07T16:46:33.488643Z","shell.execute_reply":"2022-06-07T16:48:00.611480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc=history.history['acc']  ##getting  accuracy of each epochs\nepochs_=range(0,epochs)    \nplt.plot(epochs_,acc,label='training accuracy')\nplt.xlabel('no of epochs')\nplt.ylabel('accuracy')\n\nacc_val=history.history['val_acc']  ##getting validation accuracy of each epochs\nplt.scatter(epochs_,acc_val,label=\"validation accuracy\")\nplt.title(\"no of epochs vs accuracy\")\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-06-07T16:48:30.426572Z","iopub.execute_input":"2022-06-07T16:48:30.427856Z","iopub.status.idle":"2022-06-07T16:48:30.810271Z","shell.execute_reply.started":"2022-06-07T16:48:30.427759Z","shell.execute_reply":"2022-06-07T16:48:30.809091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc=history.history['loss']    ##getting  loss of each epochs\nepochs_=range(0,epochs)\nplt.plot(epochs_,acc,label='training loss')\nplt.xlabel('No of epochs')\nplt.ylabel('loss')\n\nacc_val=history.history['val_loss']  ## getting validation loss of each epochs\nplt.scatter(epochs_,acc_val,label=\"validation loss\")\nplt.title('no of epochs vs loss')\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-06-07T16:48:41.487421Z","iopub.execute_input":"2022-06-07T16:48:41.487826Z","iopub.status.idle":"2022-06-07T16:48:41.836237Z","shell.execute_reply.started":"2022-06-07T16:48:41.487779Z","shell.execute_reply":"2022-06-07T16:48:41.834757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_results(path):\n    i = 1\n    plt.figure(figsize=(15,10))\n    for im in os.listdir(path):\n        im = os.path.join(path,im)\n        plt.subplot(5,4,i)\n        plt.subplots_adjust(hspace=0.4)\n        image = cv2.imread(im)\n        plt.imshow(image)\n        \n        image = cv2.resize(image,(224,224))\n        image = preprocess_input(np.expand_dims(image, axis=0))\n        if (vgg16.predict_classes(image) == 0):\n            txt = \"Modi\"\n        else :\n            txt = \"Rahul\"\n        plt.title(txt)\n        \n        i = i + 1","metadata":{"execution":{"iopub.status.busy":"2022-06-07T17:02:37.136804Z","iopub.execute_input":"2022-06-07T17:02:37.137112Z","iopub.status.idle":"2022-06-07T17:02:37.144422Z","shell.execute_reply.started":"2022-06-07T17:02:37.137062Z","shell.execute_reply":"2022-06-07T17:02:37.143610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_results('../input/modirahul/val/urban/')","metadata":{"execution":{"iopub.status.busy":"2022-06-07T17:02:37.650599Z","iopub.execute_input":"2022-06-07T17:02:37.650892Z","iopub.status.idle":"2022-06-07T17:02:45.544378Z","shell.execute_reply.started":"2022-06-07T17:02:37.650846Z","shell.execute_reply":"2022-06-07T17:02:45.543285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}