{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model  # Import load_model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport cv2\nimport os","metadata":{"execution":{"iopub.status.busy":"2023-08-30T13:48:10.997684Z","iopub.execute_input":"2023-08-30T13:48:10.998286Z","iopub.status.idle":"2023-08-30T13:48:22.847561Z","shell.execute_reply.started":"2023-08-30T13:48:10.998242Z","shell.execute_reply":"2023-08-30T13:48:22.846117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/face-recognition-xt122/ClassMap.csv')\ndf_sub = pd.read_csv('/kaggle/input/face-recognition-xt122/SampleSubmission.csv')","metadata":{"execution":{"iopub.status.busy":"2023-08-30T13:48:22.849627Z","iopub.execute_input":"2023-08-30T13:48:22.850426Z","iopub.status.idle":"2023-08-30T13:48:22.876930Z","shell.execute_reply.started":"2023-08-30T13:48:22.850390Z","shell.execute_reply":"2023-08-30T13:48:22.875990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2023-08-30T13:48:22.878564Z","iopub.execute_input":"2023-08-30T13:48:22.879545Z","iopub.status.idle":"2023-08-30T13:48:22.907550Z","shell.execute_reply.started":"2023-08-30T13:48:22.879508Z","shell.execute_reply":"2023-08-30T13:48:22.906024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sub.head()","metadata":{"execution":{"iopub.status.busy":"2023-08-30T13:48:22.910538Z","iopub.execute_input":"2023-08-30T13:48:22.910934Z","iopub.status.idle":"2023-08-30T13:48:22.923916Z","shell.execute_reply.started":"2023-08-30T13:48:22.910902Z","shell.execute_reply":"2023-08-30T13:48:22.922189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the labels from the CSV file\nlabels_df = pd.read_csv('/kaggle/input/face-recognition-xt122/ClassMap.csv')\n\n# Define paths for train and test data\ntrain_data_dir = '/kaggle/input/face-recognition-xt122/Train'\ntest_data_dir = '/kaggle/input/face-recognition-xt122/Test'\n\n# Set input image dimensions and batch size\nimg_width, img_height = 150, 150\nbatch_size = 32\n\n# Create an ImageDataGenerator for data augmentation and preprocessing\ntrain_datagen = ImageDataGenerator(\n    rescale=1.0 / 255,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n\ntest_datagen = ImageDataGenerator(rescale=1.0 / 255)\n\n# Load and preprocess train and test data from subfolders with labels\ntrain_generator = train_datagen.flow_from_directory(\n    train_data_dir,\n    target_size=(img_width, img_height),\n    batch_size=batch_size,\n    class_mode='categorical',\n    classes=labels_df['classe_name'].tolist()\n)\n\ntest_generator = test_datagen.flow_from_directory(\n    test_data_dir,\n    target_size=(img_width, img_height),\n    batch_size=batch_size,\n    class_mode='categorical',\n    classes=labels_df['classe_name'].tolist()\n)\n\n# Create a CNN model (same as before)\nmodel = Sequential([\n    Conv2D(216, (3, 3), activation='relu', input_shape=(img_width, img_height, 3)),\n    MaxPooling2D(2, 2),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Conv2D(32, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    Flatten(),\n    Dropout(0.5),\n    Dense(512, activation='relu'),\n    Dense(len(labels_df), activation='softmax')\n])\n","metadata":{"execution":{"iopub.status.busy":"2023-08-30T13:48:22.926047Z","iopub.execute_input":"2023-08-30T13:48:22.926462Z","iopub.status.idle":"2023-08-30T13:48:23.348079Z","shell.execute_reply.started":"2023-08-30T13:48:22.926427Z","shell.execute_reply":"2023-08-30T13:48:23.346797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer=Adam(learning_rate=0.0001),\n              loss = 'mean_squared_error',\n              )\n\n# Train the model\nmodel.fit(train_generator, epochs=30, validation_data=test_generator)\n\n# Save the trained model\nmodel.save('image_classifier_model.h5')","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-08-30T13:48:23.349925Z","iopub.execute_input":"2023-08-30T13:48:23.350410Z","iopub.status.idle":"2023-08-30T14:28:06.580537Z","shell.execute_reply.started":"2023-08-30T13:48:23.350367Z","shell.execute_reply":"2023-08-30T14:28:06.579419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the trained model\nmodel = load_model('/kaggle/working/image_classifier_model.h5')\n\n# Load and preprocess an input image\nimg_path = '/kaggle/input/face-recognition-xt122/Test/akwqggjjvl.jpg'\nimg = image.load_img(img_path, target_size=(150, 150))\nimg_array = image.img_to_array(img)\nimg_array = np.expand_dims(img_array, axis=0) / 255.0\n\n# Make predictions using the model\npredictions = model.predict(img_array)\nclass_index = np.argmax(predictions[0])  # Get the class index with highest probability\n\n# Get the class label corresponding to the predicted index\npredicted_label = labels_df['classe_name'][class_index]\n\n# Visualize the input image and prediction using a plot\nplt.imshow(img)\nplt.title(f'Predicted Label: {predicted_label}')\nplt.axis('off')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-08-30T14:28:06.582233Z","iopub.execute_input":"2023-08-30T14:28:06.583672Z","iopub.status.idle":"2023-08-30T14:28:07.592008Z","shell.execute_reply.started":"2023-08-30T14:28:06.583602Z","shell.execute_reply":"2023-08-30T14:28:07.590305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = load_model('image_classifier_model.h5') \n# Load the sample submission CSV\nsample_submission = pd.read_csv('/kaggle/input/face-recognition-xt122/SampleSubmission.csv')  \n\n# Define path for test data\ntest_data_dir = '/kaggle/input/face-recognition-xt122/Test'\n\n# Load the list of test image filenames\ntest_filenames = os.listdir(test_data_dir)\n\n# Create a DataFrame to hold the filenames\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\n\n# Set input image dimensions and batch size\nimg_width, img_height = 150, 150\nbatch_size = 32\n\ntest_datagen = ImageDataGenerator(rescale=1.0 / 255)\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=test_df,\n    directory=test_data_dir,\n    x_col='filename', \n    y_col=None,       \n    target_size=(img_width, img_height),\n    batch_size=batch_size,\n    class_mode=None,   \n    shuffle=False      \n)\n\n\n\n","metadata":{"execution":{"iopub.status.busy":"2023-08-30T14:28:07.593966Z","iopub.execute_input":"2023-08-30T14:28:07.594823Z","iopub.status.idle":"2023-08-30T14:28:08.060447Z","shell.execute_reply.started":"2023-08-30T14:28:07.594780Z","shell.execute_reply":"2023-08-30T14:28:08.058895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions using the model\npredictions = model.predict(test_generator, steps=len(test_generator), verbose=1)\n\n# Rearrange predictions to match the order of the sample submission\nrearranged_predictions = [predictions[sample_submission.index[i]] for i in range(len(sample_submission))]\n\n# Get the class indices with the highest probabilities\npredicted_indices = np.argmax(rearranged_predictions, axis=1)\n\n# Map class indices to label numbers using the provided dictionary\nclass_to_label = {'Jennie': 0, 'Jisoo': 1, 'Lisa': 2, 'Rose': 3, 'Others': 4}\npredicted_labels = [class_to_label[label] for label in labels_df['classe_name'][predicted_indices]]\n\n# Create a submission DataFrame\nsubmission_df = pd.DataFrame({\n    'filename': sample_submission['filename'],\n    'label': predicted_labels\n})\n\n# Save the submission DataFrame to a CSV file\nsubmission_df.to_csv('submission.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2023-08-30T14:28:08.062450Z","iopub.execute_input":"2023-08-30T14:28:08.062973Z","iopub.status.idle":"2023-08-30T14:28:29.768679Z","shell.execute_reply.started":"2023-08-30T14:28:08.062915Z","shell.execute_reply":"2023-08-30T14:28:29.767335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df","metadata":{"execution":{"iopub.status.busy":"2023-08-30T14:28:29.771854Z","iopub.execute_input":"2023-08-30T14:28:29.772303Z","iopub.status.idle":"2023-08-30T14:28:29.788412Z","shell.execute_reply.started":"2023-08-30T14:28:29.772268Z","shell.execute_reply":"2023-08-30T14:28:29.787033Z"},"trusted":true},"execution_count":null,"outputs":[]}],"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"}}