def main(): args = create_parser(usage).parse_args() args.tags_file = abspath(args.tags_file) if args.tags_file else None args.folder = abspath(args.folder) args.output_folder = abspath(args.output_folder) noise_min, noise_max = args.noise_ratio_low, args.noise_ratio_high data = TrainData.from_both(args.tags_file, args.folder, args.folder) noise_data = NoiseData(args.noise_folder) print('Data:', data) def translate_filename(source: str, n=0) -> str: assert source.startswith(args.folder) relative_file = source[len(args.folder):].strip(os.path.sep) if n > 0: base, ext = splitext(relative_file) relative_file = base + '.' + str(n) + ext return join(args.output_folder, relative_file) all_filenames = sum(data.train_files + data.test_files, []) for i, filename in enumerate(all_filenames): print('{0:.2%} \r'.format(i / (len(all_filenames) - 1)), end='', flush=True) audio = load_audio(filename) for n in range(args.inflation_factor): altered = noise_data.noised_audio( audio, noise_min + (noise_max - noise_min) * random()) output_filename = translate_filename(filename, n) makedirs(dirname(output_filename), exist_ok=True) save_audio(output_filename, altered) print('Done!') if args.tags_file and args.tags_file.startswith(args.folder): shutil.copy2(args.tags_file, translate_filename(args.tags_file))
def __init__(self, args): super().__init__(args) self.audio_buffer = np.zeros(pr.buffer_samples, dtype=float) self.vals_buffer = np.zeros(pr.buffer_samples, dtype=float) params = ModelParams(skip_acc=args.no_validation, extra_metrics=args.extra_metrics, loss_bias=1.0 - args.sensitivity) self.model = create_model(args.model, params) self.listener = Listener('', args.chunk_size, runner_cls=lambda x: None) from keras.callbacks import ModelCheckpoint, TensorBoard checkpoint = ModelCheckpoint(args.model, monitor=args.metric_monitor, save_best_only=args.save_best) epoch_fiti = Fitipy(splitext(args.model)[0] + '.epoch') self.epoch = epoch_fiti.read().read(0, int) def on_epoch_end(_a, _b): self.epoch += 1 epoch_fiti.write().write(self.epoch, str) self.model_base = splitext(self.args.model)[0] self.callbacks = [ checkpoint, TensorBoard(log_dir=self.model_base + '.logs', ), LambdaCallback(on_epoch_end=on_epoch_end) ] self.data = TrainData.from_both(args.tags_file, args.tags_folder, args.folder) pos_files, neg_files = self.data.train_files self.neg_files_it = iter(cycle(neg_files)) self.pos_files_it = iter(cycle(pos_files))
def load_data(args: Any): data = TrainData.from_tags(args.tags_file, args.tags_folder) return data.load(True, not args.no_validation)
def main(): parser = create_parser(usage) parser.add_argument( 'models', nargs='*', help='Either Keras (.net) or TensorFlow (.pb) models to test') args = TrainData.parse_args(parser) if not args.models and not args.input_file and args.folder: args.input_file = args.folder if bool(args.models) == bool(args.input_file): parser.error('Please specify either a list of models or an input file') if not args.output_file: load_plt() # Error early if matplotlib not installed import numpy as np if args.models: data = TrainData.from_both(args.tags_file, args.tags_folder, args.folder) print('Data:', data) filenames = sum( data.train_files if args.use_train else data.test_files, []) loader = CachedDataLoader( partial(data.load, args.use_train, not args.use_train, shuffle=False)) model_data = calc_stats(args.models, loader, args.use_train, filenames) else: model_data = { name: Stats.from_np_dict(data) for name, data in np.load(args.input_file)['data'].item().items() } for name, stats in model_data.items(): print('=== {} ===\n{}\n\n{}\n'.format(name, stats.counts_str(), stats.summary_str())) if args.output_file: np.savez(args.output_file, data={ name: stats.to_np_dict() for name, stats in model_data.items() }) else: plt = load_plt() decoder = ThresholdDecoder(pr.threshold_config, pr.threshold_center) thresholds = [ decoder.encode(i) for i in np.linspace(0.0, 1.0, args.resolution)[1:-1] ] for model_name, stats in model_data.items(): x = [stats.false_positives(i) for i in thresholds] y = [stats.false_negatives(i) for i in thresholds] plt.plot(x, y, marker='x', linestyle='-', label=model_name) if args.labels: for x, y, threshold in zip(x, y, thresholds): plt.annotate('{:.4f}'.format(threshold), (x, y)) plt.legend() plt.xlabel('False Positives') plt.ylabel('False Negatives') plt.show()