Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.28 KB | None | 0 0
  1. # USAGE
  2. # python train_simple_nn.py --dataset animals --model output/simple_nn.model --label-bin output/simple_nn_lb.pickle --plot output/simple_nn_plot.png
  3.  
  4. # set the matplotlib backend so figures can be saved in the background
  5. import matplotlib
  6. matplotlib.use("Agg")
  7.  
  8. # import the necessary packages
  9. from sklearn.preprocessing import LabelBinarizer
  10. from sklearn.model_selection import train_test_split
  11. from sklearn.metrics import classification_report
  12. from keras.models import Sequential
  13. from keras.layers.core import Dense
  14. from keras.optimizers import SGD
  15. from imutils import paths
  16. import matplotlib.pyplot as plt
  17. import numpy as np
  18. import argparse
  19. import random
  20. import pickle
  21. import cv2
  22. import os
  23. from keras import layers
  24. import tensorflow as tf
  25.  
  26. # construct the argument parser and parse the arguments
  27. ap = argparse.ArgumentParser()
  28. ap.add_argument("-d", "--dataset", required=True,
  29.     help="path to input dataset of images")
  30. ap.add_argument("-m", "--model", required=True,
  31.     help="path to output trained model")
  32. ap.add_argument("-l", "--label-bin", required=True,
  33.     help="path to output label binarizer")
  34. ap.add_argument("-p", "--plot", required=True,
  35.     help="path to output accuracy/loss plot")
  36. args = vars(ap.parse_args())
  37.  
  38. # initialize the data and labels
  39. print("[INFO] loading images...")
  40. data = []
  41. labels = []
  42.  
  43. # grab the image paths and randomly shuffle them
  44. imagePaths = sorted(list(paths.list_images(args["dataset"])))
  45. random.seed(42)
  46. random.shuffle(imagePaths)
  47.  
  48. # loop over the input images
  49. for imagePath in imagePaths:
  50.     # load the image, resize the image to be 32x32 pixels (ignoring
  51.     # aspect ratio), flatten the image into 32x32x3=3072 pixel image
  52.     # into a list, and store the image in the data list
  53.     image = cv2.imread(imagePath)
  54.     image = cv2.resize(image, (32, 32)).flatten()
  55.     data.append(image)
  56.  
  57.     # extract the class label from the image path and update the
  58.     # labels list
  59.     label = imagePath.split(os.path.sep)[-2]
  60.     labels.append(label)
  61.  
  62. # scale the raw pixel intensities to the range [0, 1]
  63. data = np.array(data, dtype="float") / 255.0
  64. labels = np.array(labels)
  65.  
  66. # partition the data into training and testing splits using 75% of
  67. # the data for training and the remaining 25% for testing
  68. (trainX, testX, trainY, testY) = train_test_split(data,
  69.     labels, test_size=0.25, random_state=42)
  70.  
  71. # convert the labels from integers to vectors (for 2-class, binary
  72. # classification you should use Keras' to_categorical function
  73. # instead as the scikit-learn's LabelBinarizer will not return a
  74. # vector)
  75. lb = LabelBinarizer()
  76. trainY = lb.fit_transform(trainY)
  77. testY = lb.transform(testY)
  78.  
  79. # define the 3072-1024-512-3 architecture using Keras
  80. model = tf.keras.Sequential()
  81. tf.keras.layers.Dense(1024, input_shape=(3072,), activation="sigmoid")
  82. tf.keras.layers.Dense(512, activation="sigmoid")
  83. tf.keras.layers.Dense(len(lb.classes_), activation="softmax")
  84.  
  85. # initialize our initial learning rate and # of epochs to train for
  86. INIT_LR = 0.01
  87. EPOCHS = 75
  88.  
  89. # compile the model using SGD as our optimizer and categorical
  90. # cross-entropy loss (you'll want to use binary_crossentropy
  91. # for 2-class classification)
  92. print("[INFO] training network...")
  93. opt = tf.keras.optimizers.SGD(lr=INIT_LR)
  94. model.compile(loss="categorical_crossentropy", optimizer=opt,
  95.     metrics=["accuracy"])
  96.  
  97. # train the neural network
  98. H = model.fit(trainX, trainY, validation_data=(testX, testY),
  99.     epochs=EPOCHS, batch_size=32)
  100.  
  101. # evaluate the network
  102. print("[INFO] evaluating network...")
  103. predictions = model.predict(testX, batch_size=32)
  104. print(classification_report(testY.argmax(axis=1),
  105.     predictions.argmax(axis=1), target_names=lb.classes_))
  106.  
  107. # plot the training loss and accuracy
  108. N = np.arange(0, EPOCHS)
  109. plt.style.use("ggplot")
  110. plt.figure()
  111. plt.plot(N, H.history["loss"], label="train_loss")
  112. plt.plot(N, H.history["val_loss"], label="val_loss")
  113. plt.plot(N, H.history["acc"], label="train_acc")
  114. plt.plot(N, H.history["val_acc"], label="val_acc")
  115. plt.title("Training Loss and Accuracy (Simple NN)")
  116. plt.xlabel("Epoch #")
  117. plt.ylabel("Loss/Accuracy")
  118. plt.legend()
  119. plt.savefig(args["plot"])
  120.  
  121. # save the model and label binarizer to disk
  122. print("[INFO] serializing network and label binarizer...")
  123. model.save(args["model"])
  124. f = open(args["label_bin"], "wb")
  125. f.write(pickle.dumps(lb))
  126. f.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement