code
stringlengths
17
6.64M
def compute_conv2d_ds(in_h, in_w, in_ch, out_ch, k_w, k_h): 'Complexity for Depthwise Separable\n\n $$ O_{ds} = O_pw + O_dw $$\n ' pw = compute_conv2d_pw(in_h, in_w, in_ch, out_ch) dw = compute_conv2d_dw(in_h, in_w, in_ch, k_w, k_h) return (pw + dw)
def is_training_scope(scope): patterns = ('/random_uniform', '/weight_regularizer', '/dropout_', '/dropout/', 'AssignMovingAvg') is_training = False for t in patterns: if (t in scope): is_training = True return is_training
def analyze_model(build_func, input_shapes, n_classes): from tensorflow.python.framework import graph_util import tensorflow.python.framework.ops as ops from tensorflow.compat.v1.graph_util import remove_training_nodes from tensorflow.python.tools import optimize_for_inference_lib g = tf.Graph() ...
def layer_info(model): df = pandas.DataFrame({'name': [l.name for l in model.layers], 'type': [l.__class__.__name__ for l in model.layers], 'shape_in': [l.get_input_shape_at(0)[1:] for l in model.layers], 'shape_out': [l.get_output_shape_at(0)[1:] for l in model.layers]}) df['size_in'] = df.shape_in.apply(num...
def stm32layer_sizes(stats): activation_types = set(['_output_array', '_output_in_array', '_output_out_array']) weight_types = set(['_weights_array', '_bias_array', '_scale_array']) array_types = activation_types.union(weight_types) def lazy_add(d, key, value): if (d.get(key, None) is None): ...
def model_info(model): with tempfile.TemporaryDirectory(prefix='microesc') as tempdir: out_dir = tempdir if (type(model) == str): model_path = model model = keras.models.load_model(model_path) else: model_path = os.path.join(out_dir, 'model.hd5f') ...
def check_model_constraints(model, max_ram=64000.0, max_maccs=(4500000.0 * 0.72), max_flash=512000.0): (stats, combined) = model_info(model) def check(val, limit, message): assert (val <= limit), message.format(val, limit) check(stats['flash_usage'], max_flash, 'FLASH use too high: {} > {}') ...
def main(): sample_rate = 44100 window_stride_ms = 10 def build_speech_tiny(): return speech.build_tiny_conv(input_frames=frames, input_bins=bands, n_classes=10) models = {'SB-CNN': (sbcnn.build_model, [(128, 128, 1)])} model_params = {} model_flops = {} model_stats = {name: analy...
def generate_config(model_path, out_path, name='network', model_type='keras', compression=None): data = {'name': name, 'toolbox': model_options[model_type], 'models': {'1': [model_path, ''], '2': [model_path, ''], '3': [model_path, ''], '4': [model_path]}, 'compression': compression, 'pinnr_path': out_path, 'src_...
def parse_with_unit(s): (number, unit) = s.split() number = float(number) multipliers = {'KBytes': 1000.0, 'MBytes': 1000000.0} mul = multipliers[unit] return (number * mul)
def extract_stats(output): regex = ' ([^:]*):(.*)' out = {} matches = re.finditer(regex, output.decode('utf-8'), re.MULTILINE) for (i, match) in enumerate(matches, start=1): (key, value) = match.groups() key = key.strip() value = value.strip() if (key == 'MACC / frame'...
def test_ram_use(): examples = [('\n AI_ARRAY_OBJ_DECLARE(\n input_1_output_array, AI_DATA_FORMAT_FLOAT, \n NULL, NULL, 1860,\n AI_STATIC)\n AI_ARRAY_OBJ_DECLARE(\n conv2d_1_output_array, AI_DATA_FORMAT_FLOAT, \n NULL, NULL, 29760,\n AI_STATIC)\n ', {'input_1_output_array': ...
def extract_ram_use(str): regex = 'AI_ARRAY_OBJ_DECLARE\\(([^)]*)\\)' matches = re.finditer(regex, str, re.MULTILINE) out = {} for (i, match) in enumerate(matches): (items,) = match.groups() items = [i.strip() for i in items.split(',')] (name, format, _, _, size, modifiers) = i...
def generatecode(model_path, out_path, name, model_type, compression): home = str(pathlib.Path.home()) version = os.environ.get('XCUBEAI_VERSION', '3.4.0') platform_name = platform.system().lower() if (platform_name == 'darwin'): platform_name = 'mac' p = 'STM32Cube/Repository/Packs/STMicr...
def parse(): parser = argparse.ArgumentParser(description='Process some integers.') a = parser.add_argument supported_types = '|'.join(model_options.keys()) a('model', metavar='PATH', type=str, help='The model to convert') a('out', metavar='DIR', type=str, help='Where to write generated output') ...
def main(): args = parse() test_ram_use() stats = generatecode(args.model, args.out, name=args.name, model_type=args.type, compression=args.compression) print('Wrote model to', args.out) print('Model status: ', json.dumps(stats))
def load_model_info(jobs_dir, job_dir): (experiment, date, time, rnd, fold) = job_dir.split('-') hist_path = os.path.join(jobs_dir, job_dir, 'train.csv') df = pandas.read_csv(hist_path) df['epoch'] = (df.epoch + 1) df['fold'] = int(fold.lstrip('fold')) df['experiment'] = experiment df['run...
def load_train_history(jobs_dir, limit=None): jobs = os.listdir(jobs_dir) if limit: matching = [d for d in jobs if (limit in d)] else: matching = jobs dataframes = [] for job_dir in matching: try: df = load_model_info(jobs_dir, job_dir) except (FileNotFo...
def test_load_history(): jobs_dir = '../../jobs' job_id = 'sbcnn44k128aug-20190227-0220-48ba' df = load_history()
def pick_best(history, n_best=1): def best_by_loss(df): return df.sort_values('voted_val_acc', ascending=False).head(n_best) return history.groupby(['experiment', 'fold']).apply(best_by_loss)
def evaluate_model(predictor, model_path, val_data, test_data): def score(model, data): y_true = data.classID p = predictor(model, data) y_pred = numpy.argmax(p, axis=1) acc = sklearn.metrics.accuracy_score(y_true, y_pred) labels = list(range(len(urbansound8k.classnames)))...
def evaluate(models, folds_data, predictor, out_dir, dry_run=False): def eval_experiment(df): results = {} by_fold = df.sort_index(level='fold', ascending=True) for (idx, row) in by_fold.iterrows(): fold = row['fold'] assert (fold > 0), 'fold number should be 1 ind...
def parse(args): import argparse parser = argparse.ArgumentParser(description='Test trained models') a = parser.add_argument common.add_arguments(parser) a('--run', dest='run', default='', help='%(default)s') a('--check', action='store_true', default='', help='Run a check pass, not actually ev...
def main(): args = parse(sys.argv[1:]) out_dir = os.path.join(args.results_dir, args.run) common.ensure_directories(out_dir) urbansound8k.maybe_download_dataset(args.datasets_dir) data = urbansound8k.load_dataset() folds = urbansound8k.folds(data) exsettings = common.load_settings_path(arg...
def maybe_download_dataset(workdir): if (not os.path.exists(workdir)): os.makedirs(workdir) dir_path = os.path.join(workdir, 'UrbanSound8K') archive_path = (dir_path + '.tar.gz') last_progress = None def download_progress(count, blocksize, totalsize): nonlocal last_progress ...
def load_dataset(): metadata_path = os.path.join(here, 'datasets/UrbanSound8K.csv') samples = pandas.read_csv(metadata_path) return samples
def sample_path(sample, dataset_path=None): if (not dataset_path): dataset_path = default_path return os.path.join(dataset_path, 'audio', ('fold' + str(sample.fold)), sample.slice_file_name)
def folds(data): fold_idxs = folds_idx(n_folds=10) assert (len(fold_idxs) == 10) folds = [] for fold in fold_idxs: (train, val, test) = fold train = (numpy.array(train) + 1) val = (numpy.array(val) + 1) test = (numpy.array(test) + 1) fold_train = data[data.fold....
def ensure_valid_fold(fold, n_folds=10): (train, val, test) = fold assert (len(train) == (n_folds - 2)), len(train) assert (0 <= train[0] < n_folds), train[0] assert (len(val) == 1), len(val) assert (0 <= val[0] < n_folds), val[0] assert (len(test) == 1), len(test) assert (0 <= test[0] < n...
def folds_idx(n_folds): 'Generate fold indices for cross-validation.\n Each fold has 1 validation, 1 test set and the remaining train' test_fold = 10 folds = [] all_folds = list(range(0, n_folds)) for idx in range(0, n_folds): test = [all_folds[idx]] val = [all_folds[(idx - 1)]]...
def sbcnn_generator(n_iter=400, random_state=1): from sklearn.model_selection import ParameterSampler params = dict(kernel_t=range(3, 10, 2), kernel_f=range(3, 10, 2), pool_t=range(2, 5), pool_f=range(2, 5), kernels_start=range(16, 64), fully_connected=range(16, 128)) sampler = ParameterSampler(params, n_...
def generate_models(): gen = sbcnn_generator() data = {'model_path': [], 'gen_path': [], 'id': []} for out in iter(gen): model = None try: (params, settings) = out model = models.build(settings.copy()) except ValueError as e: print('Error:', e) ...
def main(): df = generate_models() df.to_csv('scan.csv')
def main(): settings = common.load_experiment('experiments', 'ldcnn20k60') def build(): return train.sb_cnn(settings) m = build() m.summary() m.save('model.wip.hdf5') s = settings shape = (s['n_mels'], s['frames'], 1) model_stats = stats.analyze_model(build, [shape], n_classes...
def check_missing(df, field, name='name'): missing = df[df[field].isna()] if len(missing): print('WARN. Missing "{}" for {}'.format(field, list(missing[name])))
def logmel_models(data_path): df = pandas.read_csv(data_path) df = df[df['features'].str.contains('logmel')] df.index = df['name'] df['params'] = (df['kparams'] * 1000.0) df['window'] = ((df.frames * df.hop) / df.samplerate) df['t_step'] = (df.hop / df.samplerate) df['f_res'] = (df.sampler...
def model_table(data_path): df = logmel_models(data_path) table = pandas.DataFrame() table['Accuracy (%)'] = (df.accuracy * 100) table['MACC / second'] = ['{} M'.format(int((v / 1000000.0))) for v in df.macc_s] table['Model parameters'] = ['{} k'.format(int((v / 1000.0))) for v in df.params] t...
def plot_models(data_path, figsize=(12, 4), max_params=128000.0, max_maccs=4500000.0): df = logmel_models(data_path) (fig, ax) = plt.subplots(1, figsize=figsize) check_missing(df, 'accuracy') check_missing(df, 'kparams') check_missing(df, 'mmacc') df.plot.scatter(x='params', y='macc_s', logx=T...
def flatten(list): out = [] for x in list: for y in x: out.append(y) return out
def plot_spectrogram(f, ax=None, cmap=None): (y, sr) = librosa.load(f, sr=44100) fig = None if (not ax): (fig, ax) = plt.subplots(1, figsize=(16, 4)) S = numpy.abs(librosa.stft(y)) S = librosa.amplitude_to_db(S, ref=numpy.max) kwargs = dict(ax=ax, y_axis='log', x_axis='time', sr=sr) ...
def plot_spectrograms(files, titles, out=None): assert (len(files) == len(titles)) (fig, axs) = plt.subplots(2, (len(files) // 2), sharex=True, figsize=(16, 6)) axs = flatten(axs) for (i, (path, title, ax)) in enumerate(zip(files, titles, axs)): plot_spectrogram(path, ax=ax) ax.set_tit...
def plot_examples(examples): examples = urbansound8k_examples here = os.path.dirname(__file__) base = os.path.join(here, '../microesc/../data/datasets/UrbanSound8K/audio/') paths = [os.path.join(base, e[0]) for e in examples.values()] fig = plot_spectrograms(paths, examples.keys()) return fig
def main(): plotname = os.path.basename(sys.argv[1]) here = os.path.dirname(__file__) plot_func = plots.get(plotname, None) if (not plot_func): sys.stderr.write('Plot {} not found. Supported: \n{}'.format(plotname, plots.keys())) return 1 out = plot_func() out_path = os.path.jo...
def strformat(fmt, series): return [fmt.format(i) for i in series]
def downsample_from_name(name): if name.startswith('Stride'): return 'stride' else: return 'maxpool'
def accuracies(df, col): mean = (df[(col + '_mean')] * 100) std = (df[(col + '_std')] * 100) fmt = ['{:.1f}% +-{:.1f}'.format(*t) for t in zip(mean, std)] return fmt
def cpu_use(df): usage = (((df.utilization * 1000) * 1) / df.classifications_per_second).astype(int) return ['{:d} ms'.format(i).ljust(3) for i in usage]
def plot_augmentations(y, sr, time_shift=3000, pitch_shift=12, time_stretch=1.3): augmentations = {'Original': y, 'Timeshift left': y[time_shift:], 'Timeshift right': numpy.concatenate([numpy.zeros(time_shift), y[:(- time_shift)]]), 'Timestretch faster': librosa.effects.time_stretch(y, time_stretch), 'Timestretch...
def main(): path = '163459__littlebigsounds__lbs-fx-dog-small-alert-bark001.wav' (y, sr) = librosa.load(path, offset=0.1, duration=1.2) fig = plot_augmentations(y, sr) out = __file__.replace('.py', '.png') fig.savefig(out, bbox_inches='tight')
def bandpass_filter(lowcut, highcut, fs, order, output='sos'): assert ((order % 2) == 0), 'order must be multiple of 2' assert ((highcut * 0.95) < (fs / 2.0)), 'highcut {} above Nyquist for fs={}'.format(highcut, fs) assert (lowcut > 0.0), 'lowcut must be above 0' nyq = (0.5 * fs) low = (lowcut / ...
def filterbank(center, fraction, fs, order): reference = acoustics.octave.REFERENCE center = [f for f in center if (f < (fs / 2.0))] center = numpy.asarray(center) indices = acoustics.octave.index_of_frequency(center, fraction=fraction, ref=reference) center = acoustics.octave.exact_center_frequen...
def third_octave_filterbank(fs, order=8): from acoustics.standards import iec_61672_1_2013 as iec_61672 center = iec_61672.NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES return filterbank(center, fraction=3, fs=fs, order=order)
def plot_filterbank_oct(ax, fs=44100): filterbank = third_octave_filterbank((fs / 2)) for (center, sos) in zip(filterbank[0], filterbank[1]): (w, h) = scipy.signal.sosfreqz(sos, worN=4096, fs=fs) db = (20 * numpy.log10((numpy.abs(h) + 1e-09))) ax.plot(w, db) ax.set_title('1/3 octav...
def plot_filterbank_gammatone(ax, fs=44100): np = numpy from pyfilterbank import gammatone gfb = gammatone.GammatoneFilterbank(samplerate=44100, startband=(- 6), endband=26, density=1.5) def plotfun(x, y): xx = (x * fs) ax.plot(xx, (20 * np.log10((np.abs(y) + 1e-09)))) gfb.freqz(n...
def plot_filterbank_mel(ax, n_mels=32, n_fft=4097, fmin=10, fmax=22050, fs=44100): from pyfilterbank import melbank (melmat, (melfreq, fftfreq)) = melbank.compute_melmat(n_mels, fmin, fmax, num_fft_bands=4097, sample_rate=fs) ax.plot(fftfreq, (20 * numpy.log10((melmat.T + 1e-09)))) ax.set_title('Mel-s...
def main(): (fig, (gt_ax, oct_ax, mel_ax)) = plt.subplots(3, sharex=True, sharey=True, figsize=(12, 5)) axes = fig.gca() plot_filterbank_gammatone(gt_ax) plot_filterbank_mel(mel_ax) plot_filterbank_oct(oct_ax) axes.set_ylim([(- 40), 3]) axes.set_xlim([100, 20000]) fig.tight_layout() ...
def plot_logloss(figsize=(6, 3)): (fig, ax) = plt.subplots(1, figsize=figsize) yhat = numpy.linspace(0.0, 1.0, 300) losses_0 = [log_loss([0], [x], labels=[0, 1]) for x in yhat] losses_1 = [log_loss([1], [x], labels=[0, 1]) for x in yhat] ax.plot(yhat, losses_0, label='true=0') ax.plot(yhat, lo...
def main(): fig = plot_logloss() fig.tight_layout() out = __file__.replace('.py', '.png') fig.savefig(out, bbox_inches='tight')
def arglist(options): args = ['--{}={}'.format(k, v) for (k, v) in options.items()] return args
def command_for_job(options): args = ['python3', 'train.py'] args += arglist(options) return args
def generate_train_jobs(experiments, settings_path, folds, overrides): timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M') unique = str(uuid.uuid4())[0:4] def name(experiment, fold): name = '-'.join([experiment, timestamp, unique]) return (name + '-fold{}'.format(fold)) def j...
def parse(args): import argparse parser = argparse.ArgumentParser(description='Generate jobs') a = parser.add_argument a('--models', default='models.csv', help='%(default)s') a('--settings', default='experiments/ldcnn20k60.yaml', help='%(default)s') a('--jobs', dest='jobs_dir', default='./data...
def main(): args = parse(sys.argv[1:]) models = pandas.read_csv(args.models) settings = common.load_settings_path(args.settings) overrides = {} folds = list(range(0, 9)) if args.check: folds = (1,) overrides['train_samples'] = (settings['batch'] * 1) overrides['val_samp...
@pytest.mark.skip('fails right now') @pytest.mark.parametrize('family', FAMILIES) def test_models_basic(family): s = settings.load_settings({'model': family, 'frames': 31, 'n_mels': 60, 'samplerate': 22050}) if (family == 'sbcnn'): s['downsample_size'] = (3, 2) s['conv_size'] = (3, 3) if (...
@pytest.mark.parametrize('conv_type', CONV_TYPES) def test_strided_variations(conv_type): s = settings.load_settings({'model': 'strided', 'frames': 31, 'n_mels': 60, 'samplerate': 22050, 'conv_block': conv_type, 'filters': 20}) s['conv_size'] = (3, 3) s['downsample_size'] = (2, 2) m = models.build(s) ...
def test_conv_ds(): k = (5, 5) i = (60, 31, 16) ch = 16 conv = stats.compute_conv2d(*i, ch, *k) ds = stats.compute_conv2d_ds(*i, ch, *k) ratio = (conv / ds) assert (ratio > 9.0)
def test_conv_ds3x3(): k = (3, 3) i = (60, 31, 64) ch = 64 conv = stats.compute_conv2d(*i, ch, *k) ds = stats.compute_conv2d_ds(*i, ch, *k) ratio = (conv / ds) assert (ratio > 7.5)
@pytest.mark.skip('fails') def test_generator_fake_loader(): dataset_path = 'data/UrbanSound8K/' urbansound8k.default_path = dataset_path data = urbansound8k.load_dataset() (folds, test) = urbansound8k.folds(data) data_length = 16 batch_size = 8 frames = 72 bands = 32 n_classes = 1...
def test_windows_shorter_than_window(): frame_samples = 256 window_frames = 64 fs = 16000 length = (0.4 * fs) w = list(features.sample_windows(int(length), frame_samples, window_frames)) assert (len(w) == 1), len(w) assert (w[(- 1)][1] == length)
def test_window_typical(): frame_samples = 256 window_frames = 64 fs = 16000 length = (4.0 * fs) w = list(features.sample_windows(int(length), frame_samples, window_frames)) assert (len(w) == 8), len(w) assert (w[(- 1)][1] == length)
def _test_predict_windowed(): t = test[0:10] sbcnn16k32_settings = dict(feature='mels', samplerate=16000, n_mels=32, fmin=0, fmax=8000, n_fft=512, hop_length=256, augmentations=5) def load_sample32(sample): return features.load_sample(sample, sbcnn16k32_settings, window_frames=72, feature_dir='.....
def test_precompute(): settings = dict(feature='mels', samplerate=16000, n_mels=32, fmin=0, fmax=8000, n_fft=512, hop_length=256, augmentations=12) dir = './pre2' if os.path.exists(dir): shutil.rmtree(dir) workdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/')) data ...
def test_grouped_confusion(): cm = numpy.array([[82, 0, 3, 0, 0, 10, 0, 4, 1, 0], [3, 29, 0, 0, 0, 0, 1, 0, 0, 0], [4, 3, 37, 14, 4, 4, 0, 0, 2, 32], [5, 2, 5, 78, 4, 0, 0, 0, 0, 6], [23, 2, 4, 1, 55, 4, 2, 6, 3, 0], [9, 0, 0, 4, 3, 70, 0, 5, 1, 1], [0, 0, 0, 5, 0, 0, 27, 0, 0, 0], [0, 0, 2, 0, 1, 1, 1, 91, 0, 0]...
@pytest.mark.parametrize('example', CORRECT_FOLDS.keys()) def test_ensure_valid_fold_passes_correct(example): fold = CORRECT_FOLDS[example] folds.ensure_valid_fold(fold)
@pytest.mark.parametrize('example', WRONG_FOLDS.keys()) def test_ensure_valid_fold_detects_wrong(example): fold = WRONG_FOLDS[example] with pytest.raises(AssertionError) as e_info: folds.ensure_valid_fold(fold)
def test_folds_idx(): f = folds.folds_idx(10) print(('\n' + '\n'.join([str(i) for i in f]))) assert (f[0][2][0] == 0), 'first test fold should be 0' assert (f[(- 1)][2][0] == 9), 'last test fold should be 9'
def test_folds(): data = urbansound8k.load_dataset() f = urbansound8k.folds(data) assert (len(f) == 10)
@dataclass class DataTrainingArguments(): '\n Arguments pertaining to what data we are going to input our model for training and eval.\n ' task_name: Optional[str] = field(default='ner', metadata={'help': 'The name of the task (ner, pos...).'}) dataset_name: Optional[str] = field(default=None, metad...
@dataclass class XFUNDataTrainingArguments(DataTrainingArguments): lang: Optional[str] = field(default='en') additional_langs: Optional[str] = field(default=None)
@dataclass class DataCollatorForKeyValueExtraction(): "\n Data collator that will dynamically pad the inputs received, as well as the labels.\n\n Args:\n tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):\n The tokenizer used for encod...
class FunsdConfig(datasets.BuilderConfig): 'BuilderConfig for FUNSD' def __init__(self, **kwargs): 'BuilderConfig for FUNSD.\n\n Args:\n **kwargs: keyword arguments forwarded to super.\n ' super(FunsdConfig, self).__init__(**kwargs)
class Funsd(datasets.GeneratorBasedBuilder): 'Conll2003 dataset.' BUILDER_CONFIGS = [FunsdConfig(name='funsd', version=datasets.Version('1.0.0'), description='FUNSD dataset')] def _info(self): return datasets.DatasetInfo(description=_DESCRIPTION, features=datasets.Features({'id': datasets.Value('...
class XFUNConfig(datasets.BuilderConfig): 'BuilderConfig for XFUN.' def __init__(self, lang, additional_langs=None, **kwargs): '\n Args:\n lang: string, language for the input text\n **kwargs: keyword arguments forwarded to super.\n ' super(XFUNConfig, self...
class XFUN(datasets.GeneratorBasedBuilder): 'XFUN dataset.' BUILDER_CONFIGS = [XFUNConfig(name=f'xfun.{lang}', lang=lang) for lang in _LANG] tokenizer = AutoTokenizer.from_pretrained('xlm-roberta-base') def _info(self): return datasets.DatasetInfo(features=datasets.Features({'id': datasets.Va...
def normalize_bbox(bbox, size): return [int(((1000 * bbox[0]) / size[0])), int(((1000 * bbox[1]) / size[1])), int(((1000 * bbox[2]) / size[0])), int(((1000 * bbox[3]) / size[1]))]
def simplify_bbox(bbox): return [min(bbox[0::2]), min(bbox[1::2]), max(bbox[2::2]), max(bbox[3::2])]
def merge_bbox(bbox_list): (x0, y0, x1, y1) = list(zip(*bbox_list)) return [min(x0), min(y0), max(x1), max(y1)]
def load_image(image_path): image = read_image(image_path, format='BGR') h = image.shape[0] w = image.shape[1] img_trans = TransformList([ResizeTransform(h=h, w=w, new_h=224, new_w=224)]) image = torch.tensor(img_trans.apply_image(image).copy()).permute(2, 0, 1) return (image, (w, h))
def get_last_checkpoint(folder): content = os.listdir(folder) checkpoints = [path for path in content if ((_re_checkpoint.search(path) is not None) and os.path.isdir(os.path.join(folder, path)))] if (len(checkpoints) == 0): return return os.path.join(folder, max(checkpoints, key=(lambda x: int...
def re_score(pred_relations, gt_relations, mode='strict'): 'Evaluate RE predictions\n\n Args:\n pred_relations (list) : list of list of predicted relations (several relations in each sentence)\n gt_relations (list) : list of list of ground truth relations\n\n rel = { "head": (start...
@dataclass class ModelArguments(): '\n Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.\n ' model_name_or_path: str = field(metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}) config_name: Optional[str] = field(default=Non...
class BiaffineAttention(torch.nn.Module): 'Implements a biaffine attention operator for binary relation classification.\n\n PyTorch implementation of the biaffine attention operator from "End-to-end neural relation\n extraction using deep biaffine attention" (https://arxiv.org/abs/1812.11275) which can be u...
class REDecoder(nn.Module): def __init__(self, config, input_size): super().__init__() self.entity_emb = nn.Embedding(3, input_size, scale_grad_by_freq=True) projection = nn.Sequential(nn.Linear((input_size * 2), config.hidden_size), nn.ReLU(), nn.Dropout(config.hidden_dropout_prob), nn.L...
class FunsdTrainer(Trainer): def _prepare_inputs(self, inputs: Dict[(str, Union[(torch.Tensor, Any)])]) -> Dict[(str, Union[(torch.Tensor, Any)])]: '\n Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and\n handling potential state.\...
class XfunSerTrainer(FunsdTrainer): pass
class XfunReTrainer(FunsdTrainer): def __init__(self, **kwargs): super().__init__(**kwargs) self.label_names.append('relations') def prediction_step(self, model: nn.Module, inputs: Dict[(str, Union[(torch.Tensor, Any)])], prediction_loss_only: bool, ignore_keys: Optional[List[str]]=None) -> ...
@dataclass class ReOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None entities: Optional[Dict] = None relations: Optional[Dict] = None ...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data_arg...
def _mp_fn(index): main()
def main(): parser = HfArgumentParser((ModelArguments, XFUNDataTrainingArguments, TrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data...