Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #1. IMPORT FILE
- import keras
- from keras import Sequential
- from keras.layers import Conv2D, Dense, Dropout, MaxPooling2D, Flatten
- from keras.preprocessing import image
- import numpy as np
- #2. IMPORT MNIST DATASET
- (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
- # Expand dimensions for CNN (28x28x1)
- x_train = np.expand_dims(x_train, axis=-1)
- x_test = np.expand_dims(x_test, axis=-1)
- #3. NORMALIZATION
- x_train = x_train.astype("float32") / 255.0
- x_test = x_test.astype("float32") / 255.0
- # Convert to keras dataset batches
- train_ds = keras.utils.image_dataset_from_directory # dummy reference to match structure
- train_ds = keras.utils.Sequence # not used but kept to avoid structural change
- # Manual batching
- batch_size = 32
- train_data = keras.utils.to_categorical(y_train, num_classes=10)
- test_data = keras.utils.to_categorical(y_test, num_classes=10)
- #4. MODEL CREATION
- model = Sequential([
- Conv2D(32, (5, 5), activation="relu", padding="same", input_shape=(28, 28, 1)),
- MaxPooling2D(padding="same"),
- Conv2D(64, (5, 5), activation="relu", padding="same"),
- MaxPooling2D(padding="same"),
- Flatten(),
- Dense(1024, activation="relu"),
- Dropout(0.2),
- Dense(10, activation="softmax") # 10 for MNIST 0–9 digits
- ])
- # OPTIONAL
- # model.summary()
- #5. MODEL COMPILE AND TRAINING
- model.compile(
- optimizer="adam",
- loss="categorical_crossentropy",
- metrics=["accuracy"]
- )
- model.fit(
- x_train, train_data,
- epochs=5,
- batch_size=batch_size,
- validation_data=(x_test, test_data)
- )
- #6. IMAGE ARRAY (Predict using a test image)
- img = x_test[0]
- img_array = np.expand_dims(img, axis=0)
- #7. MODEL PREDICTION
- pred = model.predict(img_array)
- pred_class = np.argmax(pred, axis=1)[0]
- #8. LABEL PRINT
- print("Predicted label:", pred_class)
Advertisement
Add Comment
Please, Sign In to add comment