training_utils.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. import tensorflow as tf
  3. def validate_training_data(data_path):
  4. """
  5. Validate if the training data exists and is in the correct format.
  6. """
  7. if not os.path.exists(data_path):
  8. raise FileNotFoundError(f"Training data path {data_path} does not exist.")
  9. # Example validation logic (This can be more complex depending on your data structure)
  10. if not os.listdir(data_path):
  11. raise ValueError(f"No training data found in {data_path}.")
  12. # Further validation can be added here
  13. def train_hotword_model(data_path, model_path):
  14. """
  15. Train a TensorFlow model for hotword detection.
  16. """
  17. validate_training_data(data_path)
  18. # Load and preprocess data (this should be replaced with actual data loading logic)
  19. train_data, train_labels = load_data(data_path)
  20. # Create and compile the model
  21. model = tf.keras.Sequential([
  22. tf.keras.layers.Input(shape=(16000, 1)),
  23. tf.keras.layers.Conv1D(8, 13, strides=2, activation='relu'),
  24. tf.keras.layers.Conv1D(16, 11, strides=2, activation='relu'),
  25. tf.keras.layers.Conv1D(32, 9, strides=2, activation='relu'),
  26. tf.keras.layers.Conv1D(64, 7, strides=2, activation='relu'),
  27. tf.keras.layers.GlobalAveragePooling1D(),
  28. tf.keras.layers.Dense(1, activation='sigmoid')
  29. ])
  30. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  31. # Train the model
  32. model.fit(train_data, train_labels, epochs=10, batch_size=32)
  33. # Save the model
  34. converter = tf.lite.TFLiteConverter.from_keras_model(model)
  35. tflite_model = converter.convert()
  36. with open(model_path, "wb") as f:
  37. f.write(tflite_model)
  38. return model_path
  39. def load_data(data_dir):
  40. """
  41. Load training data from the specified directory.
  42. This is a placeholder function and should be replaced with actual data loading logic.
  43. """
  44. import numpy as np
  45. train_data = np.random.rand(100, 16000, 1)
  46. train_labels = np.random.randint(2, size=100)
  47. return train_data, train_labels