{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":7327,"databundleVersionId":861871,"sourceType":"competition"}],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\nimport numpy as np # linear algebra\nimport 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\nimport 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":"import cv2\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\nimport warnings\nwarnings.filterwarnings('ignore', category=FutureWarning)\nwarnings.filterwarnings('ignore', category=UserWarning)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')\nsample = pd.read_csv('/kaggle/input/dog-breed-identification/sample_submission.csv')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels['img'] = '/kaggle/input/dog-breed-identification/train/' + labels['id'] + '.jpg'\n\n# List of breeds\nbreeds = [\n    'affenpinscher', 'afghan_hound', 'african_hunting_dog', 'airedale',\n    'american_staffordshire_terrier', 'appenzeller', 'australian_terrier',\n    'basenji', 'basset', 'beagle', 'bedlington_terrier', 'bernese_mountain_dog',\n    'black-and-tan_coonhound', 'blenheim_spaniel', 'bloodhound', 'bluetick',\n    'border_collie', 'border_terrier', 'borzoi', 'boston_bull', 'bouvier_des_flandres',\n    'boxer', 'brabancon_griffon', 'briard', 'brittany_spaniel', 'bull_mastiff',\n    'cairn', 'cardigan', 'chesapeake_bay_retriever', 'chihuahua', 'chow',\n    'clumber', 'cocker_spaniel', 'collie', 'curly-coated_retriever', 'dandie_dinmont',\n    'dhole', 'dingo', 'doberman', 'english_foxhound', 'english_setter',\n    'english_springer', 'entlebucher', 'eskimo_dog', 'flat-coated_retriever',\n    'french_bulldog', 'german_shepherd', 'german_short-haired_pointer',\n    'giant_schnauzer', 'golden_retriever', 'gordon_setter', 'great_dane',\n    'great_pyrenees', 'greater_swiss_mountain_dog', 'groenendael', 'ibizan_hound',\n    'irish_setter', 'irish_terrier', 'irish_water_spaniel', 'irish_wolfhound',\n    'italian_greyhound', 'japanese_spaniel', 'keeshond', 'kelpie',\n    'kerry_blue_terrier', 'komondor', 'kuvasz', 'labrador_retriever',\n    'lakeland_terrier', 'leonberg', 'lhasa', 'malamute', 'malinois', 'maltese_dog',\n    'mexican_hairless', 'miniature_pinscher', 'miniature_poodle',\n    'miniature_schnauzer', 'newfoundland', 'norfolk_terrier', 'norwegian_elkhound',\n    'norwich_terrier', 'old_english_sheepdog', 'otterhound', 'papillon', 'pekinese',\n    'pembroke', 'pomeranian', 'pug', 'redbone', 'rhodesian_ridgeback', 'rottweiler',\n    'saint_bernard', 'saluki', 'samoyed', 'schipperke', 'scotch_terrier',\n    'scottish_deerhound', 'sealyham_terrier', 'shetland_sheepdog', 'shih-tzu',\n    'siberian_husky', 'silky_terrier', 'soft-coated_wheaten_terrier',\n    'staffordshire_bullterrier', 'standard_poodle', 'standard_schnauzer',\n    'sussex_spaniel', 'tibetan_mastiff', 'tibetan_terrier', 'toy_poodle', 'toy_terrier',\n    'vizsla', 'walker_hound', 'weimaraner', 'welsh_springer_spaniel',\n    'west_highland_white_terrier', 'whippet', 'wire-haired_fox_terrier', 'yorkshire_terrier'\n]\n\n# Create the mapping dictionary\nbreed_to_label = {breed: idx for idx, breed in enumerate(breeds)}\n\n# Map the breed column to numerical labels\nlabels['encoded_breed'] = labels['breed'].map(breed_to_label)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocess the images\nx = []\nfor img in labels['img']:\n    img = cv2.imread(img)\n    img = cv2.resize(img, (170, 170))\n    img = img / 255.0\n    x.append(img)\n\nx = np.array(x)\n\n# Convert labels to one-hot encoding\ny = labels['encoded_breed']\ny = to_categorical(y, num_classes=120)  # Assuming 120 unique dog breeds\n\n# Split the data into training and testing sets\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=42)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the VGG16 model pre-trained on ImageNet without the top layers\nbase_model = VGG16(weights='imagenet', include_top=False, input_shape=(170, 170, 3))\n\n# Freeze the base model layers\nfor layer in base_model.layers:\n    layer.trainable = False\n\n# Add custom top layers for our classification task\nx = Flatten()(base_model.output)\nx = Dense(512, activation='relu')(x)\nx = Dropout(0.5)(x)\nx = Dense(120, activation='softmax')(x)  # 120 classes for dog breeds\n\n# Create the model\nmodel = Model(inputs=base_model.input, outputs=x)\n\n# Compile the model\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nhistory = model.fit(x_train, y_train, epochs=25, batch_size=32, validation_data=(x_test, y_test))\n\n# Evaluate the model\nloss, accuracy = model.evaluate(x_test, y_test)\nprint(f'Test Loss: {loss}')\nprint(f'Test Accuracy: {accuracy}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#pip install --upgrade tensorflow keras","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('my_cnn_model.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}