{"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":"code","source":"import numpy as np\nimport tensorflow as tf\nimport requests\nimport sys\nsys.path.append(\"../input/ai-training-challenge-1/cifar10_input.py\")\nimport cifar10_input\nsys.path.append(\"../input/ai-training-challenge-1/model.py\")\nfrom model_challenge import Model_Plain_Net\nimport pandas as pd\nimport os","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-04-02T16:53:17.714077Z","iopub.execute_input":"2022-04-02T16:53:17.714434Z","iopub.status.idle":"2022-04-02T16:53:22.513172Z","shell.execute_reply.started":"2022-04-02T16:53:17.714353Z","shell.execute_reply":"2022-04-02T16:53:22.512298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get Model","metadata":{}},{"cell_type":"markdown","source":"Define Model Parameters","metadata":{}},{"cell_type":"code","source":"input_shape = (32,32,3)\nclass_num = 10\n# Construct model\nmodel = Model_Plain_Net(tf.keras.layers.Input(shape = input_shape),class_num)\nmodel.net.summary()\n# The path for CIFAR-10 dataset\ndata_path = \"../input/ai-training-challenge-1/Dataset/\"","metadata":{"execution":{"iopub.status.busy":"2022-04-02T16:53:22.516523Z","iopub.execute_input":"2022-04-02T16:53:22.517844Z","iopub.status.idle":"2022-04-02T16:53:25.936748Z","shell.execute_reply.started":"2022-04-02T16:53:22.51779Z","shell.execute_reply":"2022-04-02T16:53:25.936003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Read dataset for training and testing","metadata":{}},{"cell_type":"code","source":"# Get object for reading CIFAR-10 test datasset\nraw_cifar = cifar10_input.CIFAR10Data(data_path)\n# Get training dataset\nx_train = raw_cifar.train_data.xs / 255.0\ny_train = raw_cifar.train_data.ys\n# Get test dataset\nx_test = raw_cifar.eval_data.xs\ny_test = raw_cifar.eval_data.ys","metadata":{"execution":{"iopub.status.busy":"2022-04-02T16:53:25.938859Z","iopub.execute_input":"2022-04-02T16:53:25.939128Z","iopub.status.idle":"2022-04-02T16:53:30.869488Z","shell.execute_reply.started":"2022-04-02T16:53:25.939091Z","shell.execute_reply":"2022-04-02T16:53:30.868716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training\n**You should modify this section to define your optimizer method and train the given model with best accuracy.**\n\n**Good luck and have fun**","metadata":{}},{"cell_type":"code","source":"batch_size = 128\nepoch_size = int(50000/batch_size)\nmax_num_training_steps = epoch_size*5\narr = np.arange(50000)","metadata":{"execution":{"iopub.status.busy":"2022-04-02T16:53:30.871215Z","iopub.execute_input":"2022-04-02T16:53:30.871505Z","iopub.status.idle":"2022-04-02T16:53:30.87782Z","shell.execute_reply.started":"2022-04-02T16:53:30.87147Z","shell.execute_reply":"2022-04-02T16:53:30.875542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_accuracy(net_out,y_input):\n    predictions = tf.argmax(input=net_out, axis=1)\n    correct_prediction = tf.equal(predictions, y_input)\n    num_correct = tf.reduce_sum(input_tensor=tf.cast(correct_prediction, tf.int64))\n    accuracy = tf.reduce_mean(input_tensor=tf.cast(correct_prediction, tf.float32))\n\n    return accuracy","metadata":{"execution":{"iopub.status.busy":"2022-04-02T16:53:30.879058Z","iopub.execute_input":"2022-04-02T16:53:30.879509Z","iopub.status.idle":"2022-04-02T16:53:30.885789Z","shell.execute_reply.started":"2022-04-02T16:53:30.879472Z","shell.execute_reply":"2022-04-02T16:53:30.885162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.9)\nloss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\nfor ii in range(max_num_training_steps):      \n        # Read batch data\n        np.random.shuffle(arr)\n        x_batch = x_train[arr[0:batch_size],:,:,:]\n        y_batch = y_train[arr[0:batch_size]]\n        # Compute the gradients for a list of variables.\n        with tf.GradientTape() as tape:\n            # Run the forward pass of the layer.\n            # The operations that the layer applies\n            # to its inputs are going to be recorded\n            # on the GradientTape.\n            logits = model.net(x_batch, training=True)  # Logits for this minibatch\n\n            # Compute the loss value for this minibatch.\n            loss_value = loss_fn(y_batch, logits)\n            \n        # Use the gradient tape to automatically retrieve\n        # the gradients of the trainable variables with respect to the loss.\n        grads = tape.gradient(loss_value, model.net.trainable_weights)\n\n        # Run one step of gradient descent by updating\n        # the value of the variables to minimize the loss.\n        optimizer.apply_gradients(zip(grads, model.net.trainable_weights))\n        \n        if ii % epoch_size == 0:\n            acc = get_accuracy(logits,y_batch)\n            print(\"Accuracy: %f, Training loss (for one batch): %f at step %d\"% (acc,float(loss_value),ii)) \n            # Save trained model\n            tf.keras.models.save_model(model.net,\"./my_trained_model.hdf5\",save_format=\"h5\")\n","metadata":{"execution":{"iopub.status.busy":"2022-04-02T16:53:30.887248Z","iopub.execute_input":"2022-04-02T16:53:30.8875Z","iopub.status.idle":"2022-04-02T16:58:32.749272Z","shell.execute_reply.started":"2022-04-02T16:53:30.887467Z","shell.execute_reply":"2022-04-02T16:58:32.748551Z"},"trusted":true},"execution_count":null,"outputs":[]}]}