3

#1.load amd preprocess the CIFAR-10 dataset

import numpy as np

import tensorflow as tf

from tensorflow.keras.datasets import cifar10

from tensorflow.keras.models import Sequential

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

from sklearn.metrics import accuracy_score, precision_score, recall_score


# Load the CIFAR-10 dataset

(x_train, y_train), (x_test, y_test) = cifar10.load_data()


# Normalize pixel values to be between 0 and 1

x_train = x_train.astype('float32') / 255.0

x_test = x_test.astype('float32') / 255.0

# convert class vectors to binary class matrices(one-hot encoding)

y_train = tf.keras.utils.to_categorical(y_train,num_classes=10)

y_test = tf.keras.utils.to_categorical(y_test,num_classes=10)


#2.define a deeper cnn model

#define the cnn model

model = Sequential()

model.add(Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)))

model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))

model.add(MaxPooling2D((2, 2)))

model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))

model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))

model.add(MaxPooling2D((2, 2)))

model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))

model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))

model.add(MaxPooling2D((2, 2)))

model.add(Flatten())

model.add(Dense(128, activation='relu'))

model.add(Dense(10, activation='softmax'))


#compaile the model

model.compile(optimizer='adam',

              loss='categorical_crossentropy',

              metrics=['accuracy'])

#3.evaluate the model using precision,recall, and confusion matrix:

#train the model

model.fit(x_train, y_train, batch_size=64, epochs=10, validation_data=(x_test, y_test))

#evaluate the model

y_pred = model.predict(x_test)

y_pred_classes = np.argmax(y_pred, axis=1)

y_test_classes = np.argmax(y_test, axis=1)

#calculate precision and recall

precision = precision_score(y_test_classes, y_pred_classes, average='macro')

recall = recall_score(y_test_classes, y_pred_classes, average='macro')

print('Precision:', precision)

print('Recall:', recall) 

Comments

Popular posts from this blog

2

1