{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom  tensorflow.keras import layers\nimport glob\nimport numpy as np \nimport pandas as pd \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data=pd.read_csv(\"../input/cassava-leaf-disease-classification/train.csv\")\nimage_id=[ '/kaggle/input/cassava-leaf-disease-classification/train_images/{}'.format(p)  for p in data.image_id.tolist()]\nlabel=data.label.tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(image_id)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"auto= tf.data.experimental.AUTOTUNE\n@tf.function\ndef  enhancement(image):    \n    image=tf.image.random_crop( image, [400,400,3])\n    image=tf.image.random_flip_left_right(image)\n    image=tf.image.random_flip_up_down(image)\n    image=tf.image.random_jpeg_quality(image,80,100)\n    return image\n@tf.function\ndef  parse_image(path):\n    image=tf.io.read_file(path)\n    image=tf.image.decode_jpeg(image,channels=3)\n    image=enhancement(image)\n    image=tf.image.resize(image,[400,400])\n    image=tf.cast(image,tf.float32)\n    return image/255. \n\n\n@tf.function\ndef parse_arr(imagepath,label):   \n    return  parse_image(imagepath),label\n\ndataset=tf.data.Dataset.from_tensor_slices((image_id,label))\ndataset=dataset.map(parse_arr,num_parallel_calls=auto)\n\nbatch_size=16\ntotallen=len(image_id)\nval_len=int(totallen*0.1)\ntrain_len=totallen=val_len\ntrain_dataset=dataset.skip(val_len)\nval_dataset=dataset.take(val_len)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset=train_dataset.shuffle(300).batch(batch_size).prefetch(auto)\nval_dataset=val_dataset.batch(batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weights_path = '../input/keras-pretrained-models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels_notop.h5'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conv_base=keras.applications.InceptionResNetV2 (weights=weights_path,include_top=False)\nconv_base.trainable=False\nmodel=keras.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.GlobalAveragePooling2D())\nmodel.add(layers.Dropout(0.4))\nmodel.add(layers.Dense(1024,activation='relu'))\nmodel.add(layers.Dense(512,activation='relu'))\nmodel.add(layers.Dense(100,activation='relu'))\nmodel.add(layers.Dropout(0.4))\nmodel.add(layers.Dense(5))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nmodel.summary()\nmodel.compile(\n    optimizer=keras.optimizers.Adam(learning_rate=0.0001),\n    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n    metrics=[\"acc\"]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"checkpoint_filepath = './'\nmodel_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n    filepath=checkpoint_filepath,\n    save_weights_only=True,\n    monitor='val_acc',\n    \n    save_best_only=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nhistory=model.fit(train_dataset,epochs=30,batch_size=batch_size,validation_data=val_dataset,callbacks=[model_checkpoint_callback])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights(checkpoint_filepath)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conv_base.trainable=True\nfor layer in conv_base.layers[:-3]:\n  layer.trainable=False\nmodel.compile(\n    optimizer=keras.optimizers.Adam(learning_rate=0.00005),\n    loss=keras.losses.sparse_categorical_crossentropy,\n    metrics=[\"acc\"]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nhistory=model.fit(train_dataset,epochs=20,initial_epoch=20,  batch_size=batch_size,validation_data=val_dataset,callbacks=[model_checkpoint_callback])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights(checkpoint_filepath)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    optimizer=keras.optimizers.Adam(learning_rate=0.000005),\n    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n    metrics=[\"acc\"]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit(train_dataset,epochs=60,initial_epoch=40,  batch_size=batch_size,validation_data=val_dataset,callbacks=[model_checkpoint_callback])\nmodel.load_weights(checkpoint_filepath)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_path=glob.glob('../input/cassava-leaf-disease-classification/test_images/*.jpg')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f=open('./submission.csv','a')\nf.write(\"image_id,label\\n\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"@tf.function\ndef preparation(path):\n    image=tf.io.read_file(path)\n    image=tf.image.decode_jpeg(image,channels=3)    \n    image=tf.image.resize(image,[400,400])\n    image=tf.cast(image,tf.float32)\n    return image/255. ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for path in  test_path:\n    \n    result=np.argmax(model.predict(np.expand_dims( preparation(path),0 ) ))\n    print(result)\n    filename=path.split(\"/\")[-1]\n    f.write(filename+\",\"+str(result)+\"\\n\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}