code
stringlengths
17
6.64M
class VGG(nn.Module): def __init__(self, conv_index, rgb_range=1): super(VGG, self).__init__() vgg_features = models.vgg19(pretrained=True).features modules = [m for m in vgg_features] if (conv_index == '22'): self.vgg = nn.Sequential(*modules[:8]) elif (conv_i...
def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias)
class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rgb_mean, rgb_std, sign=(- 1)): super(MeanShift, self).__init__(3, 3, kernel_size=1) std = torch.Tensor(rgb_std) self.weight.data = torch.eye(3).view(3, 3, 1, 1) self.weight.data.div_(std.view(3, 1, 1, 1)) self.bias...
class BasicBlock(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size, stride=1, bias=True, bn=False, act=nn.ReLU(True)): m = [nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), stride=stride, bias=bias)] if bn: m.append(nn.BatchNorm2d(o...
class ResBlock(nn.Module): def __init__(self, conv, n_feat, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1): super(ResBlock, self).__init__() m = [] for i in range(2): m.append(conv(n_feat, n_feat, kernel_size, bias=bias)) if bn: m...
class Upsampler(nn.Sequential): def __init__(self, conv, scale, n_feat, bn=False, act=False, bias=True): m = [] if ((scale & (scale - 1)) == 0): for _ in range(int(math.log(scale, 2))): m.append(conv(n_feat, (4 * n_feat), 3, bias)) m.append(nn.PixelShuf...
def make_model(args, parent=False): return DDBPN(args)
def projection_conv(in_channels, out_channels, scale, up=True): (kernel_size, stride, padding) = {2: (6, 2, 2), 4: (8, 4, 2), 8: (12, 8, 2)}[scale] if up: conv_f = nn.ConvTranspose2d else: conv_f = nn.Conv2d return conv_f(in_channels, out_channels, kernel_size, stride=stride, padding=p...
class DenseProjection(nn.Module): def __init__(self, in_channels, nr, scale, up=True, bottleneck=True): super(DenseProjection, self).__init__() if bottleneck: self.bottleneck = nn.Sequential(*[nn.Conv2d(in_channels, nr, 1), nn.PReLU(nr)]) inter_channels = nr else: ...
class DDBPN(nn.Module): def __init__(self, args): super(DDBPN, self).__init__() scale = args.scale[0] n0 = 128 nr = 32 self.depth = 6 rgb_mean = (0.4488, 0.4371, 0.404) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(args.rgb_range, rgb_m...
def make_model(args, parent=False): return EDSR(args)
class EDSR(nn.Module): def __init__(self, args, conv=common.default_conv): super(EDSR, self).__init__() n_resblock = args.n_resblocks n_feats = args.n_feats kernel_size = 3 scale = args.scale[0] act = nn.ReLU(True) rgb_mean = (0.4488, 0.4371, 0.404) ...
def make_model(args, parent=False): return MDSR(args)
class MDSR(nn.Module): def __init__(self, args, conv=common.default_conv): super(MDSR, self).__init__() n_resblocks = args.n_resblocks n_feats = args.n_feats kernel_size = 3 self.scale_idx = 0 act = nn.ReLU(True) rgb_mean = (0.4488, 0.4371, 0.404) r...
def set_template(args): if (args.template.find('jpeg') >= 0): args.data_train = 'DIV2K_jpeg' args.data_test = 'DIV2K_jpeg' args.epochs = 200 args.lr_decay = 100 if (args.template.find('EDSR_paper') >= 0): args.model = 'EDSR' args.n_resblocks = 32 args.n_...
class Trainer(): def __init__(self, args, loader, my_model, my_loss, ckp): self.args = args self.scale = args.scale self.ckp = ckp self.loader_train = loader.loader_train self.loader_test = loader.loader_test self.model = my_model self.loss = my_loss ...
def angular_error(gt_mesh_name, gen_mesh_name, sample_num): '\n This function computes a symmetric chamfer distance, i.e. the sum of both chamfers.\n\n gt_mesh: trimesh.base.Trimesh of output mesh from whichever autoencoding reconstruction\n method (see compute_metrics.py for more)\n\n gen_m...
def print_matching(list_a, list_b): counter = 0 for (a, b) in zip(list_a, list_b): counter += 1 print(f'Matched {a} and {b}') print(f'Matched {counter} of {len(list_a)} and {len(list_b)}')
def res2str(name_a, name_b, res_a2b, res_b2a, ms): '\n this normalizes the results by bounding box diagonal\n and put into a new dict\n ' a2b_error_field = ms.mesh(3).vertex_quality_array() b2a_error_field = ms.mesh(5).vertex_quality_array() a2b_error_field /= res_a2b['diag_mesh_0'] b2a_e...
def compare_meshes(meshfile_a, meshfile_b, sample_num): ms = pymeshlab.MeshSet() ms.load_new_mesh(meshfile_a) ms.load_new_mesh(meshfile_b) res_a2b = ms.hausdorff_distance(sampledmesh=0, targetmesh=1, savesample=True, samplevert=False, sampleedge=False, samplefauxedge=False, sampleface=True, samplenum=...
def broyden(g, x_init, J_inv_init, max_steps=50, cvg_thresh=1e-05, dvg_thresh=1, eps=1e-06): 'Find roots of the given function g(x) = 0.\n This function is impleneted based on https://github.com/locuslab/deq.\n\n Tensor shape abbreviation:\n N: number of points\n D: space dimension\n Args:\...
def calculate_iou(gt, prediction): intersection = torch.logical_and(gt, prediction) union = torch.logical_or(gt, prediction) return (torch.sum(intersection) / torch.sum(union))
class VertexJointSelector(nn.Module): def __init__(self, vertex_ids=None, use_hands=True, use_feet_keypoints=True, **kwargs): super(VertexJointSelector, self).__init__() extra_joints_idxs = [] face_keyp_idxs = np.array([vertex_ids['nose'], vertex_ids['reye'], vertex_ids['leye'], vertex_id...
def chamfer_loss_separate(output, target, weight=10000.0, phase='train', debug=False): from chamferdist.chamferdist import ChamferDistance cdist = ChamferDistance() (model2scan, scan2model, idx1, idx2) = cdist(output, target) if (phase == 'train'): return (model2scan, scan2model, idx1, idx2) ...
def normal_loss(output_normals, target_normals, nearest_idx, weight=1.0, phase='train'): '\n Given the set of nearest neighbors found by chamfer distance, calculate the\n L1 discrepancy between the predicted and GT normals on each nearest neighbor point pairs.\n Note: the input normals are already normal...
def color_loss(output_colors, target_colors, nearest_idx, weight=1.0, phase='train', excl_holes=False): '\n Similar to normal loss, used in training a color prediction model.\n ' nearest_idx = nearest_idx.expand(3, (- 1), (- 1)).permute([1, 2, 0]).long() target_colors_chosen = torch.gather(target_co...
class GaussianSmoothing(nn.Module): '\n Apply gaussian smoothing on a\n 1d, 2d or 3d tensor. Filtering is performed seperately for each channel\n in the input using a depthwise convolution.\n Arguments:\n channels (int, sequence): Number of channels of the input tensors. Output will\n ...
class CBatchNorm2d(nn.Module): ' Conditional batch normalization layer class.\n Borrowed from Occupancy Network repo: https://github.com/autonomousvision/occupancy_networks\n Args:\n c_dim (int): dimension of latent conditioned code c\n f_channels (int): number of channels of the feature m...
class Conv2DBlock(nn.Module): def __init__(self, input_nc, output_nc, kernel_size=4, stride=2, padding=1, use_bias=False, use_bn=True, use_relu=True): super(Conv2DBlock, self).__init__() self.use_bn = use_bn self.use_relu = use_relu self.conv = nn.Conv2d(input_nc, output_nc, kerne...
class UpConv2DBlock(nn.Module): def __init__(self, input_nc, output_nc, kernel_size=4, stride=2, padding=1, use_bias=False, use_bn=True, up_mode='upconv', use_dropout=False): super(UpConv2DBlock, self).__init__() assert (up_mode in ('upconv', 'upsample')) self.use_bn = use_bn self...
class GeomConvLayers(nn.Module): '\n A few convolutional layers to smooth the geometric feature tensor\n ' def __init__(self, input_nc=16, hidden_nc=16, output_nc=16, use_relu=False): super().__init__() self.use_relu = use_relu self.conv1 = nn.Conv2d(input_nc, hidden_nc, kernel_...
class GeomConvBottleneckLayers(nn.Module): '\n A u-net-like small bottleneck network for smoothing the geometric feature tensor\n ' def __init__(self, input_nc=16, hidden_nc=16, output_nc=16, use_relu=False): super().__init__() self.use_relu = use_relu self.conv1 = nn.Conv2d(inp...
class GaussianSmoothingLayers(nn.Module): '\n use a fixed, not-trainable gaussian smoother layers for smoothing the geometric feature tensor\n ' def __init__(self, channels=16, kernel_size=5, sigma=1.0): super().__init__() self.conv1 = GaussianSmoothing(channels, kernel_size=kernel_size...
class UnetNoCond5DS(nn.Module): def __init__(self, input_nc=3, output_nc=3, nf=64, up_mode='upconv', use_dropout=False, return_lowres=False, return_2branches=False): super().__init__() assert (up_mode in ('upconv', 'upsample')) self.return_lowres = return_lowres self.return_2branc...
class UnetNoCond6DS(nn.Module): def __init__(self, input_nc=3, output_nc=3, nf=64, up_mode='upconv', use_dropout=False, return_lowres=False, return_2branches=False): super(UnetNoCond6DS, self).__init__() assert (up_mode in ('upconv', 'upsample')) self.return_lowres = return_lowres ...
class UnetNoCond7DS(nn.Module): def __init__(self, input_nc=3, output_nc=3, nf=64, up_mode='upconv', use_dropout=False, return_lowres=False, return_2branches=False): super(UnetNoCond7DS, self).__init__() assert (up_mode in ('upconv', 'upsample')) self.return_lowres = return_lowres ...
class ShapeDecoder(nn.Module): '\n The "Shape Decoder" in the POP paper Fig. 2. The same as the "shared MLP" in the SCALE paper.\n - with skip connection from the input features to the 4th layer\'s output features (like DeepSDF)\n - branches out at the second-to-last layer, one branch for position pred, ...
class PreDeformer(nn.Module): '\n ' def __init__(self, in_size, out_size=3, hsize=64, actv_fn='softplus'): self.hsize = hsize super(PreDeformer, self).__init__() self.conv1 = torch.nn.Conv1d(in_size, self.hsize, 1) self.conv2 = torch.nn.Conv1d(self.hsize, self.hsize, 1) ...
def loadShader(shaderType, shaderFile): strFilename = findFileOrThrow(shaderFile) shaderData = None print(f'Found shader filename = {strFilename}') with open(strFilename, 'r') as f: shaderData = f.read() shader = glCreateShader(shaderType) glShaderSource(shader, shaderData) glCompi...
def createProgram(shaderList): program = glCreateProgram() for shader in shaderList: glAttachShader(program, shader) glLinkProgram(program) status = glGetProgramiv(program, GL_LINK_STATUS) if (status == GL_FALSE): strInfoLog = glGetProgramInfoLog(program) print(('Linker fai...
def findFileOrThrow(strBasename): if os.path.isfile(strBasename): return strBasename LOCAL_FILE_DIR = ('data' + os.sep) GLOBAL_FILE_DIR = (((os.path.dirname(os.path.abspath(__file__)) + os.sep) + 'data') + os.sep) strFilename = (LOCAL_FILE_DIR + strBasename) if os.path.isfile(strFilename):...
def tensor2numpy(tensor): if isinstance(tensor, torch.Tensor): return tensor.detach().cpu().numpy()
def vertex_normal_2_vertex_color(vertex_normal): import torch if torch.is_tensor(vertex_normal): vertex_normal = vertex_normal.detach().cpu().numpy() normal_length = ((vertex_normal ** 2).sum(1) ** 0.5) normal_length = normal_length.reshape((- 1), 1) vertex_normal /= normal_length colo...
def export_ply_with_vquality(filename, v_array=None, f_array=None, vq_array=None): '\n v_array: vertex array\n vq_array: vertex quality array\n ' Nv = (v_array.shape[0] if (v_array is not None) else 0) Nf = (f_array.shape[0] if (f_array is not None) else 0) with open(filename, 'w') as plyfile...
def customized_export_ply(outfile_name, v, f=None, v_n=None, v_c=None, f_c=None, e=None): "\n Author: Jinlong Yang, jyang@tue.mpg.de\n\n Exports a point cloud / mesh to a .ply file\n supports vertex normal and color export\n such that the saved file will be correctly displayed in MeshLab\n\n # v: V...
def save_result_examples(save_dir, model_name, result_name, points, normals=None, patch_color=None, texture=None, coarse_pts=None, gt=None, epoch=None): from os.path import join import numpy as np if (epoch is None): normal_fn = '{}_{}_pred.ply'.format(model_name, result_name) else: no...
def adjust_loss_weights(init_weight, current_epoch, mode='decay', start=400, every=20): if (mode != 'binary'): if (current_epoch < start): if (mode == 'rise'): weight = (init_weight * 1e-06) else: weight = init_weight elif (every == 0): ...
class HierarchicalContextAggregationLoss(nn.Module): '\n Implementation of Hierarchical Context Aggregation\n\n This loss combines multiple PixelwiseContextual losses with different (alpha, beta) scales.\n Given a descriptor with n-dims and n-losses scales, each loss is given n-dims//n-losses.\n Theor...
class PixelwiseContrastiveLoss(nn.Module): '\n Implementation of "pixel-wise" contrastive loss. Contrastive loss typically compares two whole images.\n L = (Y) * (1/2 * d**2) + (1 - Y) * (1/2 * max(0, margin - d)**2)\n\n In this instance, we instead compare pairs of features within those images.\...
class SSIM(nn.Module): 'Layer to compute the weighted SSIM and L1 loss between a pair of images' def __init__(self, ssim_weight=0.85): super().__init__() self.a = ssim_weight self.b = (1 - ssim_weight) self.pool = nn.AvgPool2d(3, 1) self.refl = nn.ReflectionPad2d(1) ...
@dataclass(eq=False) class BaseModel(nn.Module): '\n Base class for PyTorch networks, expanding nn.Module.\n\n Initialization parameters will be automatically added to the state_dict and checked when loading a checkpoint\n\n Required:\n :method forward: Model forward pass (PyTorch standard)\n\n ...
class ConvBlock(nn.Module): def __init__(self, in_ch, out_ch, k_size, stride=1, padding=None, dilation=1, *, bias=False, batch_norm=True, momentum=0.1, activation=None, drop_rate=None): super().__init__() layers = OrderedDict() padding = (padding or (dilation if (dilation > 1) else (k_siz...
class ResidualBlock(nn.Module): def __init__(self, in_ch, out_ch, stride=1, padding=None, dilation=1, activation=nn.ReLU): super().__init__() self.block1 = ConvBlock(in_ch, out_ch, 3, stride, padding, dilation, activation=activation) self.block2 = ConvBlock(out_ch, out_ch, 3, 1, padding, ...
class SimpleConvBlock(nn.Module): 'Layer to perform a convolution followed by ELU' def __init__(self, in_channels, out_channels): super().__init__() self.conv = Conv3x3(in_channels, out_channels) self.nonlin = nn.ELU(inplace=True) def forward(self, x): return self.nonlin(...
class Conv3x3(nn.Module): 'Layer to pad and convolve input' def __init__(self, in_channels, out_channels, use_refl=True): super().__init__() self.pad = (nn.ReflectionPad2d(1) if use_refl else nn.ZeroPad2d(1)) self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3) def forwa...
@dataclass(eq=False) class DeFeatNet(BaseModel): num_layers: int preres: bool scales: list = range(4) use_skips: bool = True n_dims: int = 3 spp_branches: list = None activation: str = 'relu' im_pad: int = None norm: bool = True def __post_init__(self): super().__post_...
@dataclass(eq=False) class DepthNet(BaseModel): num_layers: int preres: bool = True scales: list = range(4) use_skips: bool = True def __post_init__(self): super().__post_init__() self.enc_ch = np.array([64, 64, 128, 256, 512]) self.dec_ch = np.array([16, 32, 64, 128, 256]...
def discriminator(glove, hidden_size): hypo_input = Input(shape=(None,), dtype='int32') embeds = make_fixed_embeddings(glove, None)(hypo_input) lstm = LSTM(hidden_size, inner_activation='sigmoid')(embeds) output = Dense(1, activation='sigmoid')(lstm) discriminator = Model([hypo_input], output) ...
def adverse_model(discriminator): train_input = Input(shape=(None,), dtype='int32') hypo_input = Input(shape=(None,), dtype='int32') def margin_opt(inputs): assert (len(inputs) == 2), ('Margin Output needs 2 inputs, %d given' % len(inputs)) return (K.log(inputs[0]) + K.log((1 - inputs[1])...
def minimize(y_true, y_pred): return K.abs(K.mean(y_pred, axis=(- 1)))
def reinit(ad_model): ad_model.compile(loss=minimize, optimizer='adam')
class FeedLSTM(LSTM): def __init__(self, feed_layer=None, **kwargs): self.feed_layer = feed_layer self.supports_masking = False super(FeedLSTM, self).__init__(**kwargs) def set_state(self, noise): K.set_value(self.states[1], noise) def get_initial_states(self, x): ...
class LstmAttentionLayer(LSTM): def __init__(self, feed_state=False, **kwargs): self.feed_state = feed_state self.supports_masking = False super(LstmAttentionLayer, self).__init__(**kwargs) def get_output_shape_for(self, input_shape): if self.return_sequences: ret...
def train(train, dev, model, model_dir, batch_size): if (not os.path.exists(model_dir)): os.makedirs(model_dir) es = EarlyStopping(patience=2) saver = ModelCheckpoint((model_dir + '/model.weights'), monitor='val_loss', save_best_only=True) csv = CsvHistory((model_dir + '/history.csv')) ret...
def attention_model(hidden_size, glove): prem_input = Input(shape=(None,), dtype='int32') hypo_input = Input(shape=(None,), dtype='int32') prem_embeddings = make_fixed_embeddings(glove, None)(prem_input) hypo_embeddings = make_fixed_embeddings(glove, None)(hypo_input) premise_layer = LSTM(output_d...
def attention_bnorm_model(hidden_size, glove): prem_input = Input(shape=(None,), dtype='int32') hypo_input = Input(shape=(None,), dtype='int32') prem_embeddings = make_fixed_embeddings(glove, None)(prem_input) hypo_embeddings = make_fixed_embeddings(glove, None)(hypo_input) premise_layer = LSTM(ou...
def make_fixed_embeddings(glove, seq_len): glove_mat = np.array(glove.values()) return Embedding(input_dim=glove_mat.shape[0], output_dim=glove_mat.shape[1], weights=[glove_mat], trainable=False, input_length=seq_len)
class CsvHistory(Callback): def __init__(self, filename): self.file = open(filename, 'a', 0) self.writer = csv.writer(self.file) self.header = True def on_epoch_end(self, epoch, logs={}): if self.header: self.writer.writerow((['epoch'] + logs.keys())) ...
def merge_result_batches(batches): res = list(batches[0]) for i in range(1, len(batches)): for j in range(len(res)): res[j] = np.concatenate([res[j], batches[i][j]]) return res
class HierarchicalSoftmax(Layer): def __init__(self, output_dim, init='glorot_uniform', **kwargs): self.init = initializations.get(init) self.output_dim = output_dim def hshape(n): from math import sqrt, ceil l1 = ceil(sqrt(n)) l2 = ceil((n / l1)) ...
def hs_categorical_crossentropy(y_true, y_pred): y_pred = T.clip(y_pred, _EPSILON, (1.0 - _EPSILON)) return T.nnet.categorical_crossentropy(y_pred, y_true)
def _remove_duplicate(input): return list(set(input))
def build_stage_one_edges(res, graph_voc): '\n :param res:\n :param graph_voc:\n :return: edge_idx [[1,2,3],[0,1,0]]\n ' edge_idx = [] for sample in res: sample_idx = list(map((lambda x: graph_voc.word2idx[x]), sample)) for i in range((len(sample_idx) - 1)): edge_id...
def build_stage_two_edges(res, graph_voc): '\n :param res:\n :param graph_voc:\n :return: edge_idx [[1,2,3],[0,1,0]]\n ' edge_idx = [] for sample in res: sample_idx = list(map((lambda x: graph_voc.word2idx[x]), sample)) edge_idx.extend([(sample_idx[0], sample_idx[i]) for i in r...
def build_cominbed_edges(res, graph_voc): '\n :param res:\n :param graph_voc:\n :return: edge_idx [[1,2,3],[0,1,0]]\n ' edge_idx = [] for sample in res: sample_idx = list(map((lambda x: graph_voc.word2idx[x]), sample)) for i in range((len(sample_idx) - 1)): edge_idx...
def expand_level2(): level2 = ['001-009', '010-018', '020-027', '030-041', '042', '045-049', '050-059', '060-066', '070-079', '080-088', '090-099', '100-104', '110-118', '120-129', '130-136', '137-139', '140-149', '150-159', '160-165', '170-176', '176', '179-189', '190-199', '200-208', '209', '210-229', '230-234'...
def build_icd9_tree(unique_codes): res = [] graph_voc = Voc() root_node = 'icd9_root' level3_dict = expand_level2() for code in unique_codes: level1 = code level2 = (level1[:4] if (level1[0] == 'E') else level1[:3]) level3 = level3_dict[level2] level4 = root_node ...
def build_atc_tree(unique_codes): res = [] graph_voc = Voc() root_node = 'atc_root' for code in unique_codes: sample = (([code] + [code[:i] for i in [4, 3, 1]]) + [root_node]) graph_voc.add_sentence(sample) res.append(sample) return (res, graph_voc)
class BertConfig(object): 'Configuration class to store the configuration of a `BertModel`.\n ' def __init__(self, vocab_size_or_config_json_file, hidden_size=300, num_hidden_layers=2, num_attention_heads=4, intermediate_size=300, hidden_act='relu', hidden_dropout_prob=0.4, attention_probs_dropout_prob=0....
class OntologyEmbedding(nn.Module): def __init__(self, voc, build_tree_func, in_channels=100, out_channels=20, heads=5): super(OntologyEmbedding, self).__init__() (res, graph_voc) = build_tree_func(list(voc.idx2word.values())) stage_one_edges = build_stage_one_edges(res, graph_voc) ...
class MessagePassing(nn.Module): 'Base class for creating message passing layers\n\n .. math::\n \\mathbf{x}_i^{\\prime} = \\gamma_{\\mathbf{\\Theta}} \\left( \\mathbf{x}_i,\n \\square_{j \\in \\mathcal{N}(i)} \\, \\phi_{\\mathbf{\\Theta}}\n \\left(\\mathbf{x}_i, \\mathbf{x}_j,\\mathbf{e}_...
class GATConv(MessagePassing): 'The graph attentional operator from the `"Graph Attention Networks"\n <https://arxiv.org/abs/1710.10903>`_ paper\n\n .. math::\n \\mathbf{x}^{\\prime}_i = \\alpha_{i,i}\\mathbf{\\Theta}\\mathbf{x}_{j} +\n \\sum_{j \\in \\mathcal{N}(i)} \\alpha_{i,j}\\mathbf{\\Th...
class ConcatEmbeddings(nn.Module): 'Concat rx and dx ontology embedding for easy access\n ' def __init__(self, config, dx_voc, rx_voc): super(ConcatEmbeddings, self).__init__() self.special_embedding = nn.Parameter(torch.Tensor(((config.vocab_size - len(dx_voc.idx2word)) - len(rx_voc.idx2w...
class FuseEmbeddings(nn.Module): 'Construct the embeddings from ontology, patient info and type embeddings.\n ' def __init__(self, config, dx_voc, rx_voc): super(FuseEmbeddings, self).__init__() self.ontology_embedding = ConcatEmbeddings(config, dx_voc, rx_voc) self.type_embedding ...
class Voc(object): def __init__(self): self.idx2word = {} self.word2idx = {} def add_sentence(self, sentence): for word in sentence: if (word not in self.word2idx): self.idx2word[len(self.word2idx)] = word self.word2idx[word] = len(self.wor...
class EHRTokenizer(object): 'Runs end-to-end tokenization' def __init__(self, data_dir, special_tokens=('[PAD]', '[CLS]', '[MASK]')): self.vocab = Voc() self.vocab.add_sentence(special_tokens) self.rx_voc = self.add_vocab(os.path.join(data_dir, 'rx-vocab.txt')) self.dx_voc = s...
class EHRDataset(Dataset): def __init__(self, data_pd, tokenizer: EHRTokenizer, max_seq_len): self.data_pd = data_pd self.tokenizer = tokenizer self.seq_len = max_seq_len self.sample_counter = 0 def transform_data(data): '\n :param data: raw data fo...
def load_dataset(args): data_dir = args.data_dir max_seq_len = args.max_seq_length tokenizer = EHRTokenizer(data_dir) data = pd.read_pickle(os.path.join(data_dir, 'data-multi-visit.pkl')) ids_file = [os.path.join(data_dir, 'train-id.txt'), os.path.join(data_dir, 'eval-id.txt'), os.path.join(data_d...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--model_name', default='GBert-predict', type=str, required=False, help='model name') parser.add_argument('--data_dir', default='../data', type=str, required=False, help='The input data dir.') parser.add_argument('--pretrain_dir', defa...
class Voc(object): def __init__(self): self.idx2word = {} self.word2idx = {} def add_sentence(self, sentence): for word in sentence: if (word not in self.word2idx): self.idx2word[len(self.word2idx)] = word self.word2idx[word] = len(self.wor...
class EHRTokenizer(object): 'Runs end-to-end tokenization' def __init__(self, data_dir, special_tokens=('[PAD]', '[CLS]', '[MASK]')): self.vocab = Voc() self.vocab.add_sentence(special_tokens) self.rx_voc = self.add_vocab(os.path.join(data_dir, 'rx-vocab.txt')) self.dx_voc = s...
def save(): tokenizer = EHRTokenizer(data_dir='../data') logger.info('Use Pretraining model') model = TSNE.from_pretrained(model_name, dx_voc=tokenizer.dx_voc, rx_voc=tokenizer.rx_voc) model(output_dir=output_dir) logger.info(('# of model parameters: ' + str(get_n_params(model))))
def generate_meta(build_tree_func, task, output_path='emb-meta.tsv'): tokenizer = EHRTokenizer(data_dir='../data') voc = (tokenizer.dx_voc if (task == 0) else tokenizer.rx_voc) (res, graph_voc) = build_tree_func(list(voc.idx2word.values())) level_dict = {} for row in res: for (level, item)...
def generate_meta_for_not_graph(task, output_path='emb-meta.tsv'): tokenizer = EHRTokenizer(data_dir='../data') voc = (tokenizer.dx_voc if (task == 0) else tokenizer.rx_voc) with open(os.path.join(output_dir, (('dx-' if (task == 0) else 'rx-') + output_path)), 'w') as fout: for (word, _) in voc.wo...
class HierarchicalContextAggregationLoss(nn.Module): '\n Implementation of Hierarchical Context Aggregation\n\n This loss combines multiple PixelwiseContextual losses with different (alpha, beta) scales.\n Given a descriptor with n-dims and n-losses scales, each loss is given n-dims//n-losses.\n Theor...
class PixelwiseContrastiveLoss(nn.Module): '\n Implementation of "pixel-wise" contrastive loss. Contrastive loss typically compares two whole images.\n L = (Y) * (1/2 * d**2) + (1 - Y) * (1/2 * max(0, margin - d)**2)\n\n In this instance, we instead compare pairs of features within those images.\...
def main(): args = parser.parse_args() device = ops.get_device() ckpt_file = Path(args.model_path, args.model_name).with_suffix('.pt') img_file = Path(args.image_file) img_np = imread(img_file) img_torch = ops.img2torch(img_np, batched=True).to(device) print(f'Image size (np): {img_np.shap...
class SiameseSand(nn.Module): def __init__(self, n_dims): super().__init__() self.n_dims = n_dims self.branch = Sand(self.n_dims) def forward(self, features): (f1, f2) = torch.chunk(features, 2, dim=2) (d1, d2) = (self.branch(f1), self.branch(f2)) out = torch....
class Timer(): 'Context manager to time a piece of code, including GPU synchronization.' def __init__(self, as_ms=False): (self.start, self.end) = (None, None) self.scale = (1000 if as_ms else 1) self.is_gpu = torch.cuda.is_available() def __enter__(self): if self.is_gpu:...
def main(): with Timer() as t: time.sleep(2) print(f'{t.elapsed} secs') with Timer(as_ms=True) as t: time.sleep(0.002) print(f'{t.elapsed} ms')