{"cells":[{"metadata":{},"cell_type":"markdown","source":"### This kernel shows how to easy use TPU (tensor processing unit) with tf.keras"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nprint(\"Tensorflow version \" + tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet\n\nimport efficientnet.tfkeras as efn","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Enable TPU"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Detect hardware, 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() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Load train data"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train['label'].values.astype('float32')\nY_train = tf.keras.utils.to_categorical(Y_train, 10)\nY_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train.drop(labels=['label'], axis=1)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Normalize data"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.astype('float32')\nX_train = X_train / 255","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Reshape data"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.values.reshape(42000,28,28,1)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Show some image"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X_train[1][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.pad(X_train, ((0,0), (2,2), (2,2), (0,0)), mode='constant')\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.squeeze(X_train, axis=-1)\nX_train = stacked_img = np.stack((X_train,)*3, axis=-1)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X_train[1][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model():\n    enet = efn.EfficientNetB3(\n    input_shape=(32, 32, 3),\n    weights='imagenet',\n    include_top=False,\n    )        \n    \n    model = tf.keras.Sequential([\n        enet,\n        tf.keras.layers.Flatten(),\n        tf.keras.layers.Dense(1024, activation=\"relu\"),\n        tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(10, activation='softmax')\n    ])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Train"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n  model = create_model()\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\nmodel.fit(\n    X_train, Y_train,\n    epochs=10,\n    batch_size = 210,\n    shuffle=True,\n    verbose = 1\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Load test data"},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = test.astype('float32')\ntest = test / 255\ntest = test.values.reshape(len(test),28,28,1)\ntest = np.pad(test, ((0,0), (2,2), (2,2), (0,0)), mode='constant')\ntest = np.squeeze(test, axis=-1)\ntest = stacked_img = np.stack((test,)*3, axis=-1)\ntest.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Prediction"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\ntest_predictions = model.predict(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# select the index with the maximum probability\n\nresults = np.argmax(test_predictions,axis = 1)\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Submit"},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\nsubmission.to_csv(\"submission.csv\",index=False)\n\nsubmission.head()","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":1}