0% found this document useful (0 votes)
6 views4 pages

Image Classification with TensorFlow

Solution for derp learning

Uploaded by

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

Image Classification with TensorFlow

Solution for derp learning

Uploaded by

Aryan Dhiman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

!

pip install tensorflow tensorflow -gpu opencv-python matplotlib

import tensorflow as tf

import os # os is used for joining the data like connecting data_dir with image Class(happy)

# Avoid OOM errors by setting GPU Memory Consumption Growth

gpus = [Link].list_physical_devices( 'GPU')

for gpu in gpus:

[Link].set_memory_growth( gpu, True)

[Link].list_physical_devices('GPU')

# 2. Remove dodgy images

import cv2

import imghdr

read_image=[Link]([Link](x,y,z))-> [Link](image) *cv read in BGR while Matplot in RGB

[Link]([Link](image,cv2.COLOR_BGR2RGB ))

data_dir = 'data'

image_exts = ['jpeg','jpg', 'bmp', 'png']

for image_class in [Link](data_dir):

for image in [Link]([Link](data_dir, image_class)):

image_path = [Link](data_dir, image_class, image)

try:

img = [Link](image_path)

tip = [Link](image_path)

if tip not in image_exts:

print('Image not in ext list {}'.format(image_path))

[Link](image_path)

except Exception as e:

print('Issue with image {}'.format(image_path))

# [Link](image_path)

# 3. Load Data

import numpy as np

from matplotlib #[Link]


data=[Link].image_dataset_from_directory(dir/subfld ') [Link] READ

cons this don’t pre load in mem but we need to grab data using numpt iterator

data_iterator = data.as_numpy_iterator()

batch = data_iterator.next()

fig, ax = [Link](ncols=4, figsize=(20,20))

for idx, img in enumerate(batch[0][:4]):

ax[idx].imshow([Link](int))

ax[idx].title.set_text(batch[1][idx])

# 4. Scale Data

data = [Link](lambda x,y: (x/255, y))

data.as_numpy_iterator().next()

# 5. Split Data

train_size = int(len(data)*.7)

val_size = int(len(data)*.2)

test_size = int(len(data)*.1)

train_size

train = [Link](train_size)

val = [Link](train_size).take(val_size)

test = [Link](train_size+val_size).take(test_size)

# 6. Build Deep Learning Model

train

\from [Link] import Sequential

from [Link] import Conv2D, MaxPooling2D, Dense, Flatten, Dropout

model = Sequential()

[Link](Conv2D(16, (3,3), 1, activation='relu', input_shape=(256,256,3)))

[Link](MaxPooling2D())

[Link](Conv2D(32, (3,3), 1, activation='relu'))

[Link](MaxPooling2D())

[Link](Conv2D(16, (3,3), 1, activation='relu'))

[Link](MaxPooling2D())

[Link](Flatten())
[Link](Dense(256, activation='relu'))

[Link](Dense(1, activation='sigmoid'))

[Link]('adam', loss=[Link](), metrics=['accuracy'])

[Link]()

# 7. Train

logdir='logs'

tensorboard_callback = [Link](log_dir=logdir)

hist = [Link](train, epochs=20, validation_data=val,


callbacks=[tensorboard_callback])

# 8. Plot Performance

fig = [Link]()

[Link]([Link]['loss'], color='teal', label='loss')

[Link]([Link]['val_loss'], color='orange', label='val_loss')

[Link]('Loss', fontsize=20)

[Link](loc="upper left")

[Link]()

fig = [Link]()

[Link]([Link]['accuracy'], color='teal', label='accuracy')

[Link]([Link]['val_accuracy'], color='orange', label='val_accuracy')

[Link]('Accuracy', fontsize=20)

[Link](loc="upper left")

[Link]()

# 9. Evaluate

from [Link] import Precision, Recall, BinaryAccuracy

pre = Precision()

re = Recall()

acc = BinaryAccuracy()

for batch in test.as_numpy_iterator():

X, y = batch

yhat = [Link](X)

pre.update_state(y, yhat)
re.update_state(y, yhat)

acc.update_state(y, yhat)

print([Link](), [Link](), [Link]())

# 10. Test

import cv2

img = [Link]('[Link]')

[Link](img)

[Link]()

resize = [Link](img, (256,256))

[Link]([Link]().astype(int))

[Link]()

yhat = [Link](np.expand_dims(resize/255, 0))

yhat

if yhat > 0.5:

print(f'Predicted class is Sad')

else:

print(f'Predicted class is Happy')

# 11. Save the Model

from [Link] import load_model

[Link]([Link]('models','imageclassifier.h5'))

new_model = load_model('imageclassifier.h5')

new_model.predict(np.expand_dims(resize/255, 0))

Common questions

Powered by AI

Splitting the dataset into train, validation, and test sets allows for model training, tuning, and testing on separate data, preventing overfitting and ensuring the model generalizes well to unseen data. This is accomplished by first determining the sizes of each set (70% train, 20% validation, 10% test) and using dataset methods like `take()` and `skip()` to create the partitions .

The process involves checking each image's format using `imghdr.what()` against a list of acceptable image extensions ('jpeg', 'jpg', 'bmp', 'png'). If an image doesn't match this list, it is removed from the dataset .

Challenges include handling large data size, preventing overfitting, and choosing the right architecture and parameters. Solutions involve using image dataset generators to load data efficiently, employing data augmentation, early stopping, and regularization techniques, and leveraging pre-trained models for transfer learning. Setting up GPU memory growth helps manage hardware constraints .

To predict the class of an image, the image is read using OpenCV and then resized to the input dimensions of the model (256x256). The image is normalized by dividing pixel values by 255. It is then expanded to match the model input shape and passed to the model. The prediction is made using `model.predict()`, and a threshold of 0.5 determines the predicted class as either 'Sad' or 'Happy' .

Saving the trained model is important for reusability, allowing the model to be loaded and used for predictions without retraining. This is accomplished using the `model.save()` function, saving the model's architecture, weights, and optimizer state to a file such as 'imageclassifier.h5' .

To handle potential OOM errors when using GPUs, you can set GPU memory growth. This ensures that the GPU memory is allocated only as needed, allowing better management of resources without running out of memory .

Model training is monitored using the TensorBoard callback, which logs training metrics such as loss and accuracy. This visualization helps in assessing the model’s training over time and identifying areas for improvement .

The metrics used to evaluate the model's performance are Precision, Recall, and Binary Accuracy. These metrics are calculated by comparing the predicted values (`yhat`) against the true labels (`y`) for batches from the test set. They are updated iteratively as batches are processed using `update_state()` .

Data augmentation can be performed in a TensorFlow data pipeline by mapping transformations to the dataset, such as scaling the pixel values by dividing by 255. Further augmentations like rotation, flipping, or color adjustments can be applied using `tf.image` transformations within the mapping function .

The deep learning model is a Convolutional Neural Network (CNN) consisting of sequential layers: three Conv2D layers with ReLU activation followed by MaxPooling2D layers, a Flatten layer, a Dense layer with 256 units and ReLU activation, and a final Dense layer with a sigmoid activation for binary classification .

You might also like