Advertisement
Guest User

Untitled

a guest
Jun 26th, 2022
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.25 KB | None | 0 0
  1. # Tensorflow train one
  2. # import the necessary packages
  3. from tensorflow.keras.preprocessing.image import ImageDataGenerator
  4. from tensorflow.keras.applications import MobileNetV2
  5. from tensorflow.keras.layers import AveragePooling2D
  6. from tensorflow.keras.layers import Dropout
  7. from tensorflow.keras.layers import Flatten
  8. from tensorflow.keras.layers import Dense
  9. from tensorflow.keras.layers import Input
  10. from tensorflow.keras.models import Model
  11. from tensorflow.keras.optimizers import Adam
  12. from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
  13. from tensorflow.keras.preprocessing.image import img_to_array
  14. from tensorflow.keras.preprocessing.image import load_img
  15. from tensorflow.keras.utils import to_categorical
  16. from sklearn.preprocessing import LabelBinarizer
  17. from sklearn.model_selection import train_test_split
  18. from sklearn.metrics import classification_report
  19. from imutils import paths
  20. import matplotlib.pyplot as plt
  21. import numpy as np
  22. import os
  23.  
  24. # initialize the initial learning rate, number of epochs to train for,
  25. # and batch size
  26. INIT_LR = 1e-4
  27. EPOCHS = 5
  28. BS = 32
  29.  
  30. DIRECTORY = r"C:\Users\adamt\Downloads\Compressed\Face_Mask_BadMask\dataset"
  31. CATEGORIES = ["with_mask", "without_mask"]
  32. #CATEGORIES2 = ["p2","withmask"]
  33.  
  34. # grab the list of images in our dataset directory, then initialize
  35. # the list of data (i.e., images) and class images
  36. print("[INFO] loading images...")
  37.  
  38. data = []
  39. labels = []
  40.  
  41. for category in CATEGORIES:
  42.     path = os.path.join(DIRECTORY, category)
  43.     for img in os.listdir(path):
  44.         img_path = os.path.join(path, img)
  45.         image = load_img(img_path, target_size=(226, 226))
  46.         image = img_to_array(image)
  47.         image = preprocess_input(image)
  48.  
  49.         data.append(image)
  50.         labels.append(category)
  51.  
  52. # perform one-hot encoding on the labels
  53. lb = LabelBinarizer()
  54. labels = lb.fit_transform(labels)
  55. labels = to_categorical(labels)
  56.  
  57. data = np.array(data, dtype="float32")
  58. labels = np.array(labels)
  59.  
  60. (trainX, testX, trainY, testY) = train_test_split(data, labels,
  61.     test_size=0.20, stratify=labels, random_state=42)
  62.  
  63. # construct the training image generator for data augmentation
  64. aug = ImageDataGenerator(
  65.     rotation_range=20,
  66.     zoom_range=0.02,
  67.     width_shift_range=0.02,
  68.     height_shift_range=0.02,
  69.     shear_range=0.2,
  70.     horizontal_flip=False,
  71.     fill_mode="nearest")
  72.  
  73. # Save Augmented Photos
  74. # i = 0
  75. # for batch in dataGen.flow_from_directory(directory=path,
  76. #                                         batch_size=2,
  77. #                                         save_to_dir=r'C:\Users\adamt\Desktop\dataset\New_one_pence_two_Pence\2',
  78. #                                         save_prefix='Coins_agumented_from_trainer_2',
  79. #                                         target_size=(224, 224),
  80. #                                         save_format='png'):
  81. #
  82. #    i += 1
  83. #    print(i, "i")
  84. #    if i > 31:
  85. #        break
  86.  
  87. # load the MobileNetV2 network, ensuring the head FC layer sets are
  88. # left off
  89. baseModel = MobileNetV2(weights="imagenet", include_top=False,
  90.     input_tensor=Input(shape=(226,226,3)))
  91.  
  92. # construct the head of the model that will be placed on top of the
  93. # the base model
  94. headModel = baseModel.output
  95. headModel = AveragePooling2D(pool_size=(7, 7))(headModel)
  96. headModel = Flatten(name="flatten")(headModel)
  97. headModel = Dense(128, activation="relu")(headModel)
  98. headModel = Dropout(0.5)(headModel)
  99. headModel = Dense(2, activation="softmax")(headModel)
  100.  
  101. # place the head FC model on top of the base model (this will become
  102. # the actual model we will train)
  103. model = Model(inputs=baseModel.input, outputs=headModel)
  104.  
  105. # loop over all layers in the base model and freeze them so they will
  106. # *not* be updated during the first training process
  107. for layer in baseModel.layers:
  108.     layer.trainable = False
  109.  
  110. # compile our model
  111. print("[INFO] compiling model...")
  112. opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
  113. model.compile(loss="binary_crossentropy", optimizer=opt,
  114.     metrics=["accuracy"])
  115.  
  116. # train the head of the network
  117. print("[INFO] training head...")
  118. H = model.fit(
  119.     aug.flow(trainX, trainY, batch_size=BS),
  120.     steps_per_epoch=len(trainX) // BS,
  121.     validation_data=(testX, testY),
  122.     validation_steps=len(testX) // BS,
  123.     epochs=EPOCHS)
  124.  
  125. # make predictions on the testing set
  126. print("[INFO] evaluating network...")
  127. predIdxs = model.predict(testX, batch_size=BS)
  128.  
  129. # for each image in the testing set we need to find the index of the
  130. # label with corresponding largest predicted probability
  131. predIdxs = np.argmax(predIdxs, axis=1)
  132.  
  133. # show a nicely formatted classification report
  134. print(classification_report(testY.argmax(axis=1), predIdxs,
  135.     target_names=lb.classes_))
  136.  
  137. # serialize the model to disk
  138. print("[INFO] saving mask detector model...")
  139. model.save("Face_no_mask_with_mask", save_format="h5")
  140.  
  141. # plot the training loss and accuracy
  142. N = EPOCHS
  143. plt.style.use("ggplot")
  144. plt.figure()
  145. plt.plot(np.arange(0, N), H.history["loss"], label="train_loss")
  146. plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")
  147. plt.plot(np.arange(0, N), H.history["accuracy"], label="train_acc")
  148. plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_acc")
  149. plt.title("Training Loss and Accuracy")
  150. plt.xlabel("Epoch #")
  151. plt.ylabel("Loss/Accuracy")
  152. plt.legend(loc="lower left")
  153. plt.savefig("plot.png")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement