Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Epoch 1/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 4s 7ms/step - accuracy: 0.4295 - loss: 25.8755
- Epoch 2/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 3s 7ms/step - accuracy: 0.9064 - loss: 0.4020
- Epoch 3/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 3s 7ms/step - accuracy: 0.9371 - loss: 0.2649
- Epoch 4/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 4s 7ms/step - accuracy: 0.9484 - loss: 0.2302
- Epoch 5/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 3s 7ms/step - accuracy: 0.9597 - loss: 0.1605
- Epoch 6/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 4s 7ms/step - accuracy: 0.9661 - loss: 0.1407
- Epoch 7/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 5s 10ms/step - accuracy: 0.9649 - loss: 0.1498
- Epoch 8/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 7s 14ms/step - accuracy: 0.9623 - loss: 0.1953
- Epoch 9/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 6s 12ms/step - accuracy: 0.9676 - loss: 0.1541
- Epoch 10/10
- 500/500 ━━━━━━━━━━━━━━━━━━━━ 6s 12ms/step - accuracy: 0.9777 - loss: 0.0983
- 333/333 - 1s - 4ms/step - accuracy: 0.9359 - loss: 0.5395
- """
- import cv2
- import numpy as np
- import os
- import sys
- import tensorflow as tf
- from pathlib import Path
- import pandas as pd
- import keras
- from sklearn.model_selection import train_test_split
- EPOCHS = 10
- IMG_WIDTH = 30
- IMG_HEIGHT = 30
- NUM_CATEGORIES = 43
- TEST_SIZE = 0.4
- def main():
- # Check command-line arguments
- if len(sys.argv) not in [2, 3]:
- sys.exit("Usage: python traffic.py data_directory [model.h5]")
- # Get image arrays and labels for all image files
- images, labels = load_data(sys.argv[1])
- # Split data into training and testing sets
- labels = tf.keras.utils.to_categorical(labels)
- x_train, x_test, y_train, y_test = train_test_split(
- np.array(images), np.array(labels), test_size=TEST_SIZE
- )
- # Get a compiled neural network
- model = get_model()
- # Train neural network
- model.compile(
- optimizer="adam",
- loss="categorical_crossentropy",
- metrics=["accuracy"]
- )
- # Fit model on training data
- model.fit(x_train, y_train, epochs=EPOCHS)
- # Evaluate neural network performance
- model.evaluate(x_test, y_test, verbose=2)
- # Save model to file
- if len(sys.argv) == 3:
- filename = sys.argv[2]
- model.save(filename)
- print(f"Model saved to {filename}.")
- def load_data(data_dir):
- """
- Load image data from directory `data_dir`.
- Assume `data_dir` has one directory named after each category, numbered
- 0 through NUM_CATEGORIES - 1. Inside each category directory will be some
- number of image files.
- Return tuple `(images, labels)`. `images` should be a list of all
- of the images in the data directory, where each image is formatted as a
- numpy ndarray with dimensions IMG_WIDTH x IMG_HEIGHT x 3. `labels` should
- be a list of integer labels, representing the categories for each of the
- corresponding `images`.
- """
- images = []
- labels = []
- for root, dirs, files in os.walk(data_dir):
- for file in files:
- if file.endswith(".ppm"):
- image_path = os.path.join(root, file)
- img = cv2.imread(image_path)
- img = cv2.resize(img, (IMG_WIDTH, IMG_HEIGHT), interpolation=cv2.INTER_AREA)
- images.append(img)
- labels.append(int(os.path.basename(root)))
- return images, labels
- def get_model():
- """
- Returns a compiled convolutional neural network model. Assume that the
- `input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
- The output layer should have `NUM_CATEGORIES` units, one for each category.
- """
- model = tf.keras.models.Sequential([
- # Convolutional layer. Learn 32 filters using a 3x3 kernel
- tf.keras.layers.Conv2D(32, (3,3), activation="relu"),
- # Max-pooling layer, using 2x2 pool size
- tf.keras.layers.MaxPooling2D(pool_size=(2,2)),
- tf.keras.layers.Flatten(),
- # Add a hidden layer with dropout
- #tf.keras.layers.Dense(128, activation="relu"),
- #tf.keras.layers.Dropout(0.5),
- # Add an output layer with output units for all 10 digits
- tf.keras.layers.Dense(NUM_CATEGORIES, activation="softmax")
- ])
- return model
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement