Advertisement
jules0707

traffic.py

Apr 12th, 2024 (edited)
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.70 KB | None | 0 0
  1. """
  2. Epoch 1/10
  3. 500/500 ━━━━━━━━━━━━━━━━━━━━ 4s 7ms/step - accuracy: 0.4295 - loss: 25.8755        
  4. Epoch 2/10
  5. 500/500 ━━━━━━━━━━━━━━━━━━━━ 3s 7ms/step - accuracy: 0.9064 - loss: 0.4020  
  6. Epoch 3/10
  7. 500/500 ━━━━━━━━━━━━━━━━━━━━ 3s 7ms/step - accuracy: 0.9371 - loss: 0.2649  
  8. Epoch 4/10
  9. 500/500 ━━━━━━━━━━━━━━━━━━━━ 4s 7ms/step - accuracy: 0.9484 - loss: 0.2302  
  10. Epoch 5/10
  11. 500/500 ━━━━━━━━━━━━━━━━━━━━ 3s 7ms/step - accuracy: 0.9597 - loss: 0.1605  
  12. Epoch 6/10
  13. 500/500 ━━━━━━━━━━━━━━━━━━━━ 4s 7ms/step - accuracy: 0.9661 - loss: 0.1407  
  14. Epoch 7/10
  15. 500/500 ━━━━━━━━━━━━━━━━━━━━ 5s 10ms/step - accuracy: 0.9649 - loss: 0.1498
  16. Epoch 8/10
  17. 500/500 ━━━━━━━━━━━━━━━━━━━━ 7s 14ms/step - accuracy: 0.9623 - loss: 0.1953
  18. Epoch 9/10
  19. 500/500 ━━━━━━━━━━━━━━━━━━━━ 6s 12ms/step - accuracy: 0.9676 - loss: 0.1541
  20. Epoch 10/10
  21. 500/500 ━━━━━━━━━━━━━━━━━━━━ 6s 12ms/step - accuracy: 0.9777 - loss: 0.0983
  22. 333/333 - 1s - 4ms/step - accuracy: 0.9359 - loss: 0.5395
  23. """
  24.  
  25.  
  26. import cv2
  27. import numpy as np
  28. import os
  29. import sys
  30. import tensorflow as tf
  31. from pathlib import Path
  32. import pandas as pd
  33. import keras
  34.  
  35. from sklearn.model_selection import train_test_split
  36.  
  37. EPOCHS = 10
  38. IMG_WIDTH = 30
  39. IMG_HEIGHT = 30
  40. NUM_CATEGORIES = 43
  41. TEST_SIZE = 0.4
  42.  
  43.  
  44. def main():
  45.  
  46.     # Check command-line arguments
  47.     if len(sys.argv) not in [2, 3]:
  48.         sys.exit("Usage: python traffic.py data_directory [model.h5]")
  49.  
  50.     # Get image arrays and labels for all image files
  51.     images, labels = load_data(sys.argv[1])
  52.  
  53.     # Split data into training and testing sets
  54.     labels = tf.keras.utils.to_categorical(labels)
  55.     x_train, x_test, y_train, y_test = train_test_split(
  56.         np.array(images), np.array(labels), test_size=TEST_SIZE
  57.     )
  58.  
  59.     # Get a compiled neural network
  60.     model = get_model()
  61.    
  62.     # Train neural network
  63.     model.compile(
  64.     optimizer="adam",
  65.     loss="categorical_crossentropy",
  66.     metrics=["accuracy"]
  67.     )
  68.    
  69.    
  70.  
  71.     # Fit model on training data
  72.     model.fit(x_train, y_train, epochs=EPOCHS)
  73.  
  74.     # Evaluate neural network performance
  75.     model.evaluate(x_test, y_test, verbose=2)
  76.  
  77.     # Save model to file
  78.     if len(sys.argv) == 3:
  79.         filename = sys.argv[2]
  80.         model.save(filename)
  81.         print(f"Model saved to {filename}.")
  82.  
  83.  
  84. def load_data(data_dir):
  85.     """
  86.    Load image data from directory `data_dir`.
  87.  
  88.    Assume `data_dir` has one directory named after each category, numbered
  89.    0 through NUM_CATEGORIES - 1. Inside each category directory will be some
  90.    number of image files.
  91.  
  92.    Return tuple `(images, labels)`. `images` should be a list of all
  93.    of the images in the data directory, where each image is formatted as a
  94.    numpy ndarray with dimensions IMG_WIDTH x IMG_HEIGHT x 3. `labels` should
  95.    be a list of integer labels, representing the categories for each of the
  96.    corresponding `images`.
  97.    """
  98.     images = []
  99.     labels = []
  100.  
  101.     for root, dirs, files in os.walk(data_dir):
  102.         for file in files:
  103.             if file.endswith(".ppm"):
  104.                 image_path = os.path.join(root, file)
  105.                 img = cv2.imread(image_path)
  106.                 img = cv2.resize(img, (IMG_WIDTH, IMG_HEIGHT), interpolation=cv2.INTER_AREA)
  107.                 images.append(img)
  108.                 labels.append(int(os.path.basename(root)))
  109.  
  110.     return images, labels
  111.  
  112.  
  113.  
  114. def get_model():
  115.     """
  116.    Returns a compiled convolutional neural network model. Assume that the
  117.    `input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
  118.    The output layer should have `NUM_CATEGORIES` units, one for each category.
  119.    """
  120.     model = tf.keras.models.Sequential([
  121.  
  122.         # Convolutional layer. Learn 32 filters using a 3x3 kernel
  123.         tf.keras.layers.Conv2D(32, (3,3), activation="relu"),
  124.        
  125.         # Max-pooling layer, using 2x2 pool size
  126.         tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
  127.        
  128.         tf.keras.layers.Flatten(),
  129.                
  130.         # Add a hidden layer with dropout
  131.         #tf.keras.layers.Dense(128, activation="relu"),
  132.         #tf.keras.layers.Dropout(0.5),
  133.  
  134.     # Add an output layer with output units for all 10 digits
  135.     tf.keras.layers.Dense(NUM_CATEGORIES, activation="softmax")
  136.                    
  137.     ])
  138.        
  139.     return model
  140.  
  141.  
  142. if __name__ == "__main__":
  143.     main()
  144.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement