0% found this document useful (0 votes)
7 views5 pages

CNN_Model_Code

Uploaded by

021CIVQazi Adnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

CNN_Model_Code

Uploaded by

021CIVQazi Adnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

CNN MODEL

# Step 1: Import Required Libraries

import os

import numpy as np

import tensorflow as tf

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout

from sklearn.model_selection import train_test_split

import matplotlib.pyplot as plt

# Step 2: Define Paths to Data

crack_dir = '/content/crack'

# Directory containing crack images

without_crack_dir = '/content/without_crack'

# Directory containing images without cracks

# Step 3: Initialize Data and Labels

data = []

labels = []

# Step 4: Define Valid Extensions and Load Images Function


CNN MODEL

valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff')

def load_images(folder_path, label):

"""Load images from the given folder path and assign the specified label."""

for root, _, files in os.walk(folder_path):

# Traverse all subdirectories

for img_name in files:

if img_name.lower().endswith(valid_extensions):

# Check for valid image files

img_path = os.path.join(root, img_name)

try:

img = tf.keras.utils.load_img(img_path, target_size=(128, 128))

# Resize image

img = tf.keras.utils.img_to_array(img) / 255.0

# Normalize pixel values

data.append(img)

labels.append(label)

except Exception as e:

print(f"Error loading image {img_path}: {e}")

# Step 5: Load Crack and Non-Crack Images

load_images(crack_dir, label=1)

# Label 1 for crack images

load_images(without_crack_dir, label=0)
CNN MODEL

# Label 0 for non-crack images

# Step 6: Convert Data and Labels to Numpy Arrays

data = np.array(data)

labels = np.array(labels)

print(f"Total images loaded: {len(data)}")

print(f"Labels distribution: {np.bincount(labels)}")

# Count of each label (0 and 1)

# Step 7: Split Data into Training and Testing Sets

X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=4

print(f"Training set size: {len(X_train)}, Testing set size: {len(X_test)}")

# Step 8: Build the Convolutional Neural Network (CNN) Model

model = Sequential([

Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)),

# First convolutional layer

MaxPooling2D((2, 2)),

# Max pooling

Conv2D(64, (3, 3), activation='relu'),

# Second convolutional layer

MaxPooling2D((2, 2)),
CNN MODEL

# Max pooling

Conv2D(128, (3, 3), activation='relu'),

# Third convolutional layer

MaxPooling2D((2, 2)),

# Max pooling

Flatten(),

# Flatten the output for the dense layer

Dense(128, activation='relu'),

# Fully connected dense layer

Dropout(0.5),

# Dropout to prevent overfitting

Dense(1, activation='sigmoid') # Output layer for binary classification

])

# Step 9: Compile the Model

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Step 10: Train the Model

history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=25, batch_size=3

# Step 11: Evaluate the Model on Test Data

test_loss, test_accuracy = model.evaluate(X_test, y_test)


CNN MODEL

print(f"Test Accuracy: {test_accuracy:.2f}")

# Step 12: Save the Model

model.save('/content/crack_detection_model.h5')

print("Model saved as 'crack_detection_model.h5'.")

# Step 13: Download the Model

from google.colab import files

files.download('/content/crack_detection_model.h5')

# Step 14: Plot Training Results

plt.plot(history.history['accuracy'], label='Train Accuracy')

plt.plot(history.history['val_accuracy'], label='Validation Accuracy')

plt.xlabel('Epochs')

plt.ylabel('Accuracy')

plt.legend()

plt.show()

You might also like