code stringlengths 17 6.64M |
|---|
def apply_Dropout(rng, dropoutRate, inputShape, inputData, task):
' Task:\n # 0: Training\n # 1: Validation\n # 2: Testing '
outputData = inputData
if (dropoutRate > 0.001):
activationRate = (1 - dropoutRate)
srng = T.shared_randomstreams.RandomStreams(rng.randint(999999)... |
def convolveWithKernel(W, filter_shape, inputSample, inputSampleShape):
wReshapedForConv = W.dimshuffle(0, 4, 1, 2, 3)
wReshapedForConvShape = (filter_shape[0], filter_shape[4], filter_shape[1], filter_shape[2], filter_shape[3])
inputSampleReshaped = inputSample.dimshuffle(0, 4, 1, 2, 3)
inputSampleRe... |
def applyBn(numberEpochApplyRolling, inputTrain, inputTest, inputShapeTrain):
numberOfChannels = inputShapeTrain[1]
gBn_values = np.ones(numberOfChannels, dtype='float32')
gBn = theano.shared(value=gBn_values, borrow=True)
bBn_values = np.zeros(numberOfChannels, dtype='float32')
bBn = theano.share... |
def applySoftMax(inputSample, inputSampleShape, numClasses, softmaxTemperature):
inputSampleReshaped = inputSample.dimshuffle(0, 2, 3, 4, 1)
inputSampleFlattened = inputSampleReshaped.flatten(1)
numClassifiedVoxels = ((inputSampleShape[2] * inputSampleShape[3]) * inputSampleShape[4])
firstDimOfinputSa... |
def applyBiasToFeatureMaps(bias, featMaps):
featMaps = (featMaps + bias.dimshuffle('x', 0, 'x', 'x', 'x'))
return featMaps
|
class parserConfigIni(object):
def __init__(_self):
_self.networkName = []
def readConfigIniFile(_self, fileName, task):
def createModel():
print(' --- Creating model (Reading parameters...)')
_self.readModelCreation_params(fileName)
def trainModel():
... |
def printUsage(error_type):
if (error_type == 1):
print(' ** ERROR!!: Few parameters used.')
else:
print(' ** ERROR!!: Asked to start with an already created network but its name is not specified.')
print(' ******** USAGE ******** ')
print(' --- argv 1: Name of the configIni file.')
... |
def networkSegmentation(argv):
if (len(argv) < 2):
printUsage(1)
sys.exit()
configIniName = argv[0]
networkModelName = argv[1]
startTesting(networkModelName, configIniName)
print(' ***************** SEGMENTATION DONE!!! ***************** ')
|
class BatchGenerator():
'\n Iterate over a video datasets, returning filenames of frames to laod.\n preprocessing.py can be used in combination with BatchGenerator to read and preprocess frames.\n\n (num_labels) number of labels in dataset.\n (filename) part of filename before _train.pkl or _test.pkl ... |
def i3d_model(input_images, is_training, num_labels, dropout, flip_classifier_gradient=False, flip_weight=1.0, aux_classifier=False, feat_level='features'):
rgb_model = i3d.InceptionI3d((num_labels + num_labels), spatial_squeeze=True, final_endpoint='Logits', aux_classifier=aux_classifier)
(logits, endpoints)... |
def build_i3d(reuse_variables, input_images, is_training, num_labels, flow, temporal_window, dropout, flip_classifier_gradient, flip_weight=1.0, aux_classifier=False, feat_level='features'):
with tf.variable_scope(tf.get_variable_scope(), reuse=reuse_variables):
return i3d_model(input_images, is_training,... |
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
|
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
|
def domain_classifier(feat):
shape = feat.get_shape().as_list()
dim = np.prod(shape[1:])
feat = tf.reshape(feat, [(- 1), dim])
with tf.variable_scope('Domain_Classifier'):
d_h_fc0 = tf.layers.dense(feat, 100, kernel_initializer=tf.initializers.truncated_normal(stddev=0.1), name='first')
... |
def predict_synch(feat):
shape = feat.get_shape().as_list()
dim = np.prod(shape[1:])
feat = tf.reshape(feat, [(- 1), dim])
d_h_fc0 = tf.layers.dense(feat, 100, kernel_initializer=tf.initializers.truncated_normal(stddev=0.1), name='first')
d_h_fc0 = tf.nn.relu(d_h_fc0)
d_logits = tf.layers.dens... |
class FlipGradientBuilder(object):
def __init__(self):
self.num_calls = 0
def __call__(self, x, l=1.0):
grad_name = ('FlipGradient%d' % self.num_calls)
@ops.RegisterGradient(grad_name)
def _flip_gradients(op, grad):
return [(tf.negative(grad) * l)]
g = tf... |
class Unit3D(snt.AbstractModule):
'Basic unit containing Conv3D + BatchNorm + non-linearity.'
def __init__(self, output_channels, kernel_shape=(1, 1, 1), stride=(1, 1, 1), activation_fn=tf.nn.relu, use_batch_norm=True, use_bias=False, name='unit_3d'):
'Initializes Unit3D module.'
super(Unit3D... |
class InceptionI3d(snt.AbstractModule):
'Inception-v1 I3D architecture.\n\n The model is introduced in:\n\n Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset\n Joao Carreira, Andrew Zisserman\n https://arxiv.org/pdf/1705.07750v1.pdf.\n\n See also the Inception architecture, introduced... |
def _mix_rbf_kernel(X, Y, gammas, wts=None):
if (wts is None):
wts = ([1] * len(gammas))
XX = tf.matmul(X, X, transpose_b=True)
XY = tf.matmul(X, Y, transpose_b=True)
YY = tf.matmul(Y, Y, transpose_b=True)
X_sqnorms = tf.diag_part(XX)
Y_sqnorms = tf.diag_part(YY)
r = (lambda x: tf.... |
def rbf_mmd2(X, Y, gammas=1, biased=True):
return mix_rbf_mmd2(X, Y, gammas=[gammas], biased=biased)
|
def mix_rbf_mmd2(X, Y, gammas=(1,), wts=None, biased=True):
(K_XX, K_XY, K_YY, d) = _mix_rbf_kernel(X, Y, gammas, wts)
return _mmd2(K_XX, K_XY, K_YY, const_diagonal=d, biased=biased)
|
def _mmd2(K_XX, K_XY, K_YY, const_diagonal=False, biased=False):
m = tf.cast(tf.shape(K_XX)[0], tf.float32)
n = tf.cast(tf.shape(K_YY)[0], tf.float32)
if biased:
mmd2 = (((tf.reduce_sum(K_XX) / (m * m)) + (tf.reduce_sum(K_YY) / (n * n))) - ((2 * tf.reduce_sum(K_XY)) / (m * n)))
else:
i... |
def main():
seen = tf.placeholder(tf.float32, shape=[None, 1024])
unseen = tf.placeholder(tf.float32, shape=[None, 1024])
(mmd, n) = rbf_mmd2(seen, unseen)
(mmd, n) = mix_rbf_mmd2(seen, unseen, gammas=[10.0, 1.0, 0.1, 0.01, 0.001])
source_numpy = np.load(sys.argv[1])
target_numpy = np.load(sys... |
def _get_variables_to_restore_load(to_ignore, flow):
to_ignore.append('domain_accumulators')
to_ignore.append('accum_accumulators')
to_ignore.append('accumulators')
scope_to_ignore = to_ignore
if flow:
scope_to_ignore.append('RGB')
scope_to_ignore.append('Joint')
else:
... |
def read_joint(mode=''):
if (mode == 'restore'):
to_ignore = ['Adam', 'adam', 'Momentum', 'beta1_power', 'beta2_power', 'global_step', 'Domain_Classifier']
elif (mode == 'continue'):
to_ignore = []
else:
raise Exception('Unknown mode for read_joint')
to_ignore.append('domain_ac... |
def read_i3d_checkpoint(mode='', flow=False, aux_logits=False):
if (mode == 'pretrain'):
to_ignore = ['inception_i3d/Logits', 'Adam', 'adam', 'Momentum', 'beta1_power', 'beta2_power', 'global_step', 'Domain_Classifier', 'arrow_test']
elif (mode == 'restore'):
to_ignore = ['Adam', 'adam', 'Mome... |
def restore_base(sess, saver, checkpoint_path, model_to_restore, restore_mode='model'):
if (restore_mode == 'continue'):
ckpt = tf.train.get_checkpoint_state(checkpoint_path)
if (ckpt and ckpt.model_checkpoint_path):
saver['continue'].restore(sess, ckpt.model_checkpoint_path)
e... |
def restore_joint(sess, saver, checkpoint_path, model_to_restore, restore_mode='model'):
if (restore_mode == 'continue'):
ckpt = tf.train.get_checkpoint_state(checkpoint_path)
if (ckpt and ckpt.model_checkpoint_path):
saver['continue'].restore(sess, ckpt.model_checkpoint_path)
... |
def init_savers_base(flow=False):
pretrain_loader = read_i3d_checkpoint(mode='pretrain', flow=flow)
model_loader = read_i3d_checkpoint(mode='restore', flow=flow)
savesave = read_i3d_checkpoint(mode='continue', flow=flow)
return (pretrain_loader, model_loader, savesave)
|
class TrainTestScript():
' Creates a framework to train/test an MM-SADA model\n (FLAGS) TensorFlow flags\n (results_dir) Directory of tensorboard files and other testing logs\n (train_dir) Director of saved model\n\n Methods:\n train - train MM-SADA\n ... |
def parse_args(FLAGS):
error = False
if (FLAGS.train is None):
print('Specify whether to train (True) or test (False) --train')
error = True
if (FLAGS.results_path is None):
print('Specify path to save logs and models --results_path')
error = True
if (FLAGS.datasets is ... |
def input_parser():
flags = tf.app.flags
flags.DEFINE_boolean('train', None, 'Weither to train or evaluate (False)')
flags.DEFINE_string('results_path', None, 'Where to store the log files and saved models')
flags.DEFINE_float('lr', 0.001, 'Initial Learning Rate')
flags.DEFINE_float('batch_norm_up... |
def main():
(flags, train_dir, results_dir) = input_parser()
if parse_args(flags):
return
train_test = TrainTestScript(flags, results_dir, train_dir)
if flags.train:
train_test.train()
else:
train_test.test()
|
def conv_block(in_dim, out_dim, act_fn, kernel_size=3, stride=1, padding=1, dilation=1):
model = nn.Sequential(nn.Conv2d(in_dim, out_dim, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation), nn.BatchNorm2d(out_dim), act_fn)
return model
|
def conv_block_Asym_Inception(in_dim, out_dim, act_fn, kernel_size=3, stride=1, padding=1, dilation=1):
model = nn.Sequential(nn.Conv2d(in_dim, out_dim, kernel_size=[kernel_size, 1], padding=tuple([padding, 0]), dilation=(dilation, 1)), nn.BatchNorm2d(out_dim), nn.ReLU(), nn.Conv2d(out_dim, out_dim, kernel_size=[... |
def conv_decod_block(in_dim, out_dim, act_fn):
model = nn.Sequential(nn.ConvTranspose2d(in_dim, out_dim, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(out_dim), act_fn)
return model
|
def maxpool():
pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
return pool
|
def bottleNeck(nin, nmid):
return nn.Sequential(nn.BatchNorm2d(nin), nn.ReLU(), nn.Conv2d(nin, nmid, kernel_size=1, stride=1, padding=0), nn.BatchNorm2d(nmid), nn.ReLU(), nn.Conv2d(nmid, nmid, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(nmid), nn.ReLU(), nn.Conv2d(nmid, (nmid * 4), kernel_size=1, stride=1... |
def convBatch(nin, nout, kernel_size=3, stride=1, padding=1, bias=False, layer=nn.Conv2d, dilation=1):
return nn.Sequential(layer(nin, nout, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias, dilation=dilation), nn.BatchNorm2d(nout), nn.PReLU())
|
def downSampleConv(nin, nout, kernel_size=3, stride=2, padding=1, bias=False):
return nn.Sequential(convBatch(nin, nout, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias))
|
def upSampleConv(nin, nout, kernel_size=3, upscale=2, padding=1, bias=False):
return nn.Sequential(nn.Upsample(scale_factor=upscale), convBatch(nin, nout, kernel_size=kernel_size, stride=1, padding=padding, bias=bias), convBatch(nout, nout, kernel_size=3, stride=1, padding=1, bias=bias))
|
def conv(nin, nout, kernel_size=3, stride=1, padding=1, bias=False, layer=nn.Conv2d, BN=False, ws=False, activ=nn.LeakyReLU(0.2), gainWS=2):
convlayer = layer(nin, nout, kernel_size, stride=stride, padding=padding, bias=bias)
layers = []
if ws:
layers.append(WScaleLayer(convlayer, gain=gainWS))
... |
class ResidualConv(nn.Module):
def __init__(self, nin, nout, bias=False, BN=False, ws=False, activ=nn.LeakyReLU(0.2)):
super(ResidualConv, self).__init__()
convs = [conv(nin, nout, bias=bias, BN=BN, ws=ws, activ=activ), conv(nout, nout, bias=bias, BN=BN, ws=ws, activ=None)]
self.convs = n... |
class residualConv(nn.Module):
def __init__(self, nin, nout):
super(residualConv, self).__init__()
self.convs = nn.Sequential(convBatch(nin, nout), nn.Conv2d(nout, nout, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(nout))
self.res = nn.Sequential()
if (nin != nout):
... |
def weights_init(m):
if ((type(m) == nn.Conv2d) or (type(m) == nn.ConvTranspose2d)):
nn.init.xavier_normal(m.weight.data)
elif (type(m) == nn.BatchNorm2d):
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
|
def runTraining():
print(('-' * 40))
print('~~~~~~~~ Starting the training... ~~~~~~')
print(('-' * 40))
batch_size = 4
batch_size_val = 1
batch_size_val_save = 1
lr = 0.0001
epoch = 200
num_classes = 2
initial_kernels = 32
modelName = 'IVD_Net'
img_names_ALL = []
... |
def make_dataset(root, mode):
assert (mode in ['train', 'val', 'test'])
items = []
if (mode == 'train'):
train_fat_path = os.path.join(root, 'train', 'Fat')
train_inn_path = os.path.join(root, 'train', 'Inn')
train_opp_path = os.path.join(root, 'train', 'Opp')
train_wat_pat... |
class MedicalImageDataset(Dataset):
'Face Landmarks dataset.'
def __init__(self, mode, root_dir, transform=None, mask_transform=None, augment=False, equalize=False):
'\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with ... |
class Adam(Optimizer):
'Implements Adam algorithm.\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)... |
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='=', empty=' ', tip='>', begin='[', end=']', done='[DONE]', clear=True):
'\n Print iterations progress.\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration... |
def verbose(verboseLevel, requiredLevel, printFunc=print, *printArgs, **kwPrintArgs):
'\n Calls `printFunc` passing it `printArgs` and `kwPrintArgs`\n only if `verboseLevel` meets the `requiredLevel` of verbosity.\n\n Following forms are supported:\n\n > verbose(1, 0, "message")\n\n >> ... |
def print_flush(txt=''):
print(txt)
sys.stdout.flush()
|
def hide_cursor():
if (os.name == 'nt'):
ci = _CursorInfo()
handle = ctypes.windll.kernel32.GetStdHandle((- 11))
ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
ci.visible = False
ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
... |
def show_cursor():
if (os.name == 'nt'):
ci = _CursorInfo()
handle = ctypes.windll.kernel32.GetStdHandle((- 11))
ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
ci.visible = True
ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
... |
def to_var(x):
if torch.cuda.is_available():
x = x.cuda()
return Variable(x)
|
class computeDiceOneHotBinary(nn.Module):
def __init__(self):
super(computeDiceOneHotBinary, self).__init__()
def dice(self, input, target):
inter = (input * target).float().sum()
sum = (input.sum() + target.sum())
if (sum == 0).all():
return (((2 * inter) + 1e-08... |
def DicesToDice(Dices):
sums = Dices.sum(dim=0)
return (((2 * sums[0]) + 1e-08) / (sums[1] + 1e-08))
|
def getSingleImageBin(pred):
n_channels = 2
Val = to_var(torch.zeros(2))
Val[1] = 1.0
x = predToSegmentation(pred)
out = (x * Val.view(1, n_channels, 1, 1))
return out.sum(dim=1, keepdim=True)
|
def predToSegmentation(pred):
Max = pred.max(dim=1, keepdim=True)[0]
x = (pred / Max)
return (x == 1).float()
|
def getOneHotSegmentation(batch):
backgroundVal = 0
label1 = 1.0
oneHotLabels = torch.cat(((batch == backgroundVal), (batch == label1)), dim=1)
return oneHotLabels.float()
|
def getTargetSegmentation(batch):
spineLabel = 1.0
return (batch / spineLabel).round().long().squeeze()
|
def saveImages(net, img_batch, batch_size, epoch, modelName):
path = ((('../Results/Images_PNG/' + modelName) + '_') + str(epoch))
if (not os.path.exists(path)):
os.makedirs(path)
total = len(img_batch)
net.eval()
softMax = nn.Softmax()
for (i, data) in enumerate(img_batch):
pr... |
def inference(net, img_batch, batch_size, epoch):
total = len(img_batch)
Dice1 = torch.zeros(total, 2)
net.eval()
dice = computeDiceOneHotBinary().cuda()
softMax = nn.Softmax().cuda()
img_names_ALL = []
for (i, data) in enumerate(img_batch):
printProgressBar(i, total, prefix='[Infe... |
def append(x, start, freq, precision):
'Encodes a symbol with range [start, start + freq). All frequencies are\n assumed to sum to "1 << precision", and the resulting bits get written to\n x.'
if (x[0] >= (((rans_l >> precision) << 32) * freq)):
x = ((x[0] >> 32), ((x[0] & tail_bits), x[1]))
... |
def pop(x_, precision):
'Advances in the bit stream by "popping" a single symbol with range start\n "start" and frequency "freq".'
cf = (x_[0] & ((1 << precision) - 1))
def pop(start, freq):
x = ((((freq * (x_[0] >> precision)) + cf) - start), x_[1])
return ((((x[0] << 32) | x[1][0]), ... |
def append_symbol(statfun, precision):
def append_(x, symbol):
(start, freq) = statfun(symbol)
return append(x, start, freq, precision)
return append_
|
def pop_symbol(statfun, precision):
def pop_(x):
(cf, pop_fun) = pop(x, precision)
(symbol, (start, freq)) = statfun(cf)
return (pop_fun(start, freq), symbol)
return pop_
|
def flatten(x):
'Flatten a rans state x into a 1d numpy array.'
(out, x) = ([(x[0] >> 32), x[0]], x[1])
while x:
(x_head, x) = x
out.append(x_head)
return np.asarray(out, dtype=np.uint32)
|
def unflatten(arr):
'Unflatten a 1d numpy array into a rans state.'
return (((int(arr[0]) << 32) | int(arr[1])), reduce((lambda tl, hd: (int(hd), tl)), reversed(arr[2:]), ()))
|
def run(args, kwargs):
args.snap_dir = snap_dir = 'snapshots/discrete_logisticcifar10_flows_2_levels_3__2019-09-27_13_08_49/'
(train_loader, val_loader, test_loader, args) = load_dataset(args, **kwargs)
final_model = torch.load((snap_dir + 'a.model'))
if hasattr(final_model, 'module'):
final_m... |
def run(args, kwargs):
print('\nMODEL SETTINGS: \n', args, '\n')
print('Random Seed: ', args.manual_seed)
if (('imagenet' in args.dataset) and (args.evaluate_interval_epochs > 5)):
args.evaluate_interval_epochs = 5
args.model_signature = str(datetime.datetime.now())[0:19].replace(' ', '_')
... |
class RoundStraightThrough(torch.autograd.Function):
def __init__(self):
super().__init__()
@staticmethod
def forward(ctx, input):
rounded = torch.round(input, out=None)
return rounded
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.clone()... |
def _stacked_sigmoid(x, temperature, n_approx=3):
x_ = (x - 0.5)
rounded = torch.round(x_)
x_remainder = (x_ - rounded)
size = x_.size()
x_remainder = x_remainder.view((size + (1,)))
translation = (torch.arange(n_approx) - (n_approx // 2))
translation = translation.to(device=x.device, dtyp... |
class SmoothRound(Base):
def __init__(self):
self._temperature = None
self._n_approx = None
super().__init__()
self.hard_round = None
@property
def temperature(self):
return self._temperature
@temperature.setter
def temperature(self, value):
self.... |
class StochasticRound(Base):
def __init__(self):
super().__init__()
self.hard_round = None
def forward(self, x):
u = torch.rand_like(x)
h = ((x + u) - 0.5)
if self.hard_round:
h = _round_straightthrough(h)
return h
|
class BackRound(Base):
def __init__(self, args, inverse_bin_width):
'\n BackRound is an approximation to Round that allows for Backpropagation.\n\n Approximate the round function using a sum of translated sigmoids.\n The temperature determines how well the round function is approxima... |
class Conv2dReLU(Base):
def __init__(self, n_inputs, n_outputs, kernel_size=3, stride=1, padding=0, bias=True):
super().__init__()
self.nn = nn.Conv2d(n_inputs, n_outputs, kernel_size, padding=padding)
def forward(self, x):
h = self.nn(x)
y = F.relu(h)
return y
|
class ResidualBlock(Base):
def __init__(self, n_channels, kernel, Conv2dAct):
super().__init__()
self.nn = torch.nn.Sequential(Conv2dAct(n_channels, n_channels, kernel, padding=1), torch.nn.Conv2d(n_channels, n_channels, kernel, padding=1))
def forward(self, x):
h = self.nn(x)
... |
class DenseLayer(Base):
def __init__(self, args, n_inputs, growth, Conv2dAct):
super().__init__()
conv1x1 = Conv2dAct(n_inputs, n_inputs, kernel_size=1, stride=1, padding=0, bias=True)
self.nn = torch.nn.Sequential(conv1x1, Conv2dAct(n_inputs, growth, kernel_size=3, stride=1, padding=1, b... |
class DenseBlock(Base):
def __init__(self, args, n_inputs, n_outputs, kernel, Conv2dAct):
super().__init__()
depth = args.densenet_depth
future_growth = (n_outputs - n_inputs)
layers = []
for d in range(depth):
growth = (future_growth // (depth - d))
... |
class Identity(Base):
def __init__(self):
super.__init__()
def forward(self, x):
return x
|
class NN(Base):
def __init__(self, args, c_in, c_out, height, width, nn_type, kernel=3):
super().__init__()
Conv2dAct = Conv2dReLU
n_channels = args.n_channels
if (nn_type == 'shallow'):
if (args.network1x1 == 'standard'):
conv1x1 = Conv2dAct(n_channels... |
class Base(torch.nn.Module):
'\n The base class for modules. That contains a disable round mode\n '
def __init__(self):
super().__init__()
def _set_child_attribute(self, attr, value):
'Sets the module in rounding mode.\n\n This has any effect only on certain modules if varia... |
def compute_log_ps(pxs, xs, args):
inverse_bin_width = (2.0 ** args.n_bits)
log_pxs = []
for (px, x) in zip(pxs, xs):
if (args.variable_type == 'discrete'):
if (args.distribution_type == 'logistic'):
log_px = log_discretized_logistic(x, *px, inverse_bin_width=inverse_bi... |
def compute_log_pz(pz, z, args):
inverse_bin_width = (2.0 ** args.n_bits)
if (args.variable_type == 'discrete'):
if (args.distribution_type == 'logistic'):
if (args.n_mixtures == 1):
log_pz = log_discretized_logistic(z, pz[0], pz[1], inverse_bin_width=inverse_bin_width)
... |
def compute_loss_function(pz, z, pys, ys, ldj, args):
'\n Computes the cross entropy loss function while summing over batch dimension, not averaged!\n :param x_logit: shape: (batch_size, num_classes * num_channels, pixel_width, pixel_height), real valued logits\n :param x: shape (batchsize, num_channels,... |
def convert_bpd(log_p, input_size):
return ((- log_p) / (np.prod(input_size) * np.log(2.0)))
|
def compute_loss_array(pz, z, pys, ys, ldj, args):
'\n Computes the cross entropy loss function while summing over batch dimension, not averaged!\n :param x_logit: shape: (batch_size, num_classes * num_channels, pixel_width, pixel_height), real valued logits\n :param x: shape (batchsize, num_channels, pi... |
def calculate_loss(pz, z, pys, ys, ldj, loss_aux, args):
return compute_loss_function(pz, z, pys, ys, ldj, loss_aux, args)
|
def train(epoch, train_loader, model, opt, args):
model.train()
train_loss = np.zeros(len(train_loader))
train_bpd = np.zeros(len(train_loader))
num_data = 0
for (batch_idx, (data, _)) in enumerate(train_loader):
data = data.view((- 1), *args.input_size)
data = data.to(args.device)... |
def evaluate(train_loader, val_loader, model, model_sample, args, testing=False, file=None, epoch=0):
model.eval()
loss_type = 'bpd'
def analyse(data_loader, plot=False):
bpds = []
batch_idx = 0
with torch.no_grad():
for (data, _) in data_loader:
batch_... |
def log_min_exp(a, b, epsilon=1e-08):
'\n Computes the log of exp(a) - exp(b) in a (more) numerically stable fashion.\n Using:\n log(exp(a) - exp(b))\n c + log(exp(a-c) - exp(b-c))\n a + log(1 - exp(b-a))\n And note that we assume b < a always.\n '
y = (a + torch.log(((1 - torch.exp((b... |
def log_normal(x, mean, logvar):
logp = ((- 0.5) * logvar)
logp += ((- 0.5) * np.log((2 * PI)))
logp += ((((- 0.5) * (x - mean)) * (x - mean)) / torch.exp(logvar))
return logp
|
def log_mixture_normal(x, mean, logvar, pi):
x = x.view(x.size(0), x.size(1), x.size(2), x.size(3), 1)
logp_mixtures = log_normal(x, mean, logvar)
logp = torch.log((torch.sum((pi * torch.exp(logp_mixtures)), dim=(- 1)) + 1e-08))
return logp
|
def sample_normal(mean, logvar):
y = torch.randn_like(mean)
x = ((torch.exp((0.5 * logvar)) * y) + mean)
return x
|
def sample_mixture_normal(mean, logvar, pi):
(b, c, h, w, n_mixtures) = tuple(map(int, pi.size()))
pi = pi.view((((b * c) * h) * w), n_mixtures)
sampled_pi = torch.multinomial(pi, num_samples=1).view((- 1))
mean = mean.view((((b * c) * h) * w), n_mixtures)
mean = mean[(torch.arange((((b * c) * h) ... |
def log_logistic(x, mean, logscale):
'\n pdf = sigma([x - mean] / scale) * [1 - sigma(...)] * 1/scale\n '
scale = torch.exp(logscale)
u = ((x - mean) / scale)
logp = ((F.logsigmoid(u) + F.logsigmoid((- u))) - logscale)
return logp
|
def sample_logistic(mean, logscale):
y = torch.rand_like(mean)
x = ((torch.exp(logscale) * torch.log((y / (1 - y)))) + mean)
return x
|
def log_discretized_logistic(x, mean, logscale, inverse_bin_width):
scale = torch.exp(logscale)
logp = log_min_exp(F.logsigmoid((((x + (0.5 / inverse_bin_width)) - mean) / scale)), F.logsigmoid((((x - (0.5 / inverse_bin_width)) - mean) / scale)))
return logp
|
def discretized_logistic_cdf(x, mean, logscale, inverse_bin_width):
scale = torch.exp(logscale)
cdf = torch.sigmoid((((x + (0.5 / inverse_bin_width)) - mean) / scale))
return cdf
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.