Commit df4e099e authored by Marasinghe G.M.H.T.'s avatar Marasinghe G.M.H.T.

In here I have trained inception V3 pretrained model to train my new dataset.

parent 2a62afb4
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "b7ee9c77",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"WARNING:tensorflow:Please fix your imports. Module tensorflow.python.training.tracking.data_structures has been moved to tensorflow.python.trackable.data_structures. The old module will be deleted in version 2.11.\n",
"Found 1416 files belonging to 2 classes.\n",
"Using 1133 files for training.\n",
"Found 1416 files belonging to 2 classes.\n",
"Using 283 files for validation.\n",
"Epoch 1/10\n",
"36/36 [==============================] - 39s 891ms/step - loss: 15.4106 - accuracy: 0.6884 - val_loss: 3.0666 - val_accuracy: 0.8657\n",
"Epoch 2/10\n",
"36/36 [==============================] - 32s 863ms/step - loss: 0.6082 - accuracy: 0.9444 - val_loss: 1.1136e-05 - val_accuracy: 1.0000\n",
"Epoch 3/10\n",
"36/36 [==============================] - 32s 873ms/step - loss: 0.0023 - accuracy: 0.9982 - val_loss: 6.2764e-08 - val_accuracy: 1.0000\n",
"Epoch 4/10\n",
"36/36 [==============================] - 32s 873ms/step - loss: 5.6396e-08 - accuracy: 1.0000 - val_loss: 4.0860e-08 - val_accuracy: 1.0000\n",
"Epoch 5/10\n",
"36/36 [==============================] - 34s 930ms/step - loss: 4.9767e-08 - accuracy: 1.0000 - val_loss: 3.7911e-08 - val_accuracy: 1.0000\n",
"Epoch 6/10\n",
"36/36 [==============================] - 35s 953ms/step - loss: 4.9030e-08 - accuracy: 1.0000 - val_loss: 3.7911e-08 - val_accuracy: 1.0000\n",
"Epoch 7/10\n",
"36/36 [==============================] - 32s 879ms/step - loss: 4.9030e-08 - accuracy: 1.0000 - val_loss: 3.7911e-08 - val_accuracy: 1.0000\n",
"Epoch 8/10\n",
"36/36 [==============================] - 33s 897ms/step - loss: 4.9030e-08 - accuracy: 1.0000 - val_loss: 3.7911e-08 - val_accuracy: 1.0000\n",
"Epoch 9/10\n",
"36/36 [==============================] - 32s 885ms/step - loss: 4.9030e-08 - accuracy: 1.0000 - val_loss: 3.7911e-08 - val_accuracy: 1.0000\n",
"Epoch 10/10\n",
"36/36 [==============================] - 33s 897ms/step - loss: 4.9030e-08 - accuracy: 1.0000 - val_loss: 3.7911e-08 - val_accuracy: 1.0000\n"
]
}
],
"source": [
"import tensorflow as tf\n",
"import tensorflow_hub as hub\n",
"import os\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Set the paths to your dataset folders\n",
"dataset_path = \"C:/ELBOW ANGLE-1 - Copy\"\n",
"correct_position_path = os.path.join(dataset_path, \"Corect Position\")\n",
"wrong_position_path = os.path.join(dataset_path, \"Wrong Posision\")\n",
"\n",
"# Set the parameters for training\n",
"batch_size = 32\n",
"img_height = 224\n",
"img_width = 224\n",
"epochs = 10\n",
"\n",
"# Load the pretrained InceptionV3 model from TensorFlow Hub\n",
"model_url = \"https://tfhub.dev/google/imagenet/inception_v3/classification/4\"\n",
"model = tf.keras.Sequential([\n",
" hub.KerasLayer(model_url, trainable=False),\n",
" tf.keras.layers.Dense(2, activation=\"softmax\")\n",
"])\n",
"\n",
"# Compile the model\n",
"model.compile(optimizer=\"adam\",\n",
" loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n",
" metrics=[\"accuracy\"])\n",
"\n",
"# Prepare the training dataset\n",
"train_ds = tf.keras.preprocessing.image_dataset_from_directory(\n",
" dataset_path,\n",
" validation_split=0.2,\n",
" subset=\"training\",\n",
" seed=123,\n",
" image_size=(img_height, img_width),\n",
" batch_size=batch_size\n",
")\n",
"\n",
"# Prepare the validation dataset\n",
"val_ds = tf.keras.preprocessing.image_dataset_from_directory(\n",
" dataset_path,\n",
" validation_split=0.2,\n",
" subset=\"validation\",\n",
" seed=123,\n",
" image_size=(img_height, img_width),\n",
" batch_size=batch_size\n",
")\n",
"\n",
"# Train the model\n",
"history = model.fit(\n",
" train_ds,\n",
" validation_data=val_ds,\n",
" epochs=epochs\n",
")\n",
"\n",
"# Plot the loss and accuracy curves\n",
"plt.figure(figsize=(12, 4))\n",
"plt.subplot(1, 2, 1)\n",
"plt.plot(history.history[\"loss\"], label=\"Training Loss\")\n",
"plt.plot(history.history[\"val_loss\"], label=\"Validation Loss\")\n",
"plt.xlabel(\"Epoch\")\n",
"plt.ylabel(\"Loss\")\n",
"plt.legend()\n",
"\n",
"plt.subplot(1, 2, 2)\n",
"plt.plot(history.history[\"accuracy\"], label=\"Training Accuracy\")\n",
"plt.plot(history.history[\"val_accuracy\"], label=\"Validation Accuracy\")\n",
"plt.xlabel(\"Epoch\")\n",
"plt.ylabel(\"Accuracy\")\n",
"plt.legend()\n",
"plt.show()\n",
"\n",
"# Test the model on a sample image\n",
"sample_image_path = \"C:/ELBOW ANGLE-1 - Copy/Corect Position/sample_image.jpg\"\n",
"sample_image = tf.keras.preprocessing.image.load_img(\n",
" sample_image_path, target_size=(img_height, img_width)\n",
")\n",
"sample_image_array = tf.keras.preprocessing.image.img_to_array(sample_image)\n",
"sample_image_array = np.expand_dims(sample_image_array, axis=0)\n",
"sample_image_array = sample_image_array / 255.0 # Normalize the image\n",
"\n",
"predictions = model.predict(sample_image_array)\n",
"predicted_class = np.argmax(predictions[0])\n",
"if predicted_class == 0:\n",
" predicted_label = \"Correct Position\"\n",
"else:\n",
" predicted_label = \"Wrong Position\"\n",
"\n",
"val_loss, val_accuracy = model.evaluate(val_ds)\n",
"print(\"Validation Accuracy:\", val_accuracy)\n",
"print(\"Predicted label:\", predicted_label)\n",
"print(\"Predicted probabilities:\", predictions[0])\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "fa0328ec",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found 1857 images belonging to 2 classes.\n",
"Found 463 images belonging to 2 classes.\n",
"WARNING:tensorflow:Please fix your imports. Module tensorflow.python.training.tracking.data_structures has been moved to tensorflow.python.trackable.data_structures. The old module will be deleted in version 2.11.\n",
"Epoch 1/10\n",
"59/59 [==============================] - 64s 951ms/step - loss: 0.1433 - accuracy: 0.9472 - val_loss: 0.0120 - val_accuracy: 1.0000\n",
"Epoch 2/10\n",
"59/59 [==============================] - 55s 923ms/step - loss: 0.0099 - accuracy: 1.0000 - val_loss: 0.0059 - val_accuracy: 1.0000\n",
"Epoch 3/10\n",
"59/59 [==============================] - 58s 987ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.0040 - val_accuracy: 1.0000\n",
"Epoch 4/10\n",
"59/59 [==============================] - 51s 861ms/step - loss: 0.0034 - accuracy: 1.0000 - val_loss: 0.0039 - val_accuracy: 1.0000\n",
"Epoch 5/10\n",
"59/59 [==============================] - 52s 885ms/step - loss: 0.0024 - accuracy: 1.0000 - val_loss: 0.0029 - val_accuracy: 1.0000\n",
"Epoch 6/10\n",
"59/59 [==============================] - 52s 871ms/step - loss: 0.0018 - accuracy: 1.0000 - val_loss: 0.0023 - val_accuracy: 1.0000\n",
"Epoch 7/10\n",
"59/59 [==============================] - 53s 889ms/step - loss: 0.0015 - accuracy: 1.0000 - val_loss: 0.0020 - val_accuracy: 1.0000\n",
"Epoch 8/10\n",
"59/59 [==============================] - 52s 877ms/step - loss: 0.0012 - accuracy: 1.0000 - val_loss: 0.0018 - val_accuracy: 1.0000\n",
"Epoch 9/10\n",
"59/59 [==============================] - 52s 874ms/step - loss: 9.8604e-04 - accuracy: 1.0000 - val_loss: 0.0015 - val_accuracy: 1.0000\n",
"Epoch 10/10\n",
"59/59 [==============================] - 52s 885ms/step - loss: 8.3909e-04 - accuracy: 1.0000 - val_loss: 0.0012 - val_accuracy: 1.0000\n",
"15/15 [==============================] - 11s 679ms/step - loss: 0.0012 - accuracy: 1.0000\n",
"Validation accuracy: 100.00%\n",
"1/1 [==============================] - 1s 1s/step\n",
"Test image prediction: Correct Position\n",
"Prediction probability: 0.9999942183494568\n"
]
}
],
"source": [
"import tensorflow as tf\n",
"import tensorflow_hub as hub\n",
"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n",
"from PIL import Image\n",
"\n",
"# Define the paths to your dataset folders\n",
"dataset_path = r'C:\\Users\\A C E R\\Desktop\\ELBOW ANGLE'\n",
"correct_position_path = r'C:\\Users\\A C E R\\Desktop\\ELBOW ANGLE\\Corect Position'\n",
"wrong_position_path = r'C:\\Users\\A C E R\\Desktop\\ELBOW ANGLE\\Wrong Posision'\n",
"\n",
"# Parameters for training\n",
"batch_size = 32\n",
"image_size = (224, 224)\n",
"num_epochs = 10\n",
"learning_rate = 0.001\n",
"\n",
"# Create data generators for training and validation\n",
"datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)\n",
"\n",
"train_generator = datagen.flow_from_directory(\n",
" dataset_path,\n",
" target_size=image_size,\n",
" batch_size=batch_size,\n",
" class_mode='binary',\n",
" subset='training'\n",
")\n",
"\n",
"val_generator = datagen.flow_from_directory(\n",
" dataset_path,\n",
" target_size=image_size,\n",
" batch_size=batch_size,\n",
" class_mode='binary',\n",
" subset='validation'\n",
")\n",
"\n",
"# Load the InceptionV3 model from TensorFlow Hub\n",
"model_url = 'https://tfhub.dev/google/imagenet/inception_v3/classification/5'\n",
"base_model = hub.KerasLayer(model_url, input_shape=image_size + (3,))\n",
"\n",
"# Freeze the base model\n",
"base_model.trainable = False\n",
"\n",
"# Build the model\n",
"model = tf.keras.Sequential([\n",
" base_model,\n",
" tf.keras.layers.Dense(1, activation='sigmoid')\n",
"])\n",
"\n",
"# Compile the model\n",
"model.compile(\n",
" optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),\n",
" loss=tf.keras.losses.BinaryCrossentropy(),\n",
" metrics=['accuracy']\n",
")\n",
"\n",
"# Train the model\n",
"history = model.fit(\n",
" train_generator,\n",
" validation_data=val_generator,\n",
" epochs=num_epochs\n",
")\n",
"\n",
"# Evaluate the model on the validation set\n",
"_, accuracy = model.evaluate(val_generator)\n",
"print(f'Validation accuracy: {accuracy*100:.2f}%')\n",
"\n",
"# Load a test image and predict the class label\n",
"test_image_path = 'C:\\\\Users\\\\A C E R\\\\Desktop\\\\image_2.jpeg' # Provide the path to your test image\n",
"test_image = Image.open(test_image_path)\n",
"test_image = test_image.resize(image_size) # Resize the image to match the input size of the model\n",
"test_image = tf.keras.preprocessing.image.img_to_array(test_image)\n",
"test_image = test_image / 255.0 # Normalize the image\n",
"\n",
"# Expand dimensions to create a batch of size 1\n",
"test_image = tf.expand_dims(test_image, axis=0)\n",
"\n",
"# Predict the class probability\n",
"prediction = model.predict(test_image)[0][0]\n",
"\n",
"# Determine the predicted class label based on the threshold of 0.5\n",
"predicted_label = 'Correct Position' if prediction >= 0.5 else 'Incorrect Position'\n",
"\n",
"# Print the predicted class label and probability\n",
"print(f'Test image prediction: {predicted_label}')\n",
"print(f'Prediction probability: {prediction}')\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "767a97e6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1/1 [==============================] - 0s 76ms/step\n",
"Test image prediction: Correct Position\n",
"Prediction probability: 0.9999876022338867\n"
]
}
],
"source": [
"\n",
"# Load a test image and predict the class label\n",
"test_image_path = 'C:\\\\Users\\\\A C E R\\\\Desktop\\\\image_2.jpeg' # Provide the path to your test image\n",
"test_image = Image.open(test_image_path)\n",
"test_image = test_image.resize(image_size) # Resize the image to match the input size of the model\n",
"test_image = tf.keras.preprocessing.image.img_to_array(test_image)\n",
"test_image = test_image / 255.0 # Normalize the image\n",
"\n",
"# Expand dimensions to create a batch of size 1\n",
"test_image = tf.expand_dims(test_image, axis=0)\n",
"\n",
"# Predict the class probability\n",
"prediction = model.predict(test_image)[0][0]\n",
"\n",
"# Determine the predicted class label based on the threshold of 0.5\n",
"predicted_label = 'Correct Position' if prediction >= 0.5 else 'Incorrect Position'\n",
"\n",
"# Print the predicted class label and probability\n",
"print(f'Test image prediction: {predicted_label}')\n",
"print(f'Prediction probability: {prediction}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "167dbb21",
"metadata": {},
"outputs": [],
"source": [
"CNN"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
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