Group C

QC2: 2. TensorFlow/Pytorch implementation of CNN

CNN Implementation

Solution and implementation for QC2 from Artificial Neural Network (ann).

C2_CNN_tensorflow.ipynb Download
Code Cell [In]
!pip install tensorflow scikit-learn matplotlib -q
Code Cell [In]
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
Code Cell [In]
(X_train, y_train), (X_test, y_test) = keras.datasets.cifar10.load_data()

print("Train shape:", X_train.shape)
print("Test shape:", X_test.shape)
Code Cell [In]
X_train = X_train / 255.0
X_test = X_test / 255.0
Code Cell [In]
class_names = ['airplane','automobile','bird','cat','deer',
               'dog','frog','horse','ship','truck']

plt.imshow(X_train[0])
plt.title(class_names[y_train[0][0]])
plt.axis('off')
plt.show()
Code Cell [In]
model = keras.Sequential([
    keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)),
    keras.layers.MaxPooling2D((2,2)),

    keras.layers.Conv2D(64, (3,3), activation='relu'),
    keras.layers.MaxPooling2D((2,2)),

    keras.layers.Conv2D(128, (3,3), activation='relu'),
    keras.layers.MaxPooling2D((2,2)),

    keras.layers.Flatten(),

    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

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

model.summary()
Code Cell [In]
history = model.fit(
    X_train, y_train,
    epochs=10,
    batch_size=64,
    validation_split=0.1
)
Code Cell [In]
loss, accuracy = model.evaluate(X_test, y_test)
print("Test Accuracy:", accuracy)
Code Cell [In]
plt.plot(history.history['accuracy'], label='train acc')
plt.plot(history.history['val_accuracy'], label='val acc')
plt.legend()
plt.title("Accuracy")
plt.show()
Code Cell [In]
from tensorflow.keras.preprocessing import image
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

img_path = "horse.jpg"

# Load image
img = Image.open(img_path).resize((32,32))

# Convert to array
img_array = np.array(img) / 255.0

# Reshape for model
img_array = img_array.reshape(1,32,32,3)

# Predict
prediction = model.predict(img_array)
class_index = np.argmax(prediction)

print("Predicted class:", class_names[class_index])

# Show image
plt.imshow(img)
plt.title("Input Image")
plt.axis('off')
plt.show()
horse.jpg Download
Answer image: horse.jpg

Other Questions in Artificial Neural Network

See All Available Questions
Download