{"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"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":65471,"databundleVersionId":7211464,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-17T23:49:22.998536Z","iopub.execute_input":"2024-06-17T23:49:22.999149Z","iopub.status.idle":"2024-06-17T23:49:37.131508Z","shell.execute_reply.started":"2024-06-17T23:49:22.999114Z","shell.execute_reply":"2024-06-17T23:49:37.130760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir='/kaggle/input/arabic-letters-classification/Final_Arabic_Alpha_dataset/Final_Arabic_Alpha_dataset/train'","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:49:37.132876Z","iopub.execute_input":"2024-06-17T23:49:37.133535Z","iopub.status.idle":"2024-06-17T23:49:37.138398Z","shell.execute_reply.started":"2024-06-17T23:49:37.133488Z","shell.execute_reply":"2024-06-17T23:49:37.137417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nimport os\n\n# Define paths in the writable /kaggle/working/ directory\ntraining_dir = '/kaggle/working/training'\nvalidation_dir = '/kaggle/working/validation'\n\n# Create directories\nos.makedirs(training_dir, exist_ok=True)\nos.makedirs(validation_dir, exist_ok=True)\n# Verify the existence of the train directory\nif not os.path.exists(train_dir):\n    raise FileNotFoundError(f\"Directory '{train_dir}' not found.\")\n\n# Create the training and validation directories\nos.makedirs(training_dir, exist_ok=True)\nos.makedirs(validation_dir, exist_ok=True)\n\n# Iterate through each class folder in the train directory\nfor class_folder in os.listdir(train_dir):\n    class_path = os.path.join(train_dir, class_folder)\n\n    # Get a list of images in the class folder\n    class_images = [img for img in os.listdir(class_path) if img.endswith('.png')]\n\n    # Check if there are enough images for the train-test split\n    if len(class_images) < 2:\n        print(f\"Skipping class '{class_folder}' due to insufficient images.\")\n        continue\n\n    # Split the images into training and validation sets (80-20 split)\n    train_images, validation_images = train_test_split(class_images, test_size=0.2, random_state=42)\n\n    # Create the class directories in the training and validation directories\n    class_training_dir = os.path.join(training_dir, class_folder)\n    class_validation_dir = os.path.join(validation_dir, class_folder)\n    \n    os.makedirs(class_training_dir, exist_ok=True)\n    os.makedirs(class_validation_dir, exist_ok=True)\n\n    # Move images to the training directory\n    for img in train_images:\n        src_path = os.path.join(class_path, img)\n        dest_path = os.path.join(class_training_dir, img)\n        shutil.copy2(src_path, dest_path)\n\n    # Move images to the validation directory\n    for img in validation_images:\n        src_path = os.path.join(class_path, img)\n        dest_path = os.path.join(class_validation_dir, img)\n        shutil.copy2(src_path, dest_path)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:49:37.139531Z","iopub.execute_input":"2024-06-17T23:49:37.139968Z","iopub.status.idle":"2024-06-17T23:52:04.535165Z","shell.execute_reply.started":"2024-06-17T23:49:37.139942Z","shell.execute_reply":"2024-06-17T23:52:04.534307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\nfrom IPython.display import display\n# Paths\ntrain_dir='/kaggle/input/arabic-letters-classification/Final_Arabic_Alpha_dataset/Final_Arabic_Alpha_dataset/train'\n\n# Choose a class folder\nclass_folder = '7'\n\n# Path to the training images in the chosen class\nclass_folder_path = os.path.join(train_dir, class_folder)\n\n# Check if the directory exists and has files\nif os.path.exists(class_folder_path) and os.listdir(class_folder_path):\n    # Get the first image in the directory\n    image_path = os.path.join(class_folder_path, os.listdir(class_folder_path)[5])\n\n    # Open and display the image\n    image = Image.open(image_path)\n    display(image)\nelse:\n    print(f\"No images found in the class folder {class_folder}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:04.537397Z","iopub.execute_input":"2024-06-17T23:52:04.537710Z","iopub.status.idle":"2024-06-17T23:52:04.558227Z","shell.execute_reply.started":"2024-06-17T23:52:04.537684Z","shell.execute_reply":"2024-06-17T23:52:04.557565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_height, img_width = 300, 128\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True\n)\n\nvalidation_datagen = ImageDataGenerator(\n    rescale=1./255,\n)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:04.559205Z","iopub.execute_input":"2024-06-17T23:52:04.559452Z","iopub.status.idle":"2024-06-17T23:52:04.565409Z","shell.execute_reply.started":"2024-06-17T23:52:04.559430Z","shell.execute_reply":"2024-06-17T23:52:04.564690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(\n    training_dir,\n    target_size=(img_height, img_width),\n    color_mode=\"grayscale\",\n    batch_size=32,\n    class_mode='categorical',\n    shuffle=True,\n    seed=42\n)\n\nvalidation_generator = validation_datagen.flow_from_directory(\n    validation_dir,\n    target_size=(img_height, img_width),\n    color_mode=\"grayscale\",\n    batch_size=32,\n    class_mode='categorical',\n    shuffle=False,\n    seed=42\n)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:04.566405Z","iopub.execute_input":"2024-06-17T23:52:04.566740Z","iopub.status.idle":"2024-06-17T23:52:05.975948Z","shell.execute_reply.started":"2024-06-17T23:52:04.566707Z","shell.execute_reply":"2024-06-17T23:52:05.975027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications import VGG19\nfrom tensorflow.keras.layers import Input\nimport tensorflow as tf\n\ninput_tensor = Input(shape=(img_height, img_width, 1))\nrgb_tensor = tf.image.grayscale_to_rgb(input_tensor)\nbase_model = VGG19(weights='imagenet', include_top=False, input_tensor=rgb_tensor)\n","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:05.977235Z","iopub.execute_input":"2024-06-17T23:52:05.977528Z","iopub.status.idle":"2024-06-17T23:52:08.456375Z","shell.execute_reply.started":"2024-06-17T23:52:05.977502Z","shell.execute_reply":"2024-06-17T23:52:08.455606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:08.457457Z","iopub.execute_input":"2024-06-17T23:52:08.457774Z","iopub.status.idle":"2024-06-17T23:52:08.462745Z","shell.execute_reply.started":"2024-06-17T23:52:08.457746Z","shell.execute_reply":"2024-06-17T23:52:08.461850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import layers, models\nmodel = models.Sequential([\n    base_model,\n    layers.Flatten(),\n    layers.Dense(512, activation='relu'),\n    layers.Dropout(0.5),\n    layers.Dense(65, activation='softmax')\n])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:08.463933Z","iopub.execute_input":"2024-06-17T23:52:08.464188Z","iopub.status.idle":"2024-06-17T23:52:08.629006Z","shell.execute_reply.started":"2024-06-17T23:52:08.464155Z","shell.execute_reply":"2024-06-17T23:52:08.628156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),  \n              loss='categorical_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:08.630050Z","iopub.execute_input":"2024-06-17T23:52:08.630282Z","iopub.status.idle":"2024-06-17T23:52:08.646086Z","shell.execute_reply.started":"2024-06-17T23:52:08.630261Z","shell.execute_reply":"2024-06-17T23:52:08.645265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    train_generator,\n    steps_per_epoch=len(train_generator),\n    epochs=50,\n    validation_data=validation_generator,\n    validation_steps=len(validation_generator)\n)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T23:52:08.647160Z","iopub.execute_input":"2024-06-17T23:52:08.648873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}