{"cells":[{"metadata":{"id":"Xrdtb2vV_wMa","outputId":"a410ed90-d381-40d3-841c-ea1922ea1b0c","trusted":true},"cell_type":"code","source":"! pip install -U tf-nightly","execution_count":null,"outputs":[]},{"metadata":{"id":"5ZrdgU5OT8ul","trusted":true},"cell_type":"code","source":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport matplotlib.pylab as plt\nimport tensorflow as tf\n# tf.enable_eager_execution()\nimport tensorflow_hub as hub\nimport tensorflow_datasets as tfds\nfrom tensorflow.keras import layers\nimport logging\nlogger = tf.get_logger()\nlogger.setLevel(logging.ERROR)","execution_count":null,"outputs":[]},{"metadata":{"id":"GClcFl24UZ3H","trusted":true},"cell_type":"code","source":"CLASSIFIER_URL =\"https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/2\"\nimg_res = 224\n\nmodel = tf.keras.Sequential([\n    hub.KerasLayer(CLASSIFIER_URL,input_shape=(img_res,img_res,3))\n])","execution_count":null,"outputs":[]},{"metadata":{"id":"i3Pqp0GUWF2C","trusted":true},"cell_type":"code","source":"import numpy as np\nimport PIL.Image as Image","execution_count":null,"outputs":[]},{"metadata":{"id":"-UYWuwSeqgNl","trusted":true},"cell_type":"code","source":"labels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')\nimagenet_labels = np.array(open(labels_path).read().splitlines())\n","execution_count":null,"outputs":[]},{"metadata":{"id":"N0e9rnuosqO_","trusted":true},"cell_type":"code","source":"# splits = tfds.Split.ALL.subsplit(weighted=(80,20))\nsplits=['train[:80%]', 'train[80%:100%]']\nsplits,info = tfds.load('cats_vs_dogs',with_info=True,split=splits,as_supervised=True)\ntrain_data,val_data = splits\nnum_data = info.splits['train'].num_examples\nnum_classes = info.features['label'].num_classes\n","execution_count":null,"outputs":[]},{"metadata":{"id":"1j7JGbmruKNI","trusted":true},"cell_type":"code","source":"def format_img(img,label):\n  img = tf.image.resize(img,(img_res,img_res))/255.0\n  return img,label\n\nbatch_size = 32\ntrain_batches = train_data.shuffle(num_data//4).map(format_img).batch(batch_size).prefetch(1)\nval_batches = val_data.map(format_img).batch(batch_size).prefetch(1)","execution_count":null,"outputs":[]},{"metadata":{"id":"JFHspynDwBgG","trusted":true},"cell_type":"code","source":"img_batch,label_batch = next(iter(train_batches.take(1)))\nimg_batch = img_batch.numpy()\nlabel_batch = label_batch.numpy()\nresult_batch = model.predict(img_batch)\npredicted_class_name = imagenet_labels[np.argmax(result_batch,axis=-1)]","execution_count":null,"outputs":[]},{"metadata":{"id":"acTE8pKZxZqP","outputId":"196eedd3-4b10-4b18-88d5-1d644c57c503","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,15))\nfor n in range(30):\n  plt.subplot(6,5,n+1)\n  plt.imshow(img_batch[n])\n  plt.axis('off')\n  plt.title(predicted_class_name[n])","execution_count":null,"outputs":[]},{"metadata":{"id":"ZzcJ-Vuzxysp","trusted":true},"cell_type":"code","source":"URL = \"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/2\"\nfeatures = hub.KerasLayer(URL,input_shape=(img_res,img_res,3))","execution_count":null,"outputs":[]},{"metadata":{"id":"cOH4dNUw0yWb","trusted":true},"cell_type":"code","source":"feature_batch = features(img_batch)","execution_count":null,"outputs":[]},{"metadata":{"id":"ksQGwf0V1D61","trusted":true},"cell_type":"code","source":"features.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"id":"-roQ1GRN1oDm","outputId":"6875b61c-8512-4a78-8230-8f49dc718735","trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([\n    \n    features,\n    tf.keras.layers.Dense(2,activation='softmax')\n])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"id":"yZheQrP827NP","outputId":"48bb25c4-a6b1-44f4-b588-f9909f153df3","trusted":true},"cell_type":"code","source":"model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\n\nepochs = 3\ntrained = model.fit(train_batches,epochs=epochs,\n                   validation_data=val_batches)","execution_count":null,"outputs":[]},{"metadata":{"id":"ohna_3u64fMJ","outputId":"1fb3a152-7ec1-40a9-9fb0-bbf4b6edf8e5","trusted":true},"cell_type":"code","source":"#print (trained.history.keys())\ntrain_acc = trained.history['accuracy']\nval_acc = trained.history['val_accuracy']\n\ntrain_loss = trained.history['loss']\nval_loss = trained.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(15,8))\nplt.subplot(1,2,1)\nplt.plot(epochs_range,train_acc,label='train accuracy')\nplt.plot(epochs_range,val_acc,label='validation accuracy')\nplt.legend(loc='lower right')\nplt.title('Accuracy')\n\nplt.subplot(1,2,2)\nplt.plot(epochs_range,train_loss,label='train loss')\nplt.plot(epochs_range,val_loss,label='validation loss')\nplt.legend(loc='upper right')\nplt.title('Loss')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"id":"gp5ScNw26jiK","trusted":true},"cell_type":"code","source":"class_names = np.array(info.features['label'].names)\n\npredicted_class = model.predict(img_batch)\npredicted_class = tf.squeeze(predicted_class).numpy()\n\npredicted_class_ids = np.argmax(predicted_class,axis=-1)\npredicted_class_name = class_names[np.argmax(predicted_class,axis=-1)]","execution_count":null,"outputs":[]},{"metadata":{"id":"hQCw6T3c9Hi2","outputId":"4102f0af-bb0e-4587-d102-05962a401aa1","trusted":true},"cell_type":"code","source":"print(class_names)\nprint(predicted_class_name)\nprint(predicted_class_ids)","execution_count":null,"outputs":[]},{"metadata":{"id":"Lxgj5UAI-LEA","outputId":"71607b9e-6027-491f-f3a9-c35110aa5540","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12,12))\nfor n in range(30):\n  plt.subplot(6,5,n+1)\n  plt.imshow(img_batch[n])\n  color = 'blue' if predicted_class_ids[n] == label_batch[n] else 'red'\n  plt.axis('off')\n  plt.title(predicted_class_name[n].title(),color=color)","execution_count":null,"outputs":[]},{"metadata":{"id":"ZkKvECuYvByh","trusted":true},"cell_type":"code","source":"import re\n\nwith open('submit.txt', 'w') as dst:\n    dst.write('id,label\\n')\n    for label, classifier in zip(imagenet_labels, predicted_class_name):\n        dst.write('%s,%s\\n' % (label, classifier))","execution_count":null,"outputs":[]},{"metadata":{"id":"mUwc3zm2vByk","trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"id":"iczBEtKVvByn","trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"id":"VGJe9kyXvByq","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}