{"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\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\nfor 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 numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras.applications import MobileNet\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import StratifiedKFold\n\n# Load the Dog Breed dataset\ntrain_df = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')\ntest_df = pd.read_csv('/kaggle/input/dog-breed-identification/sample_submission.csv')\n\ntrain_df['img_file']=train_df['id']+'.jpg'\ntest_df['img_file']=test_df['id']+'.jpg'\n\n# Define data generators with data augmentation\n\ntrain_datagen = ImageDataGenerator(rescale=1./255, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, validation_split=0.1,fill_mode='nearest')\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# Define the number of folds for cross-validation\nn_folds = 5\n\n# Define the cross-validation split\nskf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=42)\n\n# Define the MobileNet model\nmodel = MobileNet(include_top=False, input_shape=(224,224,3))\n\n# Add a new Dense layer for the output\nx = model.output\nx = tf.keras.layers.GlobalAveragePooling2D()(x)\nx=  tf.keras.layers.Dropout(0.2)(x)\nx = tf.keras.layers.Dense(120, activation='softmax')(x)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the new model\nmodel = tf.keras.models.Model(inputs=model.input, outputs=x)\n\n# Compile the model with Adam optimizer and loss function\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Initialize the history variable\nhistory = {'loss': [], 'accuracy': [], 'val_loss': [], 'val_accuracy': []}\n\n# Loop over the cross-validation splits starting from the second fold index\nfor fold_idx, (train_indices, val_indices) in enumerate(skf.split(train_df['img_file'], train_df['breed'])):\n    if fold_idx > 0:  # exclude the first fold\n        print(f\"Training fold {fold_idx}...\")\n        # Get the training and validation data for this fold\n        train_data = train_df.iloc[train_indices]\n        val_data = train_df.iloc[val_indices]\n\n        # Define the generators for this fold\n        train_generator = train_datagen.flow_from_dataframe(dataframe=train_data, directory=\"/kaggle/input/dog-breed-identification/train/\", x_col=\"img_file\", y_col=\"breed\", target_size=(224,224), batch_size=32, class_mode=\"categorical\", subset=\"training\")\n        val_generator = train_datagen.flow_from_dataframe(dataframe=val_data, directory=\"/kaggle/input/dog-breed-identification/train/\", x_col=\"img_file\", y_col=\"breed\", target_size=(224,224), batch_size=32, class_mode=\"categorical\", subset=\"validation\")\n\n        # Train the model for this fold\n        hist = model.fit(train_generator, epochs=10, validation_data=val_generator)\n        \n        # Concatenate the history for this fold\n        history['loss'] += hist.history['loss']\n        history['accuracy'] += hist.history['accuracy']\n        history['val_loss'] += hist.history['val_loss']\n        history['val_accuracy'] += hist.history['val_accuracy']","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_data","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}