stronk_8s

CNN CODE WITH STEP

Sep 17th, 2025 (edited)
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.38 KB | Source Code | 0 0
  1. #1. IMPORT FILE
  2. import tensorflow as tf
  3. from tensorflow import keras
  4. from tensorflow.keras import Sequential
  5. from tensorflow.keras.layers import Conv2D, Dense, Dropout, MaxPooling2D, Flatten
  6. from tensorflow.keras.preprocessing import image
  7. import numpy as np
  8.  
  9. #2. IMPORT IMAGE DATASET
  10. train_ds, val_ds = keras.utils.image_dataset_from_directory(
  11.     "E:/Maroon/College/S9/DL/Fonts",
  12.     color_mode="grayscale",
  13.     image_size=(28, 28),
  14.     validation_split=0.2,
  15.     subset="both",
  16.     seed=1337
  17. )
  18.  
  19. #3. VARIABLE DECLARATION
  20. def process(image,label):
  21.     image=tf.cast(image/255,tf.float32)
  22.     return image,label;
  23.    
  24. train_ds=train_ds.map(process)
  25. val_ds=val_ds.map(process)
  26.  
  27. #OR WITHOUT FUNCTION (KARVU HOY TO KARJO)
  28. #train_ds = train_ds.map(lambda x, y: (tf.cast(x, tf.float32) / 255.0, y))
  29. #val_ds   = val_ds.map(lambda x, y: (tf.cast(x, tf.float32) / 255.0, y))
  30.  
  31. #4.MODEL CREATION (SUGGESTION AVSE)
  32. model = Sequential([
  33.     Conv2D(32, (5, 5), activation="relu", padding="same", input_shape=(28, 28, 1)), #input_shape nu suggestion ni avse
  34.     MaxPooling2D(padding="same"),
  35.     Conv2D(64, (5, 5), activation="relu", padding="same"),
  36.     MaxPooling2D(padding="same"),
  37.     Flatten(),
  38.     Dense(1024, activation="relu"),
  39.     Dropout(0.2),
  40.     Dense(26, activation="sigmoid")  #CHANGE DENSE 26 ACCORDING TO THE NEED LIKE 10 FOR 0-9 NUMBERS
  41. ])
  42.  
  43. #OPTIONAL
  44. #model.summary()
  45.  
  46. #5. MODEL COMPILE AND TRAINING (SUGGESTION NI AVSE)
  47. model.compile(optimizer="adam",
  48.               loss="sparse_categorical_crossentropy",
  49.               metrics=["accuracy"])
  50. model.fit(train_ds, epochs=20, validation_data=val_ds)
  51.  
  52. #6. IMAGE ARRAY
  53. img = image.load_img("E:/Maroon/College/S9/DL/Fonts/test1.png",
  54.                      target_size=(28, 28), color_mode="grayscale")
  55. img_array = np.expand_dims(image.img_to_array(img) / 255.0, axis=0)
  56.  
  57. #6. MODEL PREDICTION
  58. pred = model.predict(img_array)
  59. pred_class = np.argmax(pred, axis=1)[0]
  60.  
  61. #7.VALUE GENERATION
  62. class_labels = [chr(i) for i in range(65, 91)]  #Auto-generate A–Z
  63. #class_labels=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]  Predefined data
  64. #class_labels = [chr(i) for i in range(65, 91)]  Auto-generate 0-9
  65. #class_labels = [str(i) for i in range(0, 101)]  Auto-generate 0 to 100
  66.  
  67. #8 PRINT
  68. print("Predicted label:", class_labels[pred_class])
Advertisement
Add Comment
Please, Sign In to add comment