Commit 2a11e4ab authored by Tharupathi M.A.U's avatar Tharupathi M.A.U

Upload New File

parent 21c8b7e7
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qFl9szU9egoS"
},
"outputs": [],
"source": [
"from google.colab import drive\n",
"drive.mount(\"/content/drive/\",force_remount=False)"
]
},
{
"cell_type": "code",
"source": [
"!pip install autokeras\n",
"import autokeras as ak\n",
"import tensorflow as tf\n",
"from tensorflow.keras.utils import to_categorical\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"from tensorflow.keras.utils import plot_model\n",
"\n",
"train_path = '/content/drive/MyDrive/dr_data_set/train/'\n",
"validation_path = '/content/drive/MyDrive/dr_data_set/validation/'\n",
"\n",
"# Load image dataset and corresponding labels\n",
"train_data_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n",
"train_set = train_data_gen.flow_from_directory(\n",
" train_path,\n",
" target_size=(128, 128),\n",
" batch_size=16, #32\n",
" class_mode='categorical',\n",
" shuffle=False\n",
")\n",
"\n",
"validation_data_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\n",
"validation_set = validation_data_gen.flow_from_directory(\n",
" validation_path,\n",
" target_size=(128, 128),\n",
" batch_size=16,\n",
" class_mode='categorical',\n",
" shuffle=False\n",
")\n",
"\n",
"# Convert the image datasets and labels into NumPy arrays\n",
"x_train = train_set[0][0]\n",
"y_train = to_categorical(train_set[0][1]) # Convert the target labels to categorical format\n",
"x_val = validation_set[0][0]\n",
"y_val = to_categorical(validation_set[0][1]) # Convert the target labels to categorical format\n",
"\n",
"# Reshape the target data to have the expected shape\n",
"y_train = np.reshape(y_train, (y_train.shape[0], -1))\n",
"y_val = np.reshape(y_val, (y_val.shape[0], -1))\n",
"\n",
"with tf.device('/GPU:0'):\n",
" # Initialize the ImageClassifier and perform the search for the best model\n",
" clf = ak.ImageClassifier(overwrite=True, max_trials=5)\n",
" best_model_plot = clf.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=10)\n",
"\n",
" print(\"clf\", clf)\n",
"\n",
" # Access the training history\n",
" history = best_model_plot.history\n",
"\n",
" # Plot the loss and accuracy\n",
" plt.figure(figsize=(12, 4))\n",
"\n",
" # Get the best model found during the search\n",
" best_model = clf.export_model()\n",
"\n",
" # Print the details of the best model\n",
" best_model.summary()\n",
"\n",
" # Evaluate the best model\n",
" evaluation = best_model.evaluate(x_val, y_val)\n",
" print(\"evaluation\", evaluation)\n",
"\n",
" # Plot the loss and validation loss\n",
" plt.subplot(1, 2, 1)\n",
" plt.plot(history['loss'], color='teal', label='Training Loss')\n",
" plt.plot(history['val_loss'], color='orange', label='Validation Loss')\n",
" plt.title('Loss')\n",
" plt.xlabel('Epochs')\n",
" plt.ylabel('Loss')\n",
" plt.legend()\n",
"\n",
" plt.subplot(1, 2, 2)\n",
" plt.plot(history['accuracy'], color='teal', label='Training Accuracy')\n",
" plt.plot(history['val_accuracy'], color='orange', label='Validation Accuracy')\n",
" plt.title('Accuracy')\n",
" plt.xlabel('Epochs')\n",
" plt.ylabel('Accuracy')\n",
" plt.legend()\n",
"\n",
" plt.tight_layout()\n",
" plt.show()\n",
"\n",
" #########\n",
"\n",
" # Save the best model\n",
" best_model.save('eye_model.h5')\n",
"\n",
" # Plot the model architecture\n",
" plot_model(best_model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)\n",
"\n",
" # Load the best model\n",
" loaded_model = tf.keras.models.load_model('eye_model.h5', custom_objects=ak.CUSTOM_OBJECTS)\n",
"\n",
" # Sanity Check by Visualizing the Model Predictions\n",
"\n",
" if tf.test.is_gpu_available():\n",
" with tf.device('GPU'):\n",
" loaded_model = loaded_model\n",
" else:\n",
" loaded_model = loaded_model\n",
"\n",
" ##########\n",
"\n",
" # Set up data transforms for visualization\n",
" data_transforms = tf.keras.preprocessing.image.ImageDataGenerator(\n",
" rescale=1.0/255,\n",
" samplewise_center=True,\n",
" samplewise_std_normalization=True\n",
" )\n",
"\n",
" data_dir = '/content/drive/MyDrive/dr_data_set'\n",
"\n",
" import os\n",
"\n",
" # Load test dataset\n",
" test_dataset = data_transforms.flow_from_directory(\n",
" os.path.join(data_dir, 'test'),\n",
" target_size=(128, 128),\n",
" batch_size=16,\n",
" class_mode='categorical',\n",
" shuffle=True\n",
" )\n",
"\n",
" class_names = ['dr', 'healthy']\n",
"\n",
" def visualize_model(model, num_images=10):\n",
" images, labels = test_dataset.next()\n",
" predictions = model.predict(images)\n",
" predicted_labels = np.argmax(predictions, axis=1)\n",
"\n",
" plt.figure(figsize=(10, 10))\n",
" for i in range(min(num_images, len(images))):\n",
" plt.subplot(2, 5, i+1)\n",
" plt.imshow(images[i])\n",
" if predicted_labels[i] < len(class_names):\n",
" plt.title(f'Predicted: {class_names[predicted_labels[i]]}')\n",
" else:\n",
" plt.title(\"Predicted: dr\")\n",
" #plt.title(f'Predicted: {class_names[predicted_labels[i]]}')\n",
" plt.axis('off')\n",
" plt.show()\n",
"\n",
" #loaded_model = loaded_model.to('cuda' if tf.test.is_gpu_available() else 'cpu') # Use GPU if available\n",
" visualize_model(loaded_model, num_images=10)\n",
"\n",
"\n",
"\n"
],
"metadata": {
"id": "k6Tk4KYieosx"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"\n",
"\n",
" #Load and preprocess the new image\n",
" new_image_path = '/content/drive/MyDrive/dr_data_set/374_left.jpeg' # Replace with the path to your new image\n",
" new_image = tf.keras.preprocessing.image.load_img(new_image_path, target_size=(128, 128))\n",
" new_image = tf.keras.preprocessing.image.img_to_array(new_image)\n",
" new_image = new_image / 255.0 # Normalize the image\n",
"\n",
" # Reshape the image to match the expected input shape\n",
" new_image = tf.expand_dims(new_image, axis=0)\n",
"\n",
" # Make predictions using the loaded model\n",
" predictions = loaded_model.predict(new_image)\n",
"\n",
" print(\"predictions\", predictions)\n",
"\n",
"\n",
" # Retrieve the class names and their order\n",
" class_indices = train_set.class_indices\n",
" class_names = list(class_indices.keys())\n",
" #class_names = train_set.classes\n",
"\n",
" # Get the predicted class label\n",
" predicted_class_index = np.argmax(predictions[0])\n",
"\n",
" print(\"all class\", class_names)\n",
" print(\"int\", class_indices)\n",
" print(\"predicted_class_index\", predicted_class_index)\n",
"\n",
" # Get the predicted class name\n",
" predicted_class_name = class_names[predicted_class_index]\n",
"\n",
" print(\"class\", predicted_class_name)"
],
"metadata": {
"id": "iyFym2QSeucI"
},
"execution_count": null,
"outputs": []
}
]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment