0
$\begingroup$

importing libraries

import tensorflow as tf
from tensorflow.keras import models, Sequential
import matplotlib.pyplot as plt    

from tensorflow.keras import layers
from tensorflow.keras.layers import Dense, Flatten

# importing dataset into notebook from "dataset" folder

import os

# Define the main folder containing your dataset
main_folder = "./dataset"

# Initialize lists to store image paths and corresponding labels
image_paths = []
labels = []

# Iterate through each subfolder (class) in the main folder
for class_name in os.listdir(main_folder):
    class_folder = os.path.join(main_folder, class_name)
    if os.path.isdir(class_folder):
        # Iterate through each image file in the class folder
        for image_name in os.listdir(class_folder):
            # Append the image path and corresponding label to the lists
            image_path = os.path.join(class_folder, image_name)
            image_paths.append(image_path)
            labels.append(class_name)  # Assuming the folder name represents the class label

# Print the total number of images found
print("Total number of images:", len(image_paths))

# Print the first few image paths and labels for verification
for i in range(min(5, len(image_paths))):
    print("Image Path:", image_paths[i])
    print("Label:", labels[i])
    print()

import pandas as pd
df=pd.DataFrame({'image':image_path,'labels': labels})from tensorflow.keras.preprocessing.image import ImageDataGenerator


# Create an instance of ImageDataGenerator with optional augmentation parameters
datagen = ImageDataGenerator(
    rescale=1./255, # Rescale pixel values to [0, 1]
     rotation_range=20,  # Randomly rotate images by up to 20 degrees
    # width_shift_range=0.2,  # Randomly shift images horizontally by up to 20% of the width
    # height_shift_range=0.2,  # Randomly shift images vertically by up to 20% of the height
    shear_range=0.2,  # Randomly apply shear transformations
    # zoom_range=0.2,  # Randomly zoom in or out by up to 20%
     horizontal_flip=True,  # Randomly flip images horizontally
     fill_mode='nearest'  # Strategy to fill in newly created pixels after rotation or shifting
)

# Create a generator for reading images from the directory
generator = datagen.flow_from_dataframe(
    df,
    x_col='image',
    y_col='labels', # Path to the target directory
    target_size=(256, 256),  # Resize images to (150, 150) during loading
    batch_size=3000,  # Number of images to yield in each batch
    class_mode='categorical'  # Type of labels (e.g., binary, categorical)
)

train_images, train_labels = next(generator)import numpy as np

# Get the size of the array
array_size = train_images.size

# Calculate the number of samples (assuming each sample has dimensions (256, 256, 3))
num_samples = array_size // (256 * 256 * 3)

# Create the new shape
new_shape = (num_samples, 256, 256, 3)

# Reshape the array
train_images = train_images.reshape(new_shape)
train_images.shape
from sklearn.model_selection import train_test_split 

# Split data into training, validation, and testing sets

X_train, X_test1, y_train, y_test1 = train_test_split(train_images, train_labels, test_size=0.3, random_state=42)
X_test, X_val, y_test, y_val = train_test_split(X_test1, y_test1, test_size=0.5, random_state=42) 
def conv_block(filters, act='relu'): 
 block = models.Sequential()
 block.add(layers.Conv2D(filters, 3, activation=act, padding='same'))
 block.add(layers.Conv2D(filters, 3, activation=act, padding='same'))
 block.add(layers.BatchNormalization())
 block.add(layers.MaxPool2D())
 
 return block
def norm_block(units, dropout_rate, act='relu'): 
 block = models.Sequential()
 block.add(layers.Dense(units, activation=act))
 block.add(layers.BatchNormalization())
 block.add(layers.Dropout(dropout_rate))
 
 return block
def construct_model(act='relu'):
     model = models.Sequential([
     tf.keras.Input(shape=(*[256 ,256], 3)),
     layers.Conv2D(16, 3, activation=act, padding='same'),
     layers.Conv2D(16, 3, activation=act, padding='same'),
     layers.MaxPool2D(),

     conv_block(64),
     conv_block(128),
     layers.Dropout(0.2),
     conv_block(256),
     layers.Dropout(0.2),
     layers.Flatten(),
     norm_block(512, 0.7),
     norm_block(128, 0.5),
     norm_block(64, 0.3),
     layers.Dense(7, activation='softmax') 
     ])
     return model
model = construct_model()
model.compile(loss='categorical_crossentropy',
              optimizer='adam', # try using RMSprop
              metrics=['accuracy'])
model.summary()

history = model.fit(X_train, 
                y_train,
                validation_data=(X_val, y_val),
                                    epochs=100)

I am getting accuracy of nearly 25% only...can anybody please help me with increasing accuracy...pls somebody help me..i am doing it past consective 4 days and cant figureout...it will be a lot helpful if i can get the answer

$\endgroup$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.