{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Model Creation and Training\n\nHello everyone, \n\nThe competition has just ended, thank you everyone for sharing public notebooks that helps me to learn more and more. I would love to share my model. I hope it would help everyone to get some insights and please also help to give me feedbacks to improve this model. "},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.execute_input":"2020-09-05T13:03:43.594517Z","iopub.status.busy":"2020-09-05T13:03:43.593696Z","iopub.status.idle":"2020-09-05T13:03:50.137746Z","shell.execute_reply":"2020-09-05T13:03:50.136992Z"},"papermill":{"duration":6.557353,"end_time":"2020-09-05T13:03:50.137872","exception":false,"start_time":"2020-09-05T13:03:43.580519","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport pathlib\nimport PIL\nimport PIL.Image\nimport librosa\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras import layers","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-09-05T13:03:50.160732Z","iopub.status.busy":"2020-09-05T13:03:50.159695Z","iopub.status.idle":"2020-09-05T13:03:50.672087Z","shell.execute_reply":"2020-09-05T13:03:50.671421Z"},"papermill":{"duration":0.526142,"end_time":"2020-09-05T13:03:50.672223","exception":false,"start_time":"2020-09-05T13:03:50.146081","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"data_dir = \"/kaggle/input/cornell-bird-sounds-preprocessing\"\ndata_path = pathlib.Path(data_dir)\n\n## total images\ntotal_images = len(list(data_path.glob(\"*/*.png\")))","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-09-05T13:03:50.696923Z","iopub.status.busy":"2020-09-05T13:03:50.696108Z","iopub.status.idle":"2020-09-05T13:03:55.605084Z","shell.execute_reply":"2020-09-05T13:03:55.604454Z"},"papermill":{"duration":4.925101,"end_time":"2020-09-05T13:03:55.605217","exception":false,"start_time":"2020-09-05T13:03:50.680116","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"## loading images for model\n\nBATCH_SIZE = 32\nIMG_HEIGHT = 128\nIMG_WIDTH = 128\nSEED = np.random.randint(100)\n\ntrain_ds = tf.keras.preprocessing.image_dataset_from_directory(\n  data_dir,\n  validation_split=0.1,\n  subset=\"training\",\n  seed=SEED,\n  image_size=(IMG_HEIGHT, IMG_WIDTH),\n  batch_size=BATCH_SIZE)\n\nval_ds = tf.keras.preprocessing.image_dataset_from_directory(\n  data_dir,\n  validation_split=0.1,\n  subset=\"validation\",\n  seed=SEED,\n  image_size=(IMG_HEIGHT, IMG_WIDTH),\n  batch_size=BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-09-05T13:03:55.630294Z","iopub.status.busy":"2020-09-05T13:03:55.629552Z","iopub.status.idle":"2020-09-05T13:03:55.636695Z","shell.execute_reply":"2020-09-05T13:03:55.635923Z"},"papermill":{"duration":0.022058,"end_time":"2020-09-05T13:03:55.63682","exception":false,"start_time":"2020-09-05T13:03:55.614762","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"cache_train_ds = train_ds.cache().prefetch(tf.data.experimental.AUTOTUNE)\ncache_val_ds = val_ds.cache().prefetch(tf.data.experimental.AUTOTUNE)","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-09-05T13:03:55.66754Z","iopub.status.busy":"2020-09-05T13:03:55.666725Z","iopub.status.idle":"2020-09-05T13:03:55.717853Z","shell.execute_reply":"2020-09-05T13:03:55.717188Z"},"papermill":{"duration":0.071575,"end_time":"2020-09-05T13:03:55.718012","exception":false,"start_time":"2020-09-05T13:03:55.646437","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"num_classes = 264\n\nmodel = tf.keras.Sequential([\n  layers.experimental.preprocessing.Rescaling(1./255),\n  layers.Conv2D(32, 3, activation='relu'),\n  layers.MaxPooling2D(),\n  layers.Dropout(0.2),\n  layers.Conv2D(32, 3, activation='relu'),\n  layers.MaxPooling2D(),\n  layers.Dropout(0.2),\n  layers.Conv2D(32, 3, activation='relu'),\n  layers.MaxPooling2D(),\n  layers.Flatten(),\n  layers.Dense(128, activation='relu'),\n  layers.Dense(num_classes)\n])\n\nmodel.compile(\n  optimizer='adam',\n  loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),\n  metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2020-09-05T13:03:55.743672Z","iopub.status.busy":"2020-09-05T13:03:55.742926Z","iopub.status.idle":"2020-09-05T15:45:13.610201Z","shell.execute_reply":"2020-09-05T15:45:13.609355Z"},"papermill":{"duration":9677.882495,"end_time":"2020-09-05T15:45:13.610356","exception":false,"start_time":"2020-09-05T13:03:55.727861","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"epochs = 50\n\nhistory = model.fit(\n  cache_train_ds,\n  validation_data=val_ds,\n  shuffle=True,\n  epochs=epochs\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"./model_backup.h5\")\nnp.save(\"class_indices.npy\", np.array(train_ds.class_names))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for x, y in cache_val_ds.take(1):\n    predicts = model.predict(x)\n    for index, y_real in enumerate(y):\n        y_pred = predicts[index]\n        score = tf.nn.softmax(y_pred)\n        print(f'Class: {train_ds.class_names[y_real]} -  Predict as {train_ds.class_names[np.argmax(y_pred)]} with score {np.max(score) * 100}%')","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}