{"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 pandas as pd\n\nimport os, cv2, random, time, shutil, csv\nimport tensorflow as tf\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport tqdm as tqdm\nnp.random.seed(42)\n%matplotlib inline\nimport json\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nimport keras\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Model\nfrom keras.layers import BatchNormalization, Dense, GlobalAveragePooling2D, Lambda, Dropout, InputLayer, Input\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.preprocessing.image import load_img\nfrom tqdm import tqdm\nfrom sklearn.utils import shuffle\nfrom keras.preprocessing import image","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:22.190058Z","iopub.execute_input":"2023-01-12T02:07:22.190507Z","iopub.status.idle":"2023-01-12T02:07:29.588038Z","shell.execute_reply.started":"2023-01-12T02:07:22.190403Z","shell.execute_reply":"2023-01-12T02:07:29.586889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read train labels\nlabels_df = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:40.599675Z","iopub.execute_input":"2023-01-12T02:07:40.600337Z","iopub.status.idle":"2023-01-12T02:07:40.637109Z","shell.execute_reply.started":"2023-01-12T02:07:40.600299Z","shell.execute_reply":"2023-01-12T02:07:40.636081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create list of alphabetically sorted labels\ndog_breeds = sorted(list(set(labels_df['breed'])))\nn_classes = len(dog_breeds)","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:41.431665Z","iopub.execute_input":"2023-01-12T02:07:41.432391Z","iopub.status.idle":"2023-01-12T02:07:41.446289Z","shell.execute_reply.started":"2023-01-12T02:07:41.432354Z","shell.execute_reply":"2023-01-12T02:07:41.444987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Map each label string to an integer label\nclass_to_num = dict(zip(dog_breeds, range(n_classes)))","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:42.312284Z","iopub.execute_input":"2023-01-12T02:07:42.312722Z","iopub.status.idle":"2023-01-12T02:07:42.322024Z","shell.execute_reply.started":"2023-01-12T02:07:42.312686Z","shell.execute_reply":"2023-01-12T02:07:42.320531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define image path\ntrain_dir = '/kaggle/input/dog-breed-identification/train/'\nimg_path =  os.path.join(train_dir,np.random.choice(os.listdir(train_dir)))","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:43.156818Z","iopub.execute_input":"2023-01-12T02:07:43.157242Z","iopub.status.idle":"2023-01-12T02:07:43.353447Z","shell.execute_reply.started":"2023-01-12T02:07:43.157191Z","shell.execute_reply":"2023-01-12T02:07:43.352199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Prepare image for model input\nimg = load_img(img_path, target_size=(128, 128))\nx = np.array(img).astype(\"float32\")\nx = np.expand_dims(x, axis=0)\nx = preprocess_input(x)","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:43.925609Z","iopub.execute_input":"2023-01-12T02:07:43.926012Z","iopub.status.idle":"2023-01-12T02:07:43.955348Z","shell.execute_reply.started":"2023-01-12T02:07:43.925981Z","shell.execute_reply":"2023-01-12T02:07:43.954370Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create ResNet50 model with pre-trained weights\nbase_model = ResNet50(weights='imagenet', include_top=False, input_shape=(128, 128, 3))","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:44.547008Z","iopub.execute_input":"2023-01-12T02:07:44.547844Z","iopub.status.idle":"2023-01-12T02:07:46.921604Z","shell.execute_reply.started":"2023-01-12T02:07:44.547795Z","shell.execute_reply":"2023-01-12T02:07:46.920570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Freeze all layers\nfor layer in base_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:53.441106Z","iopub.execute_input":"2023-01-12T02:07:53.441550Z","iopub.status.idle":"2023-01-12T02:07:53.452967Z","shell.execute_reply.started":"2023-01-12T02:07:53.441516Z","shell.execute_reply":"2023-01-12T02:07:53.451861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Add new layers\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(1024, activation='relu')(x)\nx = Dropout(0.5)(x)\npredictions = Dense(n_classes, activation='softmax')(x)","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:55.407465Z","iopub.execute_input":"2023-01-12T02:07:55.408301Z","iopub.status.idle":"2023-01-12T02:07:55.448250Z","shell.execute_reply.started":"2023-01-12T02:07:55.408254Z","shell.execute_reply":"2023-01-12T02:07:55.446998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create new model\nmodel = Model(inputs=base_model.input, outputs=predictions)\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:56.735763Z","iopub.execute_input":"2023-01-12T02:07:56.736156Z","iopub.status.idle":"2023-01-12T02:07:56.763845Z","shell.execute_reply.started":"2023-01-12T02:07:56.736128Z","shell.execute_reply":"2023-01-12T02:07:56.762710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = []\ny_train = []\n\nfor img_path in labels_df['id'].values:\n    img_path = os.path.join(train_dir,img_path+'.jpg')\n    img = load_img(img_path, target_size=(128, 128, 1))\n    x = np.array(img).astype(\"float32\")\n    x = preprocess_input(x)\n    x_train.append(x)\n    y_train.append(class_to_num[labels_df[labels_df['id'] == img_path.split('/')[-1].split('.')[0]]['breed'].values[0]])\n\nX_train = np.array(x_train)\ny_train = to_categorical(y_train, num_classes=n_classes)\nX_train, y_train = shuffle(X_train, y_train)\n# Number of epochs to train\nnum_epochs = 50","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:07:57.633899Z","iopub.execute_input":"2023-01-12T02:07:57.634334Z","iopub.status.idle":"2023-01-12T02:10:05.848064Z","shell.execute_reply.started":"2023-01-12T02:07:57.634299Z","shell.execute_reply":"2023-01-12T02:10:05.846630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fit the model\nhistory = model.fit(X_train, y_train, epochs=num_epochs, batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2023-01-12T02:10:53.639561Z","iopub.execute_input":"2023-01-12T02:10:53.640031Z","iopub.status.idle":"2023-01-12T05:30:57.665408Z","shell.execute_reply.started":"2023-01-12T02:10:53.639994Z","shell.execute_reply":"2023-01-12T05:30:57.663998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot the accuracy and loss curves\nplt.plot(history.history['accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train'], loc='upper left')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-12T05:34:31.306266Z","iopub.execute_input":"2023-01-12T05:34:31.306677Z","iopub.status.idle":"2023-01-12T05:34:31.518454Z","shell.execute_reply.started":"2023-01-12T05:34:31.306645Z","shell.execute_reply":"2023-01-12T05:34:31.517581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train'], loc='upper left')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-12T05:34:31.520086Z","iopub.execute_input":"2023-01-12T05:34:31.520942Z","iopub.status.idle":"2023-01-12T05:34:31.745141Z","shell.execute_reply.started":"2023-01-12T05:34:31.520901Z","shell.execute_reply":"2023-01-12T05:34:31.743797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the image and preprocess it\nimg_path =  os.path.join(train_dir,np.random.choice(os.listdir(train_dir)))\nimg = image.load_img(img_path, target_size=(128, 128))\nimg_tensor = image.img_to_array(img)\nimg_tensor = np.expand_dims(img_tensor, axis=0)\nimg_tensor /= 3.","metadata":{"execution":{"iopub.status.busy":"2023-01-12T05:42:50.362089Z","iopub.execute_input":"2023-01-12T05:42:50.362610Z","iopub.status.idle":"2023-01-12T05:42:50.383723Z","shell.execute_reply.started":"2023-01-12T05:42:50.362575Z","shell.execute_reply":"2023-01-12T05:42:50.382556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the predictions\npredictions = model.predict(img_tensor)","metadata":{"execution":{"iopub.status.busy":"2023-01-12T05:42:50.590384Z","iopub.execute_input":"2023-01-12T05:42:50.590803Z","iopub.status.idle":"2023-01-12T05:42:50.722702Z","shell.execute_reply.started":"2023-01-12T05:42:50.590771Z","shell.execute_reply":"2023-01-12T05:42:50.721071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the class label with highest prediction score\nlabel_index = np.argmax(predictions[0])\n\n# Create a dictionary to map class indices to class labels\nnum_to_class = {v: k for k, v in class_to_num.items()}","metadata":{"execution":{"iopub.status.busy":"2023-01-12T05:42:50.920012Z","iopub.execute_input":"2023-01-12T05:42:50.920414Z","iopub.status.idle":"2023-01-12T05:42:50.926021Z","shell.execute_reply.started":"2023-01-12T05:42:50.920383Z","shell.execute_reply":"2023-01-12T05:42:50.924735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Use the dictionary to map the class index to the corresponding class label\npredicted_label = num_to_class[label_index]","metadata":{"execution":{"iopub.status.busy":"2023-01-12T05:42:51.135291Z","iopub.execute_input":"2023-01-12T05:42:51.136083Z","iopub.status.idle":"2023-01-12T05:42:51.140765Z","shell.execute_reply.started":"2023-01-12T05:42:51.136041Z","shell.execute_reply":"2023-01-12T05:42:51.139683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Print the predictions and display the image\nprint(\"Predicted label: \", predicted_label)\nplt.imshow(img)\nplt.title(predicted_label)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-12T05:42:51.350137Z","iopub.execute_input":"2023-01-12T05:42:51.350592Z","iopub.status.idle":"2023-01-12T05:42:51.597660Z","shell.execute_reply.started":"2023-01-12T05:42:51.350553Z","shell.execute_reply":"2023-01-12T05:42:51.596062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}