{"cells":[{"metadata":{},"cell_type":"markdown","source":"### This notebook is taken as a reference from [here](https://www.kaggle.com/ryanholbrook/create-your-first-submission)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -U -t /kaggle/working/ git+https://github.com/Kaggle/learntools.git\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.deep_learning.ex_tpu import *\nstep_1.check()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Loading helper functions","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"## let's load the data from the utility script\nfrom petal_helper import *\n\nimport tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Distribution strategy","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Lets learn the distribution startegy for the TPU's. \n# Each TPU has 8 cores (each core is like a GPU in itself)\n# We need to tell tensorflow on how to make use of this TPU by a distribution strategy\n\n# Detect TPU, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n    \n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Loading the dataset ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"## Loading the data from the competition\n\n# when using TPUs datasets are often serialized into TFRecords.\n# This is a convenient format to feed to e ach of the TPU cores\n# petal_helper utility script will load the TFRecords and create a data pipeline \n# to use with our model \n\n\nds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()\n\nprint(\"Training : \", ds_train)\nprint(\"Validation : \", ds_valid)\nprint(\"Testing : \", ds_test)\n\nprint(\"type : \", type(ds_test))\n# These are tf.data.Dataset objects. You can think about the dataset in Tensorflow as a stream of data records\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Defining the model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# We'll use Transfer learning where we use an already built pre-trained model\n# and we can retrain a part of the models neural network to get a head-start on our new dataset\n\n# The distribution strategy we created earlier contains a context manager, strategy.scope. \n# This context manager tells TensorFlow how to divide the work of training among the eight TPU cores. \n# When using TensorFlow with a TPU, it's important to define your model in a strategy.scope() context.\n\n\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.VGG16(\n    weights = \"imagenet\",\n    input_shape = [*IMAGE_SIZE, 3],\n    include_top = False)\n    \n    \n    pretrained_model.trainable = False\n    \n    model = tf.keras.Sequential([\n    pretrained_model,\n    tf.keras.layers.GlobalAveragePooling2D(),\n    tf.keras.layers.Dense(len(CLASSES), activation='softmax')])\n    \n    model.compile(\n    optimizer = 'adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics = ['sparse_categorical_accuracy'])\n    \n\nmodel.summary()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Training the model ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define the batch size. This will be 16 with TPU off and 128 (=16*8) with TPU on\nBATCH_SIZE = 16*strategy.num_replicas_in_sync\n\n# Defining the epochs\nEPOCHS = 10\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    ds_train,\n    validation_data = ds_valid,\n    epochs = EPOCHS,\n    steps_per_epoch = STEPS_PER_EPOCH\n    \n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Predictions","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Let us generate submission.csv file.\n\nprint(\"generating submission.csv file \")\n\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds =  test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n\n# Write submission.csv file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Look at the first few predictions\n!head submission.csv\n","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}