{"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":"# # This Python 3 environment comes with many helpful analytics libraries installed\n# # It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# # For example, here's several helpful packages to load\n\n# import numpy as np # linear algebra\n# import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# # Input data files are available in the read-only \"../input/\" directory\n# # For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# # You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# # You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # This Python 3 environment comes with many helpful analytics libraries installed\n# # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# # For example, here's several helpful packages to load in \n\n# import numpy as np # linear algebra\n# import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# # Input data files are available in the \"../input/\" directory.\n# # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\n# import os\n# print(os.listdir(\"../input\"))\n\n# # Any results you write to the current directory are saved as output.","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from PIL import Image\n# import numpy as np\n# import pandas as pd\n# import matplotlib.pyplot as plt\n# import cv2\n# from sklearn.model_selection import train_test_split, StratifiedShuffleSplit\n# import tensorflow as tf\n# from tensorflow.python.framework import ops\n# import math\n# import glob\n# # from skimage.transform import resize   # for resizing images","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ext = ['jpg', 'jpeg']    # Add image formats here\n# data = []\n# labels = []\n\n# files = []\n# imdir = '../input/train/train/cbb/'\n# [files.extend(glob.glob(imdir + '*.' + e)) for e in ext]\n# data.extend([cv2.imread(file) for file in files])\n# labels.extend([\"cbb\" for file in files])\n\n# files = []\n# imdir = '../input/train/train/cbsd/'\n# [files.extend(glob.glob(imdir + '*.' + e)) for e in ext]\n# data = np.concatenate([data, [cv2.imread(file) for file in files]])\n# labels.extend([\"cbsd\" for file in files])\n\n# files = []\n# imdir = '../input/train/train/cgm/'\n# [files.extend(glob.glob(imdir + '*.' + e)) for e in ext]\n# data = np.concatenate([data, [cv2.imread(file) for file in files]])\n# labels.extend([\"cgm\" for file in files])\n\n# files = []\n# imdir = '../input/train/train/cmd/'\n# [files.extend(glob.glob(imdir + '*.' + e)) for e in ext]\n# data = np.concatenate([data, [cv2.imread(file) for file in files]])\n# labels.extend([\"cmd\" for file in files])\n\n# files = []\n# imdir = '../input/train/train/healthy/'\n# [files.extend(glob.glob(imdir + '*.' + e)) for e in ext]\n# data = np.concatenate([data, [cv2.imread(file) for file in files]])\n# labels.extend([\"healthy\" for file in files])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# size = (300, 300)\n# data = np.array([cv2.resize(d, size, interpolation = cv2.INTER_AREA) for d in data])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data = np.concatenate([data, [np.fliplr(data[i]) for i in range(len(data))]])\n# labels.extend([labels[i] for i in range(len(labels))])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# labels = np.array(labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lr = [np.fliplr(data[i]) for i in range(len(data))]\n# labels_lr = [labels[i] for i in range(len(labels))]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data = np.concatenate([data, lr])\n# labels = np.concatenate([labels, labels_lr])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # data = np.array(data)\n# labels = np.array(labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# labels = pd.get_dummies(labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# X_train = data\n# Y_train = labels\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# #using only training data\n# X_train, X_test, Y_train, Y_test = train_test_split(data, labels, test_size=.05, random_state=42, stratify=labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# #using real test data\n# testData = []\n# files = []\n# imdir = '../input/test/test/0/'\n# [files.extend(glob.glob(imdir + '*.' + e)) for e in ext]\n# testData.extend([cv2.imread(file) for file in files])\n\n# size = (300, 300)\n# testData = [cv2.resize(d, size, interpolation = cv2.INTER_AREA) for d in testData]\n\n# X_train = data\n# Y_train = labels\n# X_test = np.array(testData)\n# testLabels = files","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import numpy as np\n# from keras import layers\n# from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D\n# from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D\n# from keras.models import Model\n# from keras.preprocessing import image\n# from keras.utils import layer_utils\n# from keras.utils.data_utils import get_file\n# from keras.applications.imagenet_utils import preprocess_input\n# from keras.utils.vis_utils import model_to_dot\n# from keras.utils import plot_model\n\n# import keras.backend as K\n# K.set_image_data_format('channels_last')\n# import matplotlib.pyplot as plt\n# from matplotlib.pyplot import imshow\n\n# %matplotlib inline","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# input_shape = ((300, 300, 3))\n# X_input = Input(input_shape)\n    \n# # Zero-Padding: pads the border of X_input with zeroes\n# X = ZeroPadding2D((3, 3))(X_input)\n\n# # CONV -> BN -> RELU Block applied to X\n# X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)\n# X = BatchNormalization(axis = 3, name = 'bn0')(X)\n# X = Activation('relu')(X)\n\n# # MAXPOOL\n# X = AveragePooling2D((2, 2), name='avg_pool0')(X)\n\n# # CONV -> BN -> RELU Block applied to X\n# X = Conv2D(32, (5, 5), strides = (1, 1), name = 'conv1')(X)\n# X = BatchNormalization(axis = 3, name = 'bn1')(X)\n# X = Activation('relu')(X)\n\n# # MAXPOOL\n# X = AveragePooling2D((2, 2), name='avg_pool1')(X)\n\n# # CONV -> BN -> RELU Block applied to X\n# X = Conv2D(32, (3, 3), strides = (1, 1), name = 'conv2')(X)\n# X = BatchNormalization(axis = 3, name = 'bn2')(X)\n# X = Activation('relu')(X)\n\n# # MAXPOOL\n# X = AveragePooling2D((2, 2), name='avg_pool2')(X)\n\n# # FLATTEN X (means convert it to a vector) + FULLYCONNECTED\n# X = Flatten()(X)\n# X = Dense(1024, activation=\"relu\")(X)\n# X = Dropout(0.5)(X)\n# X = Dense(5, activation='softmax', name='fc')(X)\n\n# # Create model. This creates your Keras model instance, you'll use this instance to train/test the model.\n# model = Model(inputs = X_input, outputs = X, name='satellite')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.compile(optimizer=\"sgd\", loss=\"mean_squared_error\", metrics=[\"accuracy\"])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.fit(x=X_train, y=Y_train, epochs=50, batch_size=32)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# preds = model.evaluate(x=X_test, y=Y_test)\n# print()\n# print (\"Loss = \" + str(preds[0]))\n# print (\"Test Accuracy = \" + str(preds[1]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pred = model.predict(x=X_test)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ...............................STARYT here..................................................................................................","metadata":{}},{"cell_type":"code","source":"# import numpy as np\n# import tensorflow as tf\n# from tensorflow import keras\n# from tensorflow.keras.layers import Dense, Activation,GlobalAveragePooling2D\n# from tensorflow.keras.optimizers import Adam\n# from tensorflow.keras.metrics import categorical_crossentropy\n# from tensorflow.keras.preprocessing.image import ImageDataGenerator\n# from tensorflow.keras.preprocessing import image\n# from tensorflow.keras.models import Model\n# from tensorflow.keras.applications import imagenet_utils\n# import matplotlib.pyplot as plt\n# from keras.utils import to_categorical","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# #import tensorflow as tf\n# #from tensorflow import keras\n\n\n# import os\n# import gc\n# import re\n\n# import cv2\n# import math\n# import numpy as np\n# import scipy as sp\n# import pandas as pd\n\n# import tensorflow as tf\n# from IPython.display import SVG\n# #import efficientnet.tfkeras as efn\n# from keras.utils import plot_model\n# import tensorflow.keras.layers as L\n# from keras.utils import model_to_dot\n# import tensorflow.keras.backend as K\n# from tensorflow.keras.models import Model\n# from kaggle_datasets import KaggleDatasets\n# from tensorflow.keras.applications import DenseNet121\n# import seaborn as sns\n# from tqdm import tqdm\n# import matplotlib.cm as cm\n# from sklearn import metrics\n# import matplotlib.pyplot as plt\n# from sklearn.utils import shuffle\n# from sklearn.model_selection import train_test_split\n\n# tqdm.pandas()\n# import plotly.express as px\n# import plotly.graph_objects as go\n# import plotly.figure_factory as ff\n# from plotly.subplots import make_subplots\n\n# np.random.seed(0)\n# tf.random.set_seed(0)\n\n# import warnings\n# warnings.filterwarnings(\"ignore\")\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import os\n# from os import listdir\n# import cv2\n# def load_data(dir_list, image_size):\n#     X=[]\n#     image_width,image_height = image_size\n#     for filename in listdir(dir_list):\n#         #print(\"filename is \"+filename)\n#         image=cv2.imread(dir_list+'/'+filename)\n#         image=cv2.resize(image,dsize=(image_width, image_height), interpolation=cv2.INTER_CUBIC)\n            \n#         image=image/255\n#         X.append(image)\n    \n#     X=np.array(X)\n    \n#    # X=shuffle(X)\n#     print(\"no of examples: \"+str(len(X)))\n#     print(\"shape of X: \"+str(X.shape))\n#     return X","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# EPOCHS = 25\n# SAMPLE_LEN = 100\n# IMAGE_PATH = \"../input/plant-pathology-2021-fgvc8/train_images/\"\n# # TEST_PATH = \"../input/plant-pathology-2021-fgvc8/test.csv\"\n# TRAIN_PATH = \"../input/plant-pathology-2021-fgvc8/train.csv\"\n# SUB_PATH = \"../input/plant-pathology-2021-fgvc8/sample_submission.csv\"\n\n# sub = pd.read_csv(SUB_PATH)\n# # test_data = pd.read_csv(TEST_PATH)\n# train_data = pd.read_csv(TRAIN_PATH)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# classes = {}\n\n# for index, row in train_data.iterrows():\n#     curLabels = row['labels'].split(' ')\n#     if len(curLabels) > 1:\n#         continue\n#     for i in curLabels:\n#         classes[i] = classes.get(i, 0) + 1\n# print(classes)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# allLabels = train_data['labels'].unique()\n# uniqueLabels = []\n\n# for i in allLabels:\n#     curLabels = i.split(' ')\n#     for j in curLabels:\n#         if j not in uniqueLabels:\n#             uniqueLabels.append(j)\n\n# for i in uniqueLabels:\n#     train_data[i] = [0] * train_data.shape[0]\n\n    \n# for index, row in train_data.iterrows():\n#     curLabels = row['labels'].split(' ')\n#     for i in uniqueLabels:\n#         if i in curLabels:\n#             train_data.loc[index, i] = 1\n\n# train_data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def load_image(image):\n#     file_path = image\n#     image = cv2.imread(IMAGE_PATH + file_path)\n#     return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n# train_images = train_data[\"image\"][:SAMPLE_LEN].progress_apply(load_image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fig = px.imshow(cv2.resize(train_images[0], (205, 136)))\n# fig.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# AUTO = tf.data.experimental.AUTOTUNE\n# tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n\n# tf.config.experimental_connect_to_cluster(tpu)\n# tf.tpu.experimental.initialize_tpu_system(tpu)\n# strategy = tf.distribute.experimental.TPUStrategy(tpu)\n\n# BATCH_SIZE = 16 * strategy.num_replicas_in_sync\n# GCS_DS_PATH = KaggleDatasets().get_gcs_path()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# MIXED_PRECISION = False\n# XLA_ACCELERATE = False\n\n# if MIXED_PRECISION:\n#     from tensorflow.keras.mixed_precision import experimental as mixed_precision\n#     if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')\n#     else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')\n#     mixed_precision.set_policy(policy)\n#     print('Mixed precision enabled')\n\n# if XLA_ACCELERATE:\n#     tf.config.optimizer.set_jit(True)\n#     print('Accelerated Linear Algebra enabled')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def format_path(st):\n#     return GCS_DS_PATH + '/train_images/' + st\n\n# # test_paths = test_data.image_id.apply(format_path).values\n# train_paths = train_data.image.apply(format_path).values\n\n# train_labels = np.float32(train_data.loc[:, 'healthy':'powdery_mildew'].values)\n# train_paths, valid_paths, train_labels, valid_labels =\\\n# train_test_split(train_paths, train_labels, test_size=0.001, random_state=2021)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# IMAGE_SIZE = [224, 224]\n\n# def decode_image(filename, label=None, image_size=(224, 224)):\n#     bits = tf.io.read_file(filename)\n#     image = tf.image.decode_jpeg(bits, channels=3)\n#     image = tf.cast(image, tf.float32) / 255.0\n#     image = tf.image.resize(image, image_size)\n    \n#     if label is None:\n#         return image\n#     else:\n#         return image, label\n\n# def data_augment(image, label=None):\n#     image = tf.image.random_flip_left_right(image)\n#     image = tf.image.random_flip_up_down(image)\n    \n#     if label is None:\n#         return image\n#     else:\n#         return image, label","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train_dataset = (\n#     tf.data.Dataset\n#     .from_tensor_slices((train_paths, train_labels))\n#     .map(decode_image, num_parallel_calls=AUTO)\n#     .map(data_augment, num_parallel_calls=AUTO)\n#     .repeat()\n#     #.shuffle(2048)\n#     .batch(BATCH_SIZE)\n#     .prefetch(AUTO)\n# )\n\n# valid_dataset = (\n#     tf.data.Dataset\n#     .from_tensor_slices((valid_paths, valid_labels))\n#     .map(decode_image, num_parallel_calls=AUTO)\n#     .batch(BATCH_SIZE)\n#     .cache()\n#     .prefetch(AUTO)\n# )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print (train_dataset)\n# print (valid_dataset)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def build_lrfn(lr_start=0.00001, lr_max=0.00005, \n#                lr_min=0.00001, lr_rampup_epochs=5, \n#                lr_sustain_epochs=0, lr_exp_decay=.8):\n#     lr_max = lr_max * strategy.num_replicas_in_sync\n\n#     def lrfn(epoch):\n#         if epoch < lr_rampup_epochs:\n#             lr = (lr_max - lr_start) / lr_rampup_epochs * epoch + lr_start\n#         elif epoch < lr_rampup_epochs + lr_sustain_epochs:\n#             lr = lr_max\n#         else:\n#             lr = (lr_max - lr_min) *\\\n#                  lr_exp_decay**(epoch - lr_rampup_epochs\\\n#                                 - lr_sustain_epochs) + lr_min\n#         return lr\n#     return lrfn","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lrfn = build_lrfn()\n# STEPS_PER_EPOCH = train_labels.shape[0] // BATCH_SIZE\n# lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"/.....","metadata":{}},{"cell_type":"code","source":"#path='../input/plant-pathology-2021-fgvc8/train_images/'\n#train_x=load_data(path,(300,300))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# data_csv = pd.read_csv('../input/plant-pathology-2021-fgvc8/train.csv',dtype=dtypes)\n# plt.imshow(path+data_csv['image'][0])\n# print(data_csv)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plt.imshow(train_x[0])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # data_csv.head()\n# # y=data_csv['labels']\n# y_one_hot=to_categorical(y)\n# print(y.head())\n# preprocess_train_x=tf.keras.applications.mobilenet_v3.preprocess_input(\n#     train_x, data_format=None\n# )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":".../","metadata":{}},{"cell_type":"code","source":"# # MobileNet\n# # with strategy.scope():\n# #     base_model=tf.keras.applications.mobilenet.MobileNet(input_shape=(512,512,3),weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.\n\n# #     x=base_model.output\n# #     x=GlobalAveragePooling2D()(x)\n# #     x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.\n# #     x=Dense(1024,activation='relu')(x) #dense layer 2\n# #     x=Dense(512,activation='relu')(x) #dense layer 3\n# #     preds=Dense(train_labels.shape[1],activation='softmax')(x) #final layer with softmax activation\n# #     model=Model(inputs=base_model.input,outputs=preds)\n\n# #     model.compile(optimizer = 'adam', loss = 'categorical_crossentropy',\n# #                            metrics = ['accuracy','mae'])\n# #     model.summary()\n\n# # InceptionV3\n# with strategy.scope():\n#     from tensorflow.keras.applications.inception_v3 import InceptionV3\n#     base_model = InceptionV3(input_shape = (224, 224, 3), include_top = False, weights = 'imagenet')\n#     from tensorflow.keras.optimizers import RMSprop, Adam\n\n#     x=base_model.output\n#     x=GlobalAveragePooling2D()(x)\n# #     x = tf.keras.layers.Dense(1024, activation='relu')(x)\n# #     x = tf.keras.layers.Dropout(0.2)(x)\n#     preds=Dense(train_labels.shape[1],activation='sigmoid')(x)\n#     model=Model(inputs=base_model.input,outputs=preds)\n\n#     model.compile(optimizer = Adam(lr=0.0001), loss = 'binary_crossentropy', metrics = ['accuracy','mae'])\n    \n# #     x=base_model.output\n# #     x=GlobalAveragePooling2D()(x)\n# #     x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.\n# #     x=Dense(1024,activation='relu')(x) #dense layer 2\n# #     x=Dense(512,activation='relu')(x) #dense layer 3\n# #     preds=Dense(train_labels.shape[1],activation='softmax')(x) #final layer with softmax activation\n# #     model=Model(inputs=base_model.input,outputs=preds)\n\n# #     model.compile(optimizer = 'adam', loss = 'categorical_crossentropy',\n# #                            metrics = ['accuracy','mae'])\n#     model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# history = model.fit(train_dataset,\n#                     epochs=EPOCHS,\n#                     callbacks=[lr_schedule],\n#                     steps_per_epoch=STEPS_PER_EPOCH,\n#                     validation_data=valid_dataset)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.save('./model_inceptionv3.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test_path = \"../input/plant-pathology-2021-fgvc8/test_images/\"\n\n# images = [\"85f8cb619c66b863.jpg\", \"ad8770db05586b59.jpg\", \"c7b03e718489f3ca.jpg\"]\n# test_data = []\n# for img in images:\n#     test_data.append(decode_image(test_path + img))\n# test_data = np.array(test_data)\n# while (1):\n#     print(\"Hello World\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TEST_DATA_PATH = '../input/plant-pathology-2021-fgvc8/test_images/'\nfrom keras.models import load_model\n\nModel = load_model('./model_inceptionv3.h5')\n\ndef process(img):\n    return cv2.resize(img/255.0, (224, 224)).reshape(-1, 224, 224, 3)\n\ndef load_image(image):\n    file_path = image\n    image = cv2.imread(TEST_DATA_PATH + file_path)\n#     print(image)\n    return process(image)\n\n# def load_image(filename):\n#     bits = tf.io.read_file(filename)\n#     image = tf.image.decode_jpeg(bits, channels=3)\n# #     image = tf.cast(image, tf.float32) / 255.0\n#     image /= 255.0\n#     image = tf.image.resize(image, (512,512))\n#     return tf.reshape(image, [-1, 512, 512, 3])\n\n\nlabels = ['healthy', 'scab', 'frog_eye_leaf_spot', 'complex', 'rust', 'powdery_mildew']\n# print(sub.head())\n\nImages = []\nLabels = []\n\nTHRESHOLD = 0.5 \n\ni = 0\nfor img in os.listdir(TEST_DATA_PATH):\n    Images.append(img)\n    img = load_image(img)\n    predictions = Model.predict(img)\n#     print(predictions)\n    \n    preds = []\n    curPred = []\n    index = 0\n    for pred in predictions[0]:\n        if pred >= THRESHOLD:\n            curPred.append(labels[index])\n        preds.append((index, pred))\n        index += 1\n    \n    preds.sort(key = lambda x: x[1], reverse=True)\n    print(preds)\n    \n    if preds[0][1] < THRESHOLD:\n        curPred = []\n        curPred.append(labels[preds[0][0]])\n    i += 1\n    \n    Labels.append(' '.join(curPred))\n\n# # check for train images\n# img = load_image('../input/plant-pathology-2021-fgvc8/train_images/800cbf0ff87721f8.jpg')\n# predictions = model.predict(img)\n# Images.append('800edef467d27c15.jpg')\n# print(predictions)\n\n# preds = []\n# curPred = []\n# index = 0\n# for pred in predictions[0]:\n#     if pred >= THRESHOLD:\n#         curPred.append(labels[index])\n#     preds.append((index, pred))\n#     index += 1\n\n# preds.sort(key = lambda x: x[1], reverse=True)\n# print(preds)\n\n# if preds[0][1] < THRESHOLD:\n#     curPred = []\n#     curPred.append(labels[preds[0][0]])\n# i += 1\n\n# Labels.append(' '.join(curPred))\n\ndict = {'image': Images, 'labels': Labels}\ndf = pd.DataFrame(dict)\ndf.to_csv('submission.csv', index=False)    \n\nsub = pd.read_csv('submission.csv')\nprint(sub.head())","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# img = cv2.imread(\"../input/plant-pathology-2021-fgvc8/test_images/85f8cb619c66b863.jpg\")\n# import matplotlib.pyplot as plt\n# plt.imshow(img)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from keras.models import load_model\n# Mod = load_model(\"./model_inceptionv3.h5\")\n# Mod.save(\"./Model.h5\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# TEST_DATA_PATH = '../input/plant-pathology-2021-fgvc8/test_images/'\n\n# def process(img):\n#     return cv2.resize(img/255.0, (512, 512)).reshape(-1, 512, 512, 3)\n\n# def load_image(image):\n#     file_path = image\n#     image = cv2.imread(TEST_DATA_PATH + file_path)\n#     return image\n# #     return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n\n\n\n# from sklearn.preprocessing import MultiLabelBinarizer\n\n# mlb = MultiLabelBinarizer().fit(train_data.labels.apply(lambda x: x.split()))\n# labels = pd.DataFrame(mlb.transform(train_data.labels.apply(lambda x: x.split())), columns=mlb.classes_)\n\n\n# print(labels.columns[:])\n# print(sub.head())\n\n# THRESHOLD = 0.20\n# i = 0\n# for img in os.listdir(TEST_DATA_PATH):\n#     img = load_image(img)\n#     img = process(img)\n#     predictions = model.predict(img)\n#     print(predictions)\n#     sub.iloc[i, 1] = ' '.join(labels.columns[:][predictions[0] >= THRESHOLD])\n#     i += 1\n    \n# sub.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#base_model=tf.keras.applications.mobilenet.MobileNet(weights=None,include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.\n\n# x=base_model.output\n# #x=GlobalAveragePooling2D()(x)\n# #x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.\n# #x=Dense(1024,activation='relu')(x) #dense layer 2\n# #x=Dense(512,activation='relu')(x) #dense layer 3\n# preds=Dense(12,activation='softmax')(x) #final layer with softmax activation\n# model=Model(inputs=base_model.input,outputs=preds)\n\n# model.compile(optimizer = 'adam', loss = 'categorical_crossentropy',\n#                            metrics = ['accuracy','mae'])\n# model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#model.fit(preprocess_train_x,y_one_hot,epochs=10,batch_size=32,verbose=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}