stronk_8s

CNN Keras

Nov 24th, 2025 (edited)
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | Source Code | 0 0
  1. #1. IMPORT FILE
  2. import keras
  3. from keras import Sequential
  4. from keras.layers import Conv2D, Dense, Dropout, MaxPooling2D, Flatten
  5. from keras.preprocessing import image
  6. import numpy as np
  7.  
  8. #2. IMPORT MNIST DATASET
  9. (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
  10.  
  11. # Expand dimensions for CNN (28x28x1)
  12. x_train = np.expand_dims(x_train, axis=-1)
  13. x_test  = np.expand_dims(x_test, axis=-1)
  14.  
  15. #3. NORMALIZATION
  16. x_train = x_train.astype("float32") / 255.0
  17. x_test  = x_test.astype("float32") / 255.0
  18.  
  19. # Convert to keras dataset batches
  20. train_ds = keras.utils.image_dataset_from_directory  # dummy reference to match structure
  21. train_ds = keras.utils.Sequence      # not used but kept to avoid structural change
  22.  
  23. # Manual batching
  24. batch_size = 32
  25. train_data = keras.utils.to_categorical(y_train, num_classes=10)
  26. test_data  = keras.utils.to_categorical(y_test, num_classes=10)
  27.  
  28. #4. MODEL CREATION
  29. model = Sequential([
  30.     Conv2D(32, (5, 5), activation="relu", padding="same", input_shape=(28, 28, 1)),
  31.     MaxPooling2D(padding="same"),
  32.     Conv2D(64, (5, 5), activation="relu", padding="same"),
  33.     MaxPooling2D(padding="same"),
  34.     Flatten(),
  35.     Dense(1024, activation="relu"),
  36.     Dropout(0.2),
  37.     Dense(10, activation="softmax")  # 10 for MNIST 0–9 digits
  38. ])
  39.  
  40. # OPTIONAL
  41. # model.summary()
  42.  
  43. #5. MODEL COMPILE AND TRAINING
  44. model.compile(
  45.     optimizer="adam",
  46.     loss="categorical_crossentropy",
  47.     metrics=["accuracy"]
  48. )
  49.  
  50. model.fit(
  51.     x_train, train_data,
  52.     epochs=5,
  53.     batch_size=batch_size,
  54.     validation_data=(x_test, test_data)
  55. )
  56.  
  57. #6. IMAGE ARRAY (Predict using a test image)
  58. img = x_test[0]
  59. img_array = np.expand_dims(img, axis=0)
  60.  
  61. #7. MODEL PREDICTION
  62. pred = model.predict(img_array)
  63. pred_class = np.argmax(pred, axis=1)[0]
  64.  
  65. #8. LABEL PRINT
  66. print("Predicted label:", pred_class)
  67.  
Advertisement
Add Comment
Please, Sign In to add comment