{"cells":[{"metadata":{},"cell_type":"markdown","source":"### This kernel shows how to easy use TPU (tensor processing unit)"},{"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":{},"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","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":{},"cell_type":"markdown","source":"### Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model():        \n  model = tf.keras.models.Sequential()\n  model.add(tf.keras.layers.Conv2D(filters = 32, kernel_size = (3,3), input_shape = (28,28,1)))\n  model.add(tf.keras.layers.Flatten())\n  model.add(tf.keras.layers.Dense(10, activation=\"softmax\"))\n  model.compile(loss=\"sparse_categorical_crossentropy\", optimizer=\"Adam\", metrics=['accuracy'])   \n    \n  return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Train"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\nwith strategy.scope():\n  model = create_model()\n\nmodel.fit(\n    X_train, Y_train,\n    epochs=10,\n    steps_per_epoch=40,\n    verbose = 2\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\")","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.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":{"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}