1-A

# 1. Import necessary packages

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import pandas as pd
import matplotlib.pyplot as plt


# 2. Load the training and testing data

train_data = pd.read_csv("mnist_train.csv")
test_data = pd.read_csv("mnist_test.csv")

print("Training Data:", train_data.shape)
print("Testing Data:", test_data.shape)


# 3. Separate labels and pixel values

y_train = train_data.iloc[:, 0].values
y_test = test_data.iloc[:, 0].values

x_train = train_data.iloc[:, 1:].values
x_test = test_data.iloc[:, 1:].values

print("Training Images:", x_train.shape)
print("Training Labels:", y_train.shape)
print("Testing Images:", x_test.shape)
print("Testing Labels:", y_test.shape)


# 4. Normalize the pixel values

x_train = x_train / 255.0
x_test = x_test / 255.0

print("Minimum Pixel Value:", x_train.min())
print("Maximum Pixel Value:", x_train.max())


# 5. Define the FNN architecture

model = keras.Sequential([
    keras.Input(shape=(784,)),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dense(10, activation='softmax')
])

model.summary()


# 6. Compile the model using SGD

model.compile(
    optimizer=keras.optimizers.SGD(),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)


# 7. Train the model for 11 epochs

history = model.fit(
    x_train,
    y_train,
    epochs=11,
    batch_size=32
)


# 8. Evaluate the network

test_loss, test_accuracy = model.evaluate(x_test, y_test)

print("Test Loss:", test_loss)
print("Test Accuracy:", test_accuracy)


# 9. Plot training loss and accuracy

plt.figure(figsize=(12, 5))

# Plot training loss
plt.subplot(1, 2, 1)
plt.plot(history.history['loss'])
plt.title('Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')

# Plot training accuracy
plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'])
plt.title('Training Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')

plt.tight_layout()
plt.show()