code stringlengths 17 6.64M |
|---|
class ISAB(nn.Module):
def __init__(self, dim_in, dim_out, num_heads, num_inds, ln=False):
super(ISAB, self).__init__()
self.I = nn.Parameter(torch.Tensor(1, num_inds, dim_out))
nn.init.xavier_uniform_(self.I)
self.mab0 = MAB(dim_out, dim_in, dim_out, num_heads, ln=ln)
sel... |
class PMA(nn.Module):
def __init__(self, dim, num_heads, num_seeds, ln=False):
super(PMA, self).__init__()
self.S = nn.Parameter(torch.Tensor(1, num_seeds, dim))
nn.init.xavier_uniform_(self.S)
self.mab = MAB(dim, dim, dim, num_heads, ln=ln)
def forward(self, X):
retu... |
def generate_benchmark():
if (not os.path.isdir('benchmark')):
os.makedirs('benchmark')
N_list = np.random.randint(N_min, N_max, args.num_bench)
data = []
ll = 0.0
for N in tqdm(N_list):
(X, labels, pi, params) = mog.sample(B, N, K, return_gt=True)
ll += mog.log_prob(X, pi,... |
def train():
if (not os.path.isdir(save_dir)):
os.makedirs(save_dir)
if (not os.path.isfile(benchfile)):
generate_benchmark()
bench = torch.load(benchfile)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(args.run_name)
logger.addHandler(logging.FileHandler(os... |
def test(bench, verbose=True):
net.eval()
(data, oracle_ll) = bench
avg_ll = 0.0
for X in data:
X = X.cuda()
avg_ll += mog.log_prob(X, *mvn.parse(net(X))).item()
avg_ll /= len(data)
line = 'test ll {:.4f} (oracle {:.4f})'.format(avg_ll, oracle_ll)
if verbose:
loggin... |
def plot():
net.eval()
X = mog.sample(B, np.random.randint(N_min, N_max), K)
(pi, params) = mvn.parse(net(X))
(ll, labels) = mog.log_prob(X, pi, params, return_labels=True)
(fig, axes) = plt.subplots(2, (B // 2), figsize=(((7 * B) // 5), 5))
mog.plot(X, labels, params, axes)
plt.show()
|
class Logger():
' Writes results of training/testing '
@classmethod
def initialize(cls, args, training):
logtime = datetime.datetime.now().__format__('_%m%d_%H%M%S')
logpath = (args.logpath if training else (('_TEST_' + args.load.split('/')[(- 1)].split('.')[0]) + logtime))
if (lo... |
class AverageMeter():
' Stores loss, evaluation results, selected layers '
def __init__(self, benchamrk):
' Constructor of AverageMeter '
self.buffer_keys = ['pck']
self.buffer = {}
for key in self.buffer_keys:
self.buffer[key] = []
self.loss_buffer = []
... |
class CorrespondenceDataset(Dataset):
' Parent class of PFPascal, PFWillow, and SPair '
def __init__(self, benchmark, datapath, thres, split):
' CorrespondenceDataset constructor '
super(CorrespondenceDataset, self).__init__()
self.metadata = {'pfwillow': ('PF-WILLOW', 'test_pairs.csv... |
def load_dataset(benchmark, datapath, thres, split='test'):
' Instantiate a correspondence dataset '
correspondence_benchmark = {'spair': spair.SPairDataset, 'pfpascal': pfpascal.PFPascalDataset, 'pfwillow': pfwillow.PFWillowDataset}
dataset = correspondence_benchmark.get(benchmark)
if (dataset is Non... |
def download_from_google(token_id, filename):
' Download desired filename from Google drive '
print(('Downloading %s ...' % os.path.basename(filename)))
url = 'https://docs.google.com/uc?export=download'
destination = (filename + '.tar.gz')
session = requests.Session()
response = session.get(u... |
def get_confirm_token(response):
'Retrieves confirm token'
for (key, value) in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
|
def save_response_content(response, destination):
'Saves the response to the destination'
chunk_size = 32768
with open(destination, 'wb') as file:
for chunk in response.iter_content(chunk_size):
if chunk:
file.write(chunk)
|
def download_dataset(datapath, benchmark):
'Downloads semantic correspondence benchmark dataset from Google drive'
if (not os.path.isdir(datapath)):
os.mkdir(datapath)
file_data = {'spair': ('1KSvB0k2zXA06ojWNvFjBv0Ake426Y76k', 'SPair-71k'), 'pfpascal': ('1OOwpGzJnTsFXYh-YffMQ9XKM_Kl_zdzg', 'PF-PA... |
class SPairDataset(CorrespondenceDataset):
def __init__(self, benchmark, datapath, thres, split):
' SPair-71k dataset constructor '
super(SPairDataset, self).__init__(benchmark, datapath, thres, split)
self.train_data = open(self.spt_path).read().split('\n')
self.train_data = self... |
def conv3x3(in_planes, out_planes, stride=1):
' 3x3 convolution with padding '
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=2, bias=False)
|
def conv1x1(in_planes, out_planes, stride=1):
' 1x1 convolution '
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, groups=2, bias=False)
|
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = conv1x1(inplanes, planes)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(planes, planes, stride)
self.bn2... |
class Backbone(nn.Module):
def __init__(self, block, layers, zero_init_residual=False):
super(Backbone, self).__init__()
self.inplanes = 128
self.conv1 = nn.Conv2d(6, 128, kernel_size=7, stride=2, padding=3, groups=2, bias=False)
self.bn1 = nn.BatchNorm2d(128)
self.relu = ... |
def resnet101(pretrained=False, **kwargs):
'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = Backbone(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
weights = model_zoo.load_url(model_urls['resnet101'])
... |
class KernelGenerator():
def __init__(self, ksz, ktype):
self.ksz = ksz
self.idx4d = Geometry.init_idx4d(ksz)
self.kernel = torch.zeros((ksz, ksz, ksz, ksz)).cuda()
self.center = ((ksz // 2), (ksz // 2))
self.ktype = ktype
def quadrant(self, crd):
if (crd[0] <... |
class Correlation():
@classmethod
def mutual_nn_filter(cls, correlation_matrix, eps=1e-30):
" Mutual nearest neighbor filtering (Rocco et al. NeurIPS'18 )"
corr_src_max = torch.max(correlation_matrix, dim=2, keepdim=True)[0]
corr_trg_max = torch.max(correlation_matrix, dim=1, keepdim=... |
class CHMLearner(nn.Module):
def __init__(self, ktype, feat_dim):
super(CHMLearner, self).__init__()
self.scales = [0.5, 1, 2]
self.conv2ds = nn.ModuleList([nn.Conv2d(feat_dim, (feat_dim // 4), kernel_size=3, padding=1, bias=False) for _ in self.scales])
ksz_translation = 5
... |
class CHMNet(nn.Module):
def __init__(self, ktype):
super(CHMNet, self).__init__()
self.backbone = backbone.resnet101(pretrained=True)
self.learner = chmlearner.CHMLearner(ktype, feat_dim=1024)
def forward(self, src_img, trg_img):
(src_feat, trg_feat) = self.extract_features(... |
def test(model, dataloader):
average_meter = AverageMeter(dataloader.dataset.benchmark)
model.eval()
for (idx, batch) in enumerate(dataloader):
corr_matrix = model(batch['src_img'].cuda(), batch['trg_img'].cuda())
prd_kps = Geometry.transfer_kps(corr_matrix, batch['src_kps'].cuda(), batch[... |
def train(epoch, model, dataloader, optimizer, training):
(model.train() if training else model.eval())
average_meter = AverageMeter(dataloader.dataset.benchmark)
for (idx, batch) in enumerate(dataloader):
corr_matrix = model(batch['src_img'].cuda(), batch['trg_img'].cuda())
prd_trg_kps = ... |
class Logger():
'Writes results of training/testing'
@classmethod
def initialize(cls, args):
logtime = datetime.datetime.now().__format__('_%m%d_%H%M%S')
logpath = args.logpath
cls.logpath = os.path.join('logs', ((logpath + logtime) + '.log'))
cls.benchmark = args.benchmar... |
class AverageMeter():
'Stores loss, evaluation results, selected layers'
def __init__(self, benchamrk):
'Constructor of AverageMeter'
if (benchamrk == 'caltech'):
self.buffer_keys = ['ltacc', 'iou']
else:
self.buffer_keys = ['pck']
self.buffer = {}
... |
class SupervisionStrategy(ABC):
'Different strategies for methods:'
@abstractmethod
def get_image_pair(self, batch, *args):
pass
@abstractmethod
def get_correlation(self, correlation_matrix):
pass
@abstractmethod
def compute_loss(self, correlation_matrix, *args):
... |
class StrongSupStrategy(SupervisionStrategy):
def get_image_pair(self, batch, *args):
'Returns (semantically related) pairs for strongly-supervised training'
return (batch['src_img'], batch['trg_img'])
def get_correlation(self, correlation_matrix):
"Returns correlation matrices of 'A... |
class WeakSupStrategy(SupervisionStrategy):
def get_image_pair(self, batch, *args):
'Forms positive/negative image paris for weakly-supervised training'
training = args[0]
self.bsz = len(batch['src_img'])
if training:
shifted_idx = np.roll(np.arange(self.bsz), (- 1))
... |
def fix_randseed(seed):
'Fixes random seed for reproducibility'
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
|
def mean(x):
'Computes average of a list'
return ((sum(x) / len(x)) if (len(x) > 0) else 0.0)
|
def where(predicate):
'Predicate must be a condition on nd-tensor'
matching_indices = predicate.nonzero()
if (len(matching_indices) != 0):
matching_indices = matching_indices.t().squeeze(0)
return matching_indices
|
class CorrespondenceDataset(Dataset):
'Parent class of PFPascal, PFWillow, Caltech, and SPair'
def __init__(self, benchmark, datapath, thres, device, split):
'CorrespondenceDataset constructor'
super(CorrespondenceDataset, self).__init__()
self.metadata = {'pfwillow': ('PF-WILLOW', 't... |
def find_knn(db_vectors, qr_vectors):
'Finds K-nearest neighbors (Euclidean distance)'
db = db_vectors.unsqueeze(1).repeat(1, qr_vectors.size(0), 1)
qr = qr_vectors.unsqueeze(0).repeat(db_vectors.size(0), 1, 1)
dist = (db - qr).pow(2).sum(2).pow(0.5).t()
(_, nearest_idx) = dist.min(dim=1)
retu... |
def load_dataset(benchmark, datapath, thres, device, split='test'):
'Instantiates desired correspondence dataset'
correspondence_benchmark = {'pfpascal': pfpascal.PFPascalDataset, 'pfwillow': pfwillow.PFWillowDataset, 'caltech': caltech.CaltechDataset, 'spair': spair.SPairDataset}
dataset = correspondence... |
def download_from_google(token_id, filename):
'Downloads desired filename from Google drive'
print(('Downloading %s ...' % os.path.basename(filename)))
url = 'https://docs.google.com/uc?export=download'
destination = (filename + '.tar.gz')
session = requests.Session()
response = session.get(ur... |
def get_confirm_token(response):
'Retrieves confirm token'
for (key, value) in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
|
def save_response_content(response, destination):
'Saves the response to the destination'
chunk_size = 32768
with open(destination, 'wb') as file:
for chunk in response.iter_content(chunk_size):
if chunk:
file.write(chunk)
|
def download_dataset(datapath, benchmark):
'Downloads semantic correspondence benchmark dataset from Google drive'
if (not os.path.isdir(datapath)):
os.mkdir(datapath)
file_data = {'pfwillow': ('1tDP0y8RO5s45L-vqnortRaieiWENQco_', 'PF-WILLOW'), 'pfpascal': ('1OOwpGzJnTsFXYh-YffMQ9XKM_Kl_zdzg', 'PF... |
class SPairDataset(CorrespondenceDataset):
'Inherits CorrespondenceDataset'
def __init__(self, benchmark, datapath, thres, device, split):
'SPair-71k dataset constructor'
super(SPairDataset, self).__init__(benchmark, datapath, thres, device, split)
self.train_data = open(self.spt_path... |
class Correlation():
@classmethod
def bmm_interp(cls, src_feat, trg_feat, interp_size):
'Performs batch-wise matrix-multiplication after interpolation'
src_feat = F.interpolate(src_feat, interp_size, mode='bilinear', align_corners=True)
trg_feat = F.interpolate(trg_feat, interp_size, ... |
class Norm():
'Vector normalization'
@classmethod
def feat_normalize(cls, x, interp_size):
'L2-normalizes given 2D feature map after interpolation'
x = F.interpolate(x, interp_size, mode='bilinear', align_corners=True)
return x.pow(2).sum(1).view(x.size(0), (- 1))
@classmetho... |
def conv3x3(in_planes, out_planes, stride=1):
'3x3 convolution with padding'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, groups=2, bias=False)
|
def conv1x1(in_planes, out_planes, stride=1):
'1x1 convolution'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, groups=2, bias=False)
|
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = conv1x1(inplanes, planes)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(planes, planes, stride)
self.bn2... |
class Backbone(nn.Module):
def __init__(self, block, layers, zero_init_residual=False):
super(Backbone, self).__init__()
self.inplanes = 128
self.conv1 = nn.Conv2d(6, 128, kernel_size=7, stride=2, padding=3, groups=2, bias=False)
self.bn1 = nn.BatchNorm2d(128)
self.relu = ... |
def resnet50(pretrained=False, **kwargs):
'Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = Backbone(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
weights = model_zoo.load_url(model_urls['resnet50'])
... |
def resnet101(pretrained=False, **kwargs):
'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n '
model = Backbone(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
weights = model_zoo.load_url(model_urls['resnet101'])
... |
class DynamicHPF():
'Dynamic Hyperpixel Flow (DHPF)'
def __init__(self, backbone, device, img_side=240):
'Constructor for DHPF'
super(DynamicHPF, self).__init__()
if (backbone == 'resnet50'):
self.backbone = resnet.resnet50(pretrained=True).to(device)
self.in_c... |
class Objective():
'Provides training objectives of DHPF'
@classmethod
def initialize(cls, target_rate, alpha):
cls.softmax = torch.nn.Softmax(dim=1)
cls.target_rate = target_rate
cls.alpha = alpha
cls.eps = 1e-30
@classmethod
def weighted_cross_entropy(cls, corre... |
def test(model, dataloader):
'Code for testing DHPF'
average_meter = AverageMeter(dataloader.dataset.benchmark)
for (idx, batch) in enumerate(dataloader):
(correlation_matrix, layer_sel) = model(batch['src_img'], batch['trg_img'])
prd_kps = Geometry.transfer_kps(correlation_matrix, batch['... |
def train(epoch, model, dataloader, strategy, optimizer, training):
'Code for training DHPF'
(model.train() if training else model.eval())
average_meter = AverageMeter(dataloader.dataset.benchmark)
for (idx, batch) in enumerate(dataloader):
(src_img, trg_img) = strategy.get_image_pair(batch, t... |
def parse_layers(layer_ids):
'Parse list of layer ids (int) into string format'
layer_str = ''.join(list(map((lambda x: ('%d,' % x)), layer_ids)))[:(- 1)]
layer_str = (('(' + layer_str) + ')')
return layer_str
|
def find_topk(membuf, kval):
'Return top-k performance along with layer combinations'
membuf.sort(key=(lambda x: x[0]), reverse=True)
return membuf[:kval]
|
def log_evaluation(layers, score, elapsed):
'Log a single evaluation result'
logging.info(('%20s: %4.2f %% %5.1f sec' % (layers, score, elapsed)))
|
def log_selected(depth, membuf_topk):
'Log selected layers at each depth'
logging.info((' ===================== Depth %d =====================' % depth))
for (score, layers) in membuf_topk:
logging.info(('%20s: %4.2f %%' % (layers, score)))
logging.info(' ======================================... |
def beamsearch_hp(datapath, benchmark, backbone, thres, alpha, logpath, candidate_base, candidate_layers, beamsize, maxdepth):
'Implementation of beam search for hyperpixel layers'
device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu'))
model = hpflow.HyperpixelFlow(backbone, '0', benchm... |
class CorrespondenceDataset(Dataset):
'Parent class of PFPascal, PFWillow, Caltech, and SPair'
def __init__(self, benchmark, datapath, thres, device, split):
'CorrespondenceDataset constructor'
super(CorrespondenceDataset, self).__init__()
self.metadata = {'pfwillow': ('PF-WILLOW', 't... |
class UnNormalize():
'Image unnormalization'
def __init__(self):
self.mean = [0.485, 0.456, 0.406]
self.std = [0.229, 0.224, 0.225]
def __call__(self, image):
img = image.clone()
for (im_channel, mean, std) in zip(img, self.mean, self.std):
im_channel.mul_(std... |
class Normalize():
'Image normalization'
def __init__(self, image_keys, norm_range=True):
self.image_keys = image_keys
self.norm_range = norm_range
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
def __call__(self, sample):
for... |
def load_dataset(benchmark, datapath, thres, device, split='test'):
'Instantiate desired correspondence dataset'
correspondence_benchmark = {'pfpascal': pfpascal.PFPascalDataset, 'pfwillow': pfwillow.PFWillowDataset, 'caltech': caltech.CaltechDataset, 'spair': spair.SPairDataset}
dataset = correspondence_... |
def download_from_google(token_id, filename):
'Download desired filename from Google drive'
print(('Downloading %s ...' % os.path.basename(filename)))
url = 'https://docs.google.com/uc?export=download'
destination = (filename + '.tar.gz')
session = requests.Session()
response = session.get(url... |
def get_confirm_token(response):
'Retrieve confirm token'
for (key, value) in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
|
def save_response_content(response, destination):
'Save the response to the destination'
chunk_size = 32768
with open(destination, 'wb') as file:
for chunk in response.iter_content(chunk_size):
if chunk:
file.write(chunk)
|
def download_dataset(datapath, benchmark):
'Download desired semantic correspondence benchmark dataset from Google drive'
if (not os.path.isdir(datapath)):
os.mkdir(datapath)
file_data = {'pfwillow': ('1tDP0y8RO5s45L-vqnortRaieiWENQco_', 'PF-WILLOW'), 'pfpascal': ('1OOwpGzJnTsFXYh-YffMQ9XKM_Kl_zdz... |
class SPairDataset(CorrespondenceDataset):
'Inherits CorrespondenceDataset'
def __init__(self, benchmark, datapath, thres, device, split):
'SPair-71k dataset constructor'
super(SPairDataset, self).__init__(benchmark, datapath, thres, device, split)
self.train_data = open(self.spt_path... |
def run(datapath, benchmark, backbone, thres, alpha, hyperpixel, logpath, beamsearch, model=None, dataloader=None, visualize=False):
'Runs Hyperpixel Flow framework'
if (not os.path.isdir('logs')):
os.mkdir('logs')
if (not beamsearch):
cur_datetime = datetime.datetime.now().__format__('_%m... |
class Evaluator():
'To evaluate and log evaluation metrics: PCK, LT-ACC, IoU'
def __init__(self, benchmark, device):
'Constructor for Evaluator'
self.eval_buf = {'pfwillow': {'pck': [], 'cls_pck': dict()}, 'pfpascal': {'pck': [], 'cls_pck': dict()}, 'spair': {'pck': [], 'cls_pck': dict()}, 'c... |
def correct_kps(trg_kps, prd_kps, pckthres, alpha=0.1):
'Compute the number of correctly transferred key-points'
l2dist = torch.pow(torch.sum(torch.pow((trg_kps - prd_kps), 2), 0), 0.5)
thres = pckthres.expand_as(l2dist).float()
correct_pts = torch.le(l2dist, (thres * alpha))
return torch.sum(corr... |
def pts2ptstr(pts):
'Convert tensor of points to string'
x_str = str(list(pts[0].cpu().numpy()))
x_str = x_str[1:(len(x_str) - 1)]
y_str = str(list(pts[1].cpu().numpy()))
y_str = y_str[1:(len(y_str) - 1)]
return (x_str, y_str)
|
def pts2mask(x_pts, y_pts, shape):
'Build a binary mask tensor base on given xy-points'
(x_idx, y_idx) = draw.polygon(x_pts, y_pts, shape)
mask = np.zeros(shape, dtype=np.bool)
mask[(x_idx, y_idx)] = True
return mask
|
def ptstr2mask(x_str, y_str, out_h, out_w):
'Convert xy-point mask (string) to tensor mask'
x_pts = np.fromstring(x_str, sep=',')
y_pts = np.fromstring(y_str, sep=',')
mask_np = pts2mask(y_pts, x_pts, [out_h, out_w])
mask = torch.tensor(mask_np.astype(np.float32)).unsqueeze(0).unsqueeze(0).float()... |
def intersection_over_union(mask1, mask2):
'Computes IoU between two masks'
rel_part_weight = (torch.sum(torch.sum(mask2.gt(0.5).float(), 2, True), 3, True) / torch.sum(mask2.gt(0.5).float()))
part_iou = (torch.sum(torch.sum((mask1.gt(0.5) & mask2.gt(0.5)).float(), 2, True), 3, True) / torch.sum(torch.sum... |
def label_transfer_accuracy(mask1, mask2):
'LT-ACC measures the overlap with emphasis on the background class'
return torch.mean((mask1.gt(0.5) == mask2.gt(0.5)).double()).item()
|
def init_logger(logfile):
'Initialize logging settings'
logging.basicConfig(filemode='w', filename=logfile, level=logging.INFO, format='%(message)s', datefmt='%m-%d %H:%M:%S')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(message)s')
console.... |
def log_args(args):
'Log program arguments'
logging.info('\n+========== Hyperpixel Flow Arguments ===========+')
for arg_key in args.__dict__:
logging.info(('| %20s: %-24s |' % (arg_key, str(args.__dict__[arg_key]))))
logging.info('+================================================+\n')
|
def resize(img, kps, side_thres=300):
'Resize given image with imsize: (1, 3, H, W)'
imsize = torch.tensor(img.size()).float()
kps = kps.float()
side_max = torch.max(imsize)
inter_ratio = 1.0
if (side_max > side_thres):
inter_ratio = (side_thres / side_max)
img = F.interpolate(... |
def where(predicate):
'Returns indices which match given predicate'
matching_idx = predicate.nonzero()
n_match = len(matching_idx)
if (n_match != 0):
matching_idx = matching_idx.t().squeeze(0)
return matching_idx
|
def intersect1d(tensor1, tensor2):
'Takes two 1D tensor and returns tensor of common values'
aux = torch.cat((tensor1, tensor2), dim=0)
aux = aux.sort()[0]
return aux[:(- 1)][(aux[1:] == aux[:(- 1)]).data]
|
def parse_hyperpixel(hyperpixel_ids):
'Parse given hyperpixel list (string -> int)'
return list(map(int, re.findall('\\d+', hyperpixel_ids)))
|
def visualize_prediction(src_kps, prd_kps, src_img, trg_img, vispath, relaxation=2000):
'TPS transform source image using predicted correspondences'
src_imsize = src_img.size()[1:][::(- 1)]
trg_imsize = trg_img.size()[1:][::(- 1)]
img_tps = geometry.ImageTPS(src_kps, prd_kps, src_imsize, trg_imsize, r... |
class MyDataset(Dataset):
def __init__(self, X, y):
self.data = X
self.target = y
def __getitem__(self, index):
x = self.data[index]
y = self.target[index]
return (x, y)
def __len__(self):
return len(self.data)
|
def lossFunctionKLD(mu, logvar):
'Compute KL divergence loss. \n Parameters\n ----------\n mu: Tensor\n Latent space mean of encoder distribution.\n logvar: Tensor\n Latent space log variance of encoder distribution.\n '
kl_error = ((- 0.5) * torch.sum((((1 + logvar) - mu.pow(2)) ... |
def recoLossGaussian(predicted_s, x, gaussian_noise_std, data_std):
'\n Compute reconstruction loss for a Gaussian noise model. \n This is essentially the MSE loss with a factor depending on the standard deviation.\n Parameters\n ----------\n predicted_s: Tensor\n Predicted signal by DivNoi... |
def recoLoss(predicted_s, x, data_mean, data_std, noiseModel):
'Compute reconstruction loss for an arbitrary noise model. \n Parameters\n ----------\n predicted_s: Tensor\n Predicted signal by DivNoising decoder.\n x: Tensor\n Noisy observation image.\n data_mean: float\n Mean ... |
def loss_fn(predicted_s, x, mu, logvar, gaussian_noise_std, data_mean, data_std, noiseModel):
'Compute DivNoising loss. \n Parameters\n ----------\n predicted_s: Tensor\n Predicted signal by DivNoising decoder.\n x: Tensor\n Noisy observation image.\n mu: Tensor\n Latent space ... |
def create_dataloaders(x_train_tensor, x_val_tensor, batch_size):
train_dataset = dataLoader.MyDataset(x_train_tensor, x_train_tensor)
val_dataset = dataLoader.MyDataset(x_val_tensor, x_val_tensor)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(va... |
def create_model_and_train(basedir, data_mean, data_std, gaussian_noise_std, noise_model, n_depth, max_epochs, logger, checkpoint_callback, train_loader, val_loader, kl_annealing, weights_summary):
for filename in glob.glob((basedir + '/*')):
os.remove(filename)
vae = lightningmodel.VAELightning(data_... |
def train_network(x_train_tensor, x_val_tensor, batch_size, data_mean, data_std, gaussian_noise_std, noise_model, n_depth, max_epochs, model_name, basedir, log_info=False):
(train_loader, val_loader) = create_dataloaders(x_train_tensor, x_val_tensor, batch_size)
collapse_flag = True
if (not os.path.exists... |
def PickleMapName(name):
'\n\tIf you change the name of a function or module, then pickle, you can fix it with this.\n\t'
if (name in renametable):
return renametable[name]
return name
|
def mapped_load_global(self):
module = PickleMapName(self.readline()[:(- 1)])
name = PickleMapName(self.readline()[:(- 1)])
print('Finding ', module, name)
klass = self.find_class(module, name)
self.append(klass)
|
class MyUnpickler(pickle.Unpickler):
def find_class(self, module, name):
return pickle.Unpickler.find_class(self, PickleMapName(module), PickleMapName(name))
|
def UnPickleTM(file):
"\n\tEventually we need to figure out how the mechanics of dispatch tables changed.\n\tSince we only use this as a hack anyways, I'll just comment out what changed\n\tbetween python2.7x and python3x.\n\t"
tmp = None
if (sys.version_info[0] < 3):
f = open(file, 'rb')
u... |
class MorseModel(ForceHolder):
def __init__(self, natom_=3):
'\n\t\tsimple morse model for three atoms for a training example.\n\t\t'
ForceHolder.__init__(self, natom_)
self.lat_pl = None
self.Prepare()
def PorterKarplus(self, x_pl):
x1 = (x_pl[0] - x_pl[1])
x... |
class QuantumElectrostatic(ForceHolder):
def __init__(self, natom_=3):
'\n\t\tThis is a huckle-like model, something like BeH2\n\t\tfour valence charges are exchanged between the atoms\n\t\twhich experience a screened coulomb interaction\n\t\t'
ForceHolder.__init__(self, natom_)
self.Prep... |
class ExtendedHuckel(ForceHolder):
def __init__(self):
'\n\n\t\t'
ForceHolder.__init__(self, natom_)
self.Prepare()
def HuckelBeH2(self, x_pl):
r = tf.reduce_sum((x_pl * x_pl), 1)
r = tf.reshape(r, [(- 1), 1])
D = tf.sqrt((((r - (2 * tf.matmul(x_pl, tf.transpo... |
class TMIPIManger():
def __init__(self, EnergyForceField=None, TCP_IP='localhost', TCP_PORT=31415):
self.EnergyForceField = EnergyForceField
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.hasdata = False
try:
self.s.connect((TCP_IP, TCP_PORT))
... |
class NN_MBE():
def __init__(self, tfm_=None):
self.nn_mbe = dict()
if (tfm_ != None):
for order in tfm_:
print(tfm_[order])
self.nn_mbe[order] = TFMolManage(tfm_[order], None, False)
return
def NN_Energy(self, mol):
mol.Generate_Al... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.