code stringlengths 17 6.64M |
|---|
class augmentations(object):
def __init__(self):
self.scale_ratio = 0.8
self.jitter_ratio = 0.2
|
class Config(object):
def __init__(self):
self.dataset = 'IOpsCompetition'
self.input_channels = 1
self.kernel_size = 4
self.stride = 1
self.final_out_channels = 32
self.num_classes = 2
self.dropout = 0.45
self.features_len = 4
self.window_s... |
class augmentations(object):
def __init__(self):
self.jitter_scale_ratio = 1.5
self.jitter_ratio = 0.4
self.max_seg = 4
|
class Context_Cont_configs(object):
def __init__(self):
self.temperature = 0.2
self.use_cosine_similarity = True
|
class TC(object):
def __init__(self):
self.hidden_dim = 64
self.timesteps = 2
|
class Config(object):
def __init__(self):
self.dataset = 'UCR'
self.input_channels = 1
self.kernel_size = 8
self.stride = 1
self.final_out_channels = 64
self.num_classes = 2
self.dropout = 0.45
self.features_len = 10
self.window_size = 64
... |
class augmentations(object):
def __init__(self):
self.jitter_scale_ratio = 0.8
self.jitter_ratio = 0.2
self.max_seg = 8
|
class Context_Cont_configs(object):
def __init__(self):
self.temperature = 0.2
self.use_cosine_similarity = True
|
class TC(object):
def __init__(self):
self.hidden_dim = 100
self.timesteps = 2
|
class Load_Dataset(Dataset):
def __init__(self, dataset, config):
super(Load_Dataset, self).__init__()
X_train = dataset['samples']
y_train = dataset['labels']
if (len(X_train.shape) < 3):
X_train = X_train.unsqueeze(2)
if isinstance(X_train, np.ndarray):
... |
def data_generator1(train_data, test_data, train_labels, test_labels, configs):
train_time_series_ts = train_data
test_time_series_ts = test_data
mvn = MeanVarNormalize()
mvn.train((train_time_series_ts + test_time_series_ts))
(bias, scale) = (mvn.bias, mvn.scale)
train_time_series = train_tim... |
def data_generator2(train_data, test_data, train_labels, test_labels, configs):
train_time_series_ts = train_data
test_time_series_ts = test_data
mvn = MeanVarNormalize()
mvn.train((train_time_series_ts + test_time_series_ts))
(bias, scale) = (mvn.bias, mvn.scale)
train_time_series = train_tim... |
class base_Model(nn.Module):
def __init__(self, configs, device):
super(base_Model, self).__init__()
self.input_channels = configs.input_channels
self.final_out_channels = configs.final_out_channels
self.features_len = configs.features_len
self.project_channels = configs.p... |
class base_Model(nn.Module):
def __init__(self, configs, device):
super(base_Model, self).__init__()
self.input_channels = configs.input_channels
self.final_out_channels = configs.final_out_channels
self.features_len = configs.features_len
self.project_channels = configs.p... |
class EarlyStopping():
"Early stops the training if validation loss doesn't improve after a given patience."
def __init__(self, save_path, idx, patience=10, verbose=False, delta=0):
'\n Args:\n save_path : save model path\n patience (int): How long to wait after last time... |
def Trainer(model, model_optimizer, train_dl, val_dl, test_dl, device, logger, config, idx):
logger.debug('Training started ....')
save_path = ('./best_network/' + config.dataset)
os.makedirs(save_path, exist_ok=True)
early_stopping = EarlyStopping(save_path, idx)
scheduler = torch.optim.lr_schedu... |
def model_train(model, model_optimizer, train_loader, center, length, config, device, epoch):
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
model.train()
for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader):
(dat... |
def model_evaluate(model, test_dl, center, length, config, device, epoch):
model.eval()
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
all_projection = []
with torch.no_grad():
for (data, target, aug1, aug2) in test_dl:
... |
def train(feature1, feature_dec1, center, length, epoch, config, device):
center = center.unsqueeze(0)
center = F.normalize(center, dim=1)
feature1 = F.normalize(feature1, dim=1)
feature_dec1 = F.normalize(feature_dec1, dim=1)
distance1 = F.cosine_similarity(feature1, center, eps=1e-06)
distan... |
def center_c(train_loader, model, device, center, config, eps=0.1):
'Initialize hypersphere center c as the mean from an initial forward pass on the data.'
n_samples = 0
c = center
model.eval()
with torch.no_grad():
for data in train_loader:
(data, target, aug1, aug2) = data
... |
def get_radius(dist: torch.Tensor, nu: float):
'Optimally solve for radius R via the (1-nu)-quantile of distances.'
dist = dist.reshape((- 1))
return np.quantile(dist.clone().data.cpu().numpy(), (1 - nu))
|
def Trainer(model, model_optimizer, train_dl, val_dl, test_dl, device, logger, config, experiment_log_dir, idx):
save_path = ('./best_network/' + config.dataset)
os.makedirs(save_path, exist_ok=True)
early_stopping = EarlyStopping(save_path, idx)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(... |
def model_train(model, model_optimizer, train_loader, center, length, config, device, epoch):
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
model.train()
for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader):
(dat... |
def model_evaluate(model, test_dl, center, length, config, device, epoch):
model.eval()
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
all_projection = []
with torch.no_grad():
for (data, target, aug1, aug2) in test_dl:
... |
def train(feature1, feature_dec1, center, length, epoch, config, device):
center = center.unsqueeze(0)
center = F.normalize(center, dim=1)
feature1 = F.normalize(feature1, dim=1)
feature_dec1 = F.normalize(feature_dec1, dim=1)
distance1 = F.cosine_similarity(feature1, center, eps=1e-06)
distan... |
def center_c(train_loader, model, device, center, config, eps=0.1):
'Initialize hypersphere center c as the mean from an initial forward pass on the data.'
n_samples = 0
c = center
model.eval()
with torch.no_grad():
for data in train_loader:
(data, target, aug1, aug2) = data
... |
def get_radius(dist: torch.Tensor, nu: float):
'Optimally solve for radius R via the (1-nu)-quantile of distances.'
dist = dist.reshape((- 1))
return np.quantile(dist.clone().data.cpu().numpy(), (1 - nu))
|
def Trainer(model, model_optimizer, train_dl, val_dl, test_dl, device, logger, config, experiment_log_dir, idx):
save_path = ('./best_network/' + config.dataset)
os.makedirs(save_path, exist_ok=True)
early_stopping = EarlyStopping(save_path, idx)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(... |
def model_train(model, model_optimizer, train_loader, center, length, config, device, epoch):
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
model.train()
for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader):
(dat... |
def model_evaluate(model, test_dl, center, length, config, device, epoch):
model.eval()
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
all_projection = []
with torch.no_grad():
for (data, target, aug1, aug2) in test_dl:
... |
def train(feature1, center, length, epoch, config, device):
center = center.unsqueeze(0)
center = F.normalize(center, dim=1)
feature1 = F.normalize(feature1, dim=1)
distance1 = F.cosine_similarity(feature1, center, eps=1e-06)
distance1 = (1 - distance1)
sigma_aug1 = torch.sqrt((feature1.var([0... |
def center_c(train_loader, model, device, center, config, eps=0.1):
'Initialize hypersphere center c as the mean from an initial forward pass on the data.'
n_samples = 0
c = center
model.eval()
with torch.no_grad():
for data in train_loader:
(data, target, aug1, aug2) = data
... |
def get_radius(dist: torch.Tensor, nu: float):
'Optimally solve for radius R via the (1-nu)-quantile of distances.'
dist = dist.reshape((- 1))
return np.quantile(dist.clone().data.cpu().numpy(), (1 - nu))
|
def Trainer(model, model_optimizer, train_dl, val_dl, test_dl, device, logger, config, experiment_log_dir, idx):
logger.debug('Training started ....')
save_path = ('./best_network/' + config.dataset)
os.makedirs(save_path, exist_ok=True)
early_stopping = EarlyStopping(save_path, idx)
scheduler = t... |
def model_train(model, model_optimizer, train_loader, center, length, config, device, epoch):
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
model.train()
for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader):
(dat... |
def model_evaluate(model, test_dl, center, length, config, device, epoch):
model.eval()
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
all_projection = []
with torch.no_grad():
for (data, target, aug1, aug2) in test_dl:
... |
def train(feature1, feature_dec1, center, length, epoch, config, device):
feature1 = F.normalize(feature1, dim=1)
feature_dec1 = F.normalize(feature_dec1, dim=1)
distance1 = F.cosine_similarity(feature1, feature_dec1, eps=1e-06)
distance1 = (1 - distance1)
sigma_aug1 = torch.sqrt((feature1.var([0]... |
def center_c(train_loader, model, device, center, config, eps=0.1):
'Initialize hypersphere center c as the mean from an initial forward pass on the data.'
n_samples = 0
c = center
model.eval()
with torch.no_grad():
for data in train_loader:
(data, target, aug1, aug2) = data
... |
def get_radius(dist: torch.Tensor, nu: float):
'Optimally solve for radius R via the (1-nu)-quantile of distances.'
dist = dist.reshape((- 1))
return np.quantile(dist.clone().data.cpu().numpy(), (1 - nu))
|
def Trainer(model, model_optimizer, train_dl, val_dl, test_dl, device, logger, config, experiment_log_dir, idx):
logger.debug('Training started ....')
save_path = ('./best_network/' + config.dataset)
os.makedirs(save_path, exist_ok=True)
early_stopping = EarlyStopping(save_path, idx)
scheduler = t... |
def model_train(model, model_optimizer, train_loader, center, length, config, device, epoch):
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
model.train()
for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader):
(dat... |
def model_evaluate(model, test_dl, center, length, config, device, epoch):
model.eval()
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
all_projection = []
with torch.no_grad():
for (data, target, aug1, aug2) in test_dl:
... |
def train(feature1, feature_dec1, center, length, epoch, config, device):
center = center.unsqueeze(0)
center = F.normalize(center, dim=1)
feature1 = F.normalize(feature1, dim=1)
feature_dec1 = F.normalize(feature_dec1, dim=1)
distance1 = F.cosine_similarity(feature1, center, eps=1e-06)
distan... |
def center_c(train_loader, model, device, center, config, eps=0.1):
'Initialize hypersphere center c as the mean from an initial forward pass on the data.'
n_samples = 0
c = center
model.eval()
with torch.no_grad():
for data in train_loader:
(data, target, aug1, aug2) = data
... |
def get_radius(dist: torch.Tensor, nu: float):
'Optimally solve for radius R via the (1-nu)-quantile of distances.'
dist = dist.reshape((- 1))
return np.quantile(dist.clone().data.cpu().numpy(), (1 - nu))
|
def Trainer(model, model_optimizer, train_dl, val_dl, test_dl, device, logger, config, experiment_log_dir, idx):
logger.debug('Training started ....')
save_path = ('./best_network/' + config.dataset)
os.makedirs(save_path, exist_ok=True)
early_stopping = EarlyStopping(save_path, idx)
scheduler = t... |
def model_train(model, model_optimizer, train_loader, center, length, config, device, epoch):
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
model.train()
for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader):
(dat... |
def model_evaluate(model, test_dl, center, length, config, device, epoch):
model.eval()
(total_loss, total_f1, total_precision, total_recall) = ([], [], [], [])
(all_target, all_predict) = ([], [])
all_projection = []
with torch.no_grad():
for (data, target, aug1, aug2) in test_dl:
... |
def train(feature1, feature2, center, length, epoch, config, device):
center = center.unsqueeze(0)
center = F.normalize(center, dim=1)
feature1 = F.normalize(feature1, dim=1)
feature2 = F.normalize(feature2, dim=1)
distance1 = F.cosine_similarity(feature1, center, eps=1e-06)
distance2 = F.cosi... |
def center_c(train_loader, model, device, center, config, eps=0.1):
'Initialize hypersphere center c as the mean from an initial forward pass on the data.'
n_samples = 0
c = center
model.eval()
with torch.no_grad():
for data in train_loader:
(data, target, aug1, aug2) = data
... |
def get_radius(dist: torch.Tensor, nu: float):
'Optimally solve for radius R via the (1-nu)-quantile of distances.'
dist = dist.reshape((- 1))
return np.quantile(dist.clone().data.cpu().numpy(), (1 - nu))
|
class CPCConf(DetectorConfig):
_default_transform = MeanVarNormalize()
@initializer
def __init__(self, logging_dir='./results/cpc', epochs=150, n_warmup_steps=100, batch_size=256, sequence_length=16, timestep=2, masked_frames=0, cuda=torch.cuda.is_available(), seed=1, log_interval=50, **kwargs):
... |
class ForwardLibriSpeechRawXXreverseDataset(data.Dataset):
def __init__(self, raw_file, list_file):
' raw_file: train-clean-100.h5\n list_file: list/training.txt\n audio_window: 20480\n '
self.raw_file = raw_file
self.utts = []
with open(list_file) as ... |
class ForwardLibriSpeechReverseRawDataset(data.Dataset):
def __init__(self, raw_file, list_file):
' raw_file: train-clean-100.h5\n list_file: list/training.txt\n audio_window: 20480\n '
self.raw_file = raw_file
self.utts = []
with open(list_file) as f:... |
class ForwardLibriSpeechRawDataset(data.Dataset):
def __init__(self, raw_file, list_file):
' raw_file: train-clean-100.h5\n list_file: list/training.txt\n audio_window: 20480\n '
self.raw_file = raw_file
self.utts = []
with open(list_file) as f:
... |
class ReverseRawDataset(data.Dataset):
def __init__(self, raw_file, list_file, audio_window):
' RawDataset trained reverse;\n raw_file: train-clean-100.h5\n list_file: list/training.txt\n audio_window: 20480\n '
self.raw_file = raw_file
self.audio_w... |
class ForwardDatasetSITWSilence(data.Dataset):
' dataset for forward passing sitw without vad '
def __init__(self, wav_file):
' wav_file: /export/c01/jlai/thesis/data/sitw_dev_enroll/wav.scp\n '
self.wav_file = wav_file
with open(wav_file) as f:
temp = f.readlines()... |
class ForwardDatasetSwbdSreSilence(data.Dataset):
' dataset for forward passing swbd_sre or sre16 without vad '
def __init__(self, wav_dir, scp_file):
' wav_dir: /export/c01/jlai/thesis/data/swbd_sre_combined/wav/\n list_file: /export/c01/jlai/thesis/data/swbd_sre_combined/list/log/swbd_sr... |
class RawDatasetSwbdSreOne(data.Dataset):
' dataset for swbd_sre with vad ; for training cpc with ONE voiced segment per recording '
def __init__(self, raw_file, list_file):
' raw_file: swbd_sre_combined_20k_20480.h5\n list_file: list/training3.txt, list/val3.txt\n '
self.ra... |
class RawDatasetSwbdSreSilence(data.Dataset):
' dataset for swbd_sre without vad; for training cpc with ONE voiced/unvoiced segment per recording '
def __init__(self, raw_file, list_file, audio_window):
' raw_file: swbd_sre_combined_20k_20480.h5\n list_file: list/training2.txt, list/val2.t... |
class RawDatasetSwbdSre(data.Dataset):
' dataset for swbd_sre with vad ; for training cpc with ONE voiced segment per recording '
def __init__(self, raw_file, list_file):
' raw_file: swbd_sre_combined_20k_20480.h5\n list_file: list/training.txt\n '
self.raw_file = raw_file
... |
class RawDatasetSpkClass(data.Dataset):
def __init__(self, raw_file, list_file, index_file, audio_window, frame_window):
' raw_file: train-clean-100.h5\n list_file: list/training.txt\n index_file: spk2idx\n audio_window: 20480\n '
self.raw_file = raw_file
... |
class RawXXreverseDataset(data.Dataset):
' RawDataset but returns sequence twice: x, x_reverse '
def __init__(self, raw_file, list_file, audio_window):
' raw_file: train-clean-100.h5\n list_file: list/training.txt\n audio_window: 20480\n '
self.raw_file = raw_file... |
class RawDataset(data.Dataset):
def __init__(self, raw_file, list_file, audio_window):
' raw_file: train-clean-100.h5\n list_file: list/training.txt\n audio_window: 20480\n '
self.raw_file = raw_file
self.audio_window = audio_window
self.utts = []
... |
def forwardXXreverse(args, cpc_model, device, data_loader, output_ark, output_scp):
logger.info('Starting Forward Passing')
cpc_model.eval()
ark_scp_output = ((('ark:| copy-feats --compress=true ark:- ark,scp:' + output_ark) + ',') + output_scp)
with torch.no_grad():
with ko.open_or_fd(ark_scp... |
def forward_dct(args, cpc_model, device, data_loader, output_ark, output_scp, dct_dim=24):
' forward with dct '
logger.info('Starting Forward Passing')
cpc_model.eval()
ark_scp_output = ((('ark:| copy-feats --compress=true ark:- ark,scp:' + output_ark) + ',') + output_scp)
with torch.no_grad():
... |
def forward(cpc_model, device, data_loader, output_ark, output_scp):
logger.info('Starting Forward Passing')
cpc_model.eval()
ark_scp_output = ((('ark:| copy-feats --compress=true ark:- ark,scp:' + output_ark) + ',') + output_scp)
with torch.no_grad():
with ko.open_or_fd(ark_scp_output, 'wb') ... |
class UnsupportedDataType(Exception):
pass
|
class UnknownVectorHeader(Exception):
pass
|
class UnknownMatrixHeader(Exception):
pass
|
class BadSampleSize(Exception):
pass
|
class BadInputFormat(Exception):
pass
|
class SubprocessFailed(Exception):
pass
|
def open_or_fd(file, mode='rb'):
" fd = open_or_fd(file)\n Open file, gzipped file, pipe, or forward the file-descriptor.\n Eventually seeks in the 'file' argument contains ':offset' suffix.\n "
offset = None
try:
if re.search('^(ark|scp)(,scp|,b|,t|,n?f|,n?p|,b?o|,n?s|,n?cs)*:', file):
... |
def popen(cmd, mode='rb'):
if (not isinstance(cmd, str)):
raise TypeError(('invalid cmd type (%s, expected string)' % type(cmd)))
import subprocess, io, threading
def cleanup(proc, cmd):
ret = proc.wait()
if (ret > 0):
raise SubprocessFailed(('cmd %s returned %d !' % (... |
def read_key(fd):
" [key] = read_key(fd)\n Read the utterance-key from the opened ark/stream descriptor 'fd'.\n "
key = ''
while 1:
char = fd.read(1).decode()
if (char == ''):
break
if (char == ' '):
break
key += char
key = key.strip()
if ... |
def read_ali_ark(file_or_fd):
" Alias to 'read_vec_int_ark()' "
return read_vec_int_ark(file_or_fd)
|
def read_vec_int_ark(file_or_fd):
" generator(key,vec) = read_vec_int_ark(file_or_fd)\n Create generator of (key,vector<int>) tuples, which reads from the ark file/stream.\n file_or_fd : ark, gzipped ark, pipe or opened file descriptor.\n\n Read ark to a 'dictionary':\n d = { u:d for u,d in kaldi_io.read_... |
def read_vec_int(file_or_fd):
' [int-vec] = read_vec_int(file_or_fd)\n Read kaldi integer vector, ascii or binary input,\n '
fd = open_or_fd(file_or_fd)
binary = fd.read(2).decode()
if (binary == '\x00B'):
assert (fd.read(1).decode() == '\x04')
vec_size = np.frombuffer(fd.read(4), d... |
def write_vec_int(file_or_fd, v, key=''):
" write_vec_int(f, v, key='')\n Write a binary kaldi integer vector to filename or stream.\n Arguments:\n file_or_fd : filename or opened file descriptor for writing,\n v : the vector to be stored,\n key (optional) : used for writing ark-file, the utterance-id g... |
def read_vec_flt_scp(file_or_fd):
" generator(key,mat) = read_vec_flt_scp(file_or_fd)\n Returns generator of (key,vector) tuples, read according to kaldi scp.\n file_or_fd : scp, gzipped scp, pipe or opened file descriptor.\n\n Iterate the scp:\n for key,vec in kaldi_io.read_vec_flt_scp(file):\n ...\n... |
def read_vec_flt_ark(file_or_fd):
" generator(key,vec) = read_vec_flt_ark(file_or_fd)\n Create generator of (key,vector<float>) tuples, reading from an ark file/stream.\n file_or_fd : ark, gzipped ark, pipe or opened file descriptor.\n\n Read ark to a 'dictionary':\n d = { u:d for u,d in kaldi_io.read_vec... |
def read_vec_flt(file_or_fd):
' [flt-vec] = read_vec_flt(file_or_fd)\n Read kaldi float vector, ascii or binary input,\n '
fd = open_or_fd(file_or_fd)
binary = fd.read(2).decode()
if (binary == '\x00B'):
header = fd.read(3).decode()
if (header == 'FV '):
sample_size = 4
... |
def write_vec_flt(file_or_fd, v, key=''):
" write_vec_flt(f, v, key='')\n Write a binary kaldi vector to filename or stream. Supports 32bit and 64bit floats.\n Arguments:\n file_or_fd : filename or opened file descriptor for writing,\n v : the vector to be stored,\n key (optional) : used for writing ark... |
def read_mat_scp(file_or_fd):
" generator(key,mat) = read_mat_scp(file_or_fd)\n Returns generator of (key,matrix) tuples, read according to kaldi scp.\n file_or_fd : scp, gzipped scp, pipe or opened file descriptor.\n\n Iterate the scp:\n for key,mat in kaldi_io.read_mat_scp(file):\n ...\n\n Read sc... |
def read_mat_ark(file_or_fd):
" generator(key,mat) = read_mat_ark(file_or_fd)\n Returns generator of (key,matrix) tuples, read from ark file/stream.\n file_or_fd : scp, gzipped scp, pipe or opened file descriptor.\n\n Iterate the ark:\n for key,mat in kaldi_io.read_mat_ark(file):\n ...\n\n Read ark ... |
def read_mat(file_or_fd):
' [mat] = read_mat(file_or_fd)\n Reads single kaldi matrix, supports ascii and binary.\n file_or_fd : file, gzipped file, pipe or opened file descriptor.\n '
fd = open_or_fd(file_or_fd)
try:
binary = fd.read(2).decode()
if (binary == '\x00B'):
mat... |
def _read_mat_binary(fd):
header = fd.read(3).decode()
if header.startswith('CM'):
return _read_compressed_mat(fd, header)
elif (header == 'FM '):
sample_size = 4
elif (header == 'DM '):
sample_size = 8
else:
raise UnknownMatrixHeader(("The header contained '%s'" % ... |
def _read_mat_ascii(fd):
rows = []
while 1:
line = fd.readline().decode()
if (len(line) == 0):
raise BadInputFormat
if (len(line.strip()) == 0):
continue
arr = line.strip().split()
if (arr[(- 1)] != ']'):
rows.append(np.array(arr, dty... |
def _read_compressed_mat(fd, format):
' Read a compressed matrix,\n see: https://github.com/kaldi-asr/kaldi/blob/master/src/matrix/compressed-matrix.h\n methods: CompressedMatrix::Read(...), CompressedMatrix::CopyToMat(...),\n '
assert (format == 'CM ')
global_header = np.dtype([('minvalue', 'f... |
def write_mat(file_or_fd, m, key=''):
" write_mat(f, m, key='')\n Write a binary kaldi matrix to filename or stream. Supports 32bit and 64bit floats.\n Arguments:\n file_or_fd : filename of opened file descriptor for writing,\n m : the matrix to be stored,\n key (optional) : used for writing ark-file, the... |
def read_cnet_ark(file_or_fd):
" Alias of function 'read_post_ark()', 'cnet' = confusion network "
return read_post_ark(file_or_fd)
|
def read_post_ark(file_or_fd):
" generator(key,vec<vec<int,float>>) = read_post_ark(file)\n Returns generator of (key,posterior) tuples, read from ark file.\n file_or_fd : ark, gzipped ark, pipe or opened file descriptor.\n\n Iterate the ark:\n for key,post in kaldi_io.read_post_ark(file):\n ...\n\n ... |
def read_post(file_or_fd):
" [post] = read_post(file_or_fd)\n Reads single kaldi 'Posterior' in binary format.\n\n The 'Posterior' is C++ type 'vector<vector<tuple<int,float> > >',\n the outer-vector is usually time axis, inner-vector are the records\n at given time, and the tuple is composed of an 'inde... |
def read_cntime_ark(file_or_fd):
" generator(key,vec<tuple<float,float>>) = read_cntime_ark(file_or_fd)\n Returns generator of (key,cntime) tuples, read from ark file.\n file_or_fd : file, gzipped file, pipe or opened file descriptor.\n\n Iterate the ark:\n for key,time in kaldi_io.read_cntime_ark(file):\... |
def read_cntime(file_or_fd):
" [cntime] = read_cntime(file_or_fd)\n Reads single kaldi 'Confusion Network time info', in binary format:\n C++ type: vector<tuple<float,float> >.\n (begin/end times of bins at the confusion network).\n\n Binary layout is '<num-bins> <beg1> <end1> <beg2> <end2> ...'\n\n fil... |
def read_segments_as_bool_vec(segments_file):
" [ bool_vec ] = read_segments_as_bool_vec(segments_file)\n using kaldi 'segments' file for 1 wav, format : '<utt> <rec> <t-beg> <t-end>'\n - t-beg, t-end is in seconds,\n - assumed 100 frames/second,\n "
segs = np.loadtxt(segments_file, dtype='object,objec... |
def setup_logs(save_dir, run_name):
logger = logging.getLogger('cdc')
logger.setLevel(logging.INFO)
log_file = os.path.join(save_dir, (run_name + '.log'))
fh = logging.FileHandler(log_file)
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(message)s')
fh.setFormat... |
class ScheduledOptim(object):
'A simple wrapper class for learning rate scheduling'
def __init__(self, optimizer, n_warmup_steps):
self.optimizer = optimizer
self.d_model = 128
self.n_warmup_steps = n_warmup_steps
self.n_current_steps = 0
self.delta = 1
def state_... |
def prediction_spk(args, cdc_model, spk_model, device, data_loader, batch_size, frame_window):
logger.info('Starting Evaluation')
cdc_model.eval()
spk_model.eval()
total_loss = 0
total_acc = 0
with torch.no_grad():
for [data, target] in data_loader:
data = data.float().unsq... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.