└── Handwritten Digit Classification /Handwritten Digit Classification: -------------------------------------------------------------------------------- 1 | from tensorflow.keras.datasets import mnist 2 | from tensorflow.keras.models import Sequential 3 | from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D 4 | from tensorflow.keras.callbacks import EarlyStopping 5 | 6 | # Load the MNIST dataset 7 | (X_train, y_train), (X_test, y_test) = mnist.load_data() 8 | 9 | # Preprocess the data 10 | X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255 11 | X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255 12 | 13 | # One-hot encode the labels 14 | y_train = pd.get_dummies(y_train).values 15 | y_test = pd.get_dummies(y_test).values 16 | 17 | # Define the CNN model 18 | model = Sequential() 19 | model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1))) 20 | model.add(MaxPooling2D((2, 2))) 21 | model.add(Flatten()) 22 | model.add(Dense(128, activation='relu', kernel_initializer='he_uniform')) 23 | model.add(Dense(10, activation='softmax')) 24 | 25 | # Compile the model 26 | model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) 27 | 28 | # Early stopping to prevent overfitting 29 | early_stopping = EarlyStopping(monitor='val_loss', patience=3) 30 | 31 | # Train the model 32 | model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test), callbacks=[early_stopping]) 33 | 34 | # Evaluate the model 35 | loss, accuracy = model.evaluate(X_test, y_test) 36 | print(f'Test accuracy: {accuracy:.2f}') 37 | --------------------------------------------------------------------------------