DL 4
DL 4
: 4
Name: Gayatri Rajendra Jagadale
Roll No.:2447062
Batch: D
Problem Statement –
Design and implement a CNN for Image Classification a) Select a suitable image classification dataset
(medical imaging, agricultural, etc.). b) Optimized with different hyper-parameters including learning
rate, filter size, no. of layers, optimizers, dropouts, etc.
1. Import Libraries
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,
Dense, Dropout
from tensorflow.keras.optimizers import Adam, SGD
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
y_train = y_train.flatten()
show_dataset_grid(x_train, y_train, class_names, rows=5,
cols=10)
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(dropout_rate))
model.add(Dense(10, activation='softmax')) # 10 classes
model.compile(optimizer=optimizer,
loss='categorical_crossentropy', metrics=['accuracy'])
return model
4. Train Model with Hyperparameters
# Try different optimizers
optimizer = Adam(learning_rate=0.001) # Try SGD(learning_rate=0.01)
as well dropout_rate = 0.3
model = create_cnn_model(optimizer=optimizer,
dropout_rate=dropout_rate)
D:\Users\shrey\anaconda3\lib\site-packages\keras\src\layers\
convolutional\base_conv.py:107: UserWarning: Do not pass an
`input_shape`/`input_dim` argument to a layer. When using Sequential
models, prefer using an `Input(shape)` object as the first layer in
the model instead.
super().__init__(activity_regularizer=activity_regularizer, **kwargs)
# Classification report
print(classification_report(y_test, y_pred, target_names=class_names))
precision recall f1-score support
airplane 0.77 0.60 0.67 1000
automobile 0.76 0.82 0.79 1000
plt.figure(figsize=(12,4))
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Val Accuracy')
plt.legend() plt.title('Accuracy')
plt.subplot(1,2,2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.legend() plt.title('Loss')
plt.tight_layout()
plt.show()
import numpy as np
from tensorflow.keras.preprocessing import image from
PIL import Image import matplotlib.pyplot as plt
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
prediction = model.predict(img_array)
predicted_class = class_names[np.argmax(prediction)]