Advertisement
Guest User

Untitled

a guest
Jun 26th, 2022
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.60 KB | None | 0 0
  1. #Tensorflow training two
  2.  
  3. import warnings
  4.  
  5. warnings.filterwarnings('ignore')
  6.  
  7. import cv2
  8. import numpy as np
  9. import os
  10. import matplotlib.pyplot as plt
  11. from sklearn.model_selection import train_test_split
  12. from keras.preprocessing.image import ImageDataGenerator
  13. from keras.utils.np_utils import to_categorical
  14. from keras.models import Sequential
  15. from keras.layers import Conv2D, Dense, MaxPooling2D, Activation, Dropout, Flatten
  16. from tensorflow.keras.optimizers import Adam
  17. import mplcursors
  18. from tensorflow.keras.applications import MobileNetV2
  19. from tensorflow.keras.layers import Input
  20. from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
  21. ########################################
  22.  
  23. path = r'C:\Users\adamt\Desktop\archive'
  24.  
  25. # Saves the Photos that the data gen generates to view before training
  26. # This could cause issues so I left the original code in its original place
  27.  
  28. brightness = [0.1, 0.5]
  29. width = [0.01, 0.05]
  30. height = [0.01, 0.05]
  31.  
  32.  
  33.  
  34. images = []
  35. classNo = []
  36. testRatio = 0.2
  37. valRatio = 0.2
  38. imgDimension = (167, 167, 3)  # 1 is Black and white, 3 is RGB
  39. img_counter = 0
  40. #########################################
  41.  
  42. myList = os.listdir(path)
  43.  
  44. numOfClasses = len(myList)
  45.  
  46. print(numOfClasses)
  47.  
  48. print("Importing Classes..........")
  49. for x in range(0, numOfClasses):
  50.     myPicList = os.listdir(path + "/" + str(x))
  51.     # myData/0/img.jpg # Not sure what this does
  52.     for y in myPicList:
  53.         curImg = cv2.imread(path + "/" + str(x) + "/" + y)
  54.         curImg = cv2.resize(curImg, (imgDimension[0], imgDimension[1]))
  55.         images.append(curImg)
  56.         classNo.append(x)
  57.     print(x, "X")
  58.  
  59. images = np.array(images)
  60. classNo = np.array(classNo)
  61.  
  62. #########Spliting The Data###########
  63.  
  64. x_train, x_test, y_train, y_test = train_test_split(images, classNo, test_size=testRatio)
  65. x_train, x_validation, y_train, y_validation = train_test_split(x_train, y_train, test_size=valRatio)
  66.  
  67. print(x_train.shape)
  68. #print(x_validation,"x_validation")
  69. #print(y_validation,"y_validation")
  70. #print(testRatio,"test Ratio")
  71. numOfSample = []
  72.  
  73. for x in range(0, numOfClasses):
  74.     numOfSample.append(len(np.where(y_train == x)[0]))
  75.  
  76. plt.figure(figsize=(10, 5))
  77. plt.bar(range(0, numOfClasses), numOfSample)
  78. # print(numOfSample,"number of samples")
  79. plt.title("Bar Plot of Classes & Images")
  80. plt.xlabel("No Of Classes")
  81. plt.ylabel("No of Images")
  82. mplcursors.cursor(hover=True)  # Hover over bar charts tells you how many photos are being used(y)
  83. plt.show()
  84.  
  85.  
  86. def preprocessing(img):
  87.     # img=np.astype("uint8")
  88.     img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  89.     #cv2.imshow("v",img)
  90.     img = cv2.equalizeHist(img)
  91.     img = img / 255
  92.     return img
  93.  
  94.  
  95. x_train = np.array(list(map(preprocessing, x_train)))
  96. x_test = np.array(list(map(preprocessing, x_test)))
  97. x_validation = np.array(list(map(preprocessing, x_validation)))
  98.  
  99. x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1)
  100. x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], 1)
  101. x_validation = x_validation.reshape(x_validation.shape[0], x_validation.shape[1], x_validation.shape[2], 1)
  102.  
  103. # brightness = [0.1, 0.5]
  104. # width = [0.01, 0.05]
  105. # height = [0.01, 0.05]
  106.  
  107. dataGen = ImageDataGenerator(
  108.     featurewise_center=True,
  109.     featurewise_std_normalization=True,
  110.     rotation_range=20,
  111.     width_shift_range=0.02,
  112.     height_shift_range=0.02,
  113.     horizontal_flip=True,
  114.     brightness_range=brightness,
  115.     validation_split=0.90)
  116.  
  117. # Save Augmented Photos
  118. # i = 0
  119. # for batch in dataGen.flow_from_directory(directory=path,
  120. #                                         batch_size=2,
  121. #                                         save_to_dir=r'C:\Users\adamt\Desktop\dataset\New_one_pence_two_Pence\2',
  122. #                                         save_prefix='Coins_agumented_from_trainer_2',
  123. #                                         target_size=(224, 224),
  124. #                                         save_format='png'):
  125. #
  126. #    i += 1
  127. #    print(i, "i")
  128. #    if i > 31:
  129. #        break
  130.  
  131. y_train = to_categorical(y_train, numOfClasses)
  132. y_test = to_categorical(y_test, numOfClasses)
  133. y_validation = to_categorical(y_validation, numOfClasses)
  134.  
  135. baseModel = MobileNetV2(weights="imagenet", include_top=False,
  136.     input_tensor=Input(shape=(128,129,3)))
  137.  
  138. def myModel():
  139.     sizeOfFilter1 = (3, 3)
  140.     sizeOfFilter2 = (3, 3)
  141.     sizeOfPool = (2, 2)
  142.  
  143.     model = Sequential()
  144.     model.add((Conv2D(32, sizeOfFilter1, input_shape=(imgDimension[0], imgDimension[1], 1), activation='relu')))
  145.     model.add((Conv2D(32, sizeOfFilter1, activation='relu')))
  146.     model.add(MaxPooling2D(pool_size=sizeOfPool))
  147.  
  148.     model.add((Conv2D(64, sizeOfFilter2, activation='relu')))
  149.     model.add((Conv2D(64, sizeOfFilter2, activation='relu')))
  150.     model.add(MaxPooling2D(pool_size=sizeOfPool))
  151.     model.add(Dropout(0.8))  # Changed from 0.5 to 0.8
  152.  
  153.     model.add(Flatten())
  154.     model.add(Dense(64, activation='relu'))
  155.     model.add(Dropout(0.5))
  156.     model.add(Dense(numOfClasses, activation='softmax'))
  157.     model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
  158.     return model
  159.  
  160.  
  161. model = myModel()
  162. print(model.summary())
  163.  
  164. history = model.fit_generator(dataGen.flow(x_train, y_train, batch_size=32),
  165.                               steps_per_epoch=100,
  166.                               # https://chowdera.com/2022/01/202201090452117647.html amount of images divided by
  167.                               # batch size, only need to do for 1 folder
  168.                               epochs=5, validation_data=(x_validation, y_validation), shuffle=250)
  169. model.save("Eye_Detector_100_Train.h5")
  170.  
  171.  
  172.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement