Question: Python Using the code below 1 . adjust parameters to improve accuracy and a discussion on the activities you performed and results. 2 . Generate

Python
Using the code below
1. adjust parameters to improve accuracy and a discussion on the activities you performed and results.
2. Generate a Tensorboard and produce graphics that show various improvements that you were able to gain. Loss and Accuracy for train and validation for example.
#Load the libraries - Load them all here - not sprinkled throughout the notebook.
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, recall_score, precision_score, f1_score
import warnings
warnings.filterwarnings('ignore') #ignore warnings
%load_ext tensorboard
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.optimizers import Adam, Nadam, RMSprop
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test)= mnist.load_data()
from google.colab import drive
drive.mount('/content/drive')
df_mnist_train = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/data/mnist_train.csv')
df_mnist_test = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/data/mnist_test.csv')
Model Development
batch_size =32
num_classes =10
epochs =10
input_shape =(28,28,1)
optimizer = Adam(learning_rate=0.001)
log_dir = "logs/fit/" # Adjust the directory as needed
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32,(5,5), padding='same', activation='relu', input_shape=input_shape),
tf.keras.layers.Conv2D(32,(5,5), padding='same', activation='relu'),
tf.keras.layers.MaxPool2D(),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.Conv2D(64,(3,3), padding='same', activation='relu'),
tf.keras.layers.Conv2D(64,(3,3), padding='same', activation='relu'),
tf.keras.layers.MaxPool2D(strides=(2,2)),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_classes, activation='softmax')
])
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['acc'])
# Define early stopping callback
early_stopping = EarlyStopping(
monitor='val_loss', # Monitor validation loss
patience=3, # Number of epochs with no improvement after which training will stop
min_delta=0.001, # Minimum change to qualify as an improvement
mode='min', # 'min' because we're looking for the minimum validation loss
restore_best_weights=True # Restore model weights from the epoch with the best validation loss
)
from sys import version
# Train the model with early stopping
history = model.fit(
train_array, y_train,
validation_split=0.2,
epochs=epochs,
batch_size=batch_size,
verbose =1,
callbacks=[early_stopping, tensorboard_callback]
)
fig, ax = plt.subplots(2,1)
ax[0].plot(history.history['loss'], color='b', label="Training Loss")
ax[0].plot(history.history['val_loss'], color='r', label="Validation Loss",axes =ax[0])
legend = ax[0].legend(loc='best', shadow=True)
ax[1].plot(history.history['acc'], color='b', label="Training Accuracy")
ax[1].plot(history.history['val_acc'], color='r',label="Validation Accuracy")
legend = ax[1].legend(loc='best', shadow=True)
test_loss, test_acc = model.evaluate(test_array, y_test)
# Predict the values from the testing dataset
Y_pred = model.predict(test_array)
# Convert predictions classes to one hot vectors
Y_pred_classes = np.argmax(Y_pred,axis =1)
# Convert testing observations to one hot vectors
Y_true = np.argmax(y_test,axis =1)
# compute the confusion matrix
confusion_mtx = tf.math.confusion_matrix(Y_true, Y_pred_classes)
plt.figure(figsize=(10,8))
sns.heatmap(confusion_mtx, annot=True, fmt='g')
accuracy = accuracy_score(Y_true, Y_pred_classes)
recall = recall_score(Y_true, Y_pred_classes, average='weighted')
precision = precision_score(Y_true, Y_pred_classes, average='weighted')
f1= f1_score(Y_true, Y_pred_classes, average='weighted')
print(f"Accuracy: {accuracy}")
print(f"Recall: {recall}")
print(f"Precision: {precision}")
print(f"F1 Score: {f1}")
%tensorboard --logdir logs/fit
batch_size =32
num_classes =10
epochs =10
train_array = train_array.reshape(60000,28,28)
optimizer = Adam(learning_rate=0.001)
log_dir = "logs/fit/" # Adjust the directory as needed
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
The code is continued on the image
Python Using the code below 1 . adjust parameters

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!