Creating Python code for digit classification
The user wants Python code to classify handwritten digits, likely using MNIST with Keras or TensorFlow. I’ll choose TensorFlow, since it’s common. I’ll provide concise yet functional code with comments, including model definition, training, and evaluation. I think it’s sensible to load the MNIST dataset and reshape the input for a CNN. Although the user hasn't asked for an explanation, I will include everything needed to run the script, ensuring it’s clear and ready to go!Finalizing Python code structure
I’m considering adding features like early stopping and saving models, but I want to keep it concise according to the user's instructions. I should include some code comments but avoid lengthy explanations. It might be a good idea to create a self-contained script, focusing on modular functions and maybe even GPU detection. I’ll ensure the code is set to execute typically in environments with TensorFlow version 2 or higher. I’ll present just the code block, with a brief explanation beforehand if needed. ```python
"""
CNN for handwritten digit classification (MNIST) using TensorFlow/Keras.
Install dependencies:
pip install tensorflow
Run:
python mnist_cnn.py
"""
import tensorflow as tf
from tensorflow.keras import layers, models
def load_and_preprocess_data():
# Load MNIST dataset (60,000 training + 10,000 test 28x28 grayscale images)
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Normalize to [0, 1] and add channel dimension (28, 28, 1)
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
return (x_train, y_train), (x_test, y_test)
def build_cnn_model(input_shape=(28, 28, 1), num_classes=10):
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation="relu", input_shape=input_shape),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation="relu"),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation="relu"),
layers.Flatten(),
layers.Dense(64, activation="relu"),
layers.Dense(num_classes, activation="softmax"),
])
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
def main():
(x_train, y_train), (x_test, y_test) = load_and_preprocess_data()
model = build_cnn_model()
model.summary()
# Train
model.fit(
x_train, y_train,
epochs=5,
batch_size=64,
validation_split=0.1,
verbose=2,
)
# Evaluate
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"\nTest accuracy: {test_acc:.4f}")
# Save model
model.save("mnist_cnn_model.h5")
print("Model saved as mnist_cnn_model.h5")
if name == "main":
main()