code stringlengths 17 6.64M |
|---|
class ClevrBatcher():
def __init__(self, batchSize, split, maxSamples=None, rand=True):
dat = h5py.File('data/preprocessed/clevr.h5', 'r')
self.questions = dat[(split + 'Questions')]
self.answers = dat[(split + 'Answers')]
self.programs = dat[(split + 'Programs')]
self.img... |
def buildVocab(fName):
dat = open(fName).read()
dat = dat.split()
vocab = dict(zip(dat, (1 + np.arange(len(dat)))))
invVocab = {v: k for (k, v) in vocab.items()}
return (vocab, invVocab)
|
def applyVocab(line, vocab):
ret = []
for e in line:
ret += [vocab[e]]
return np.asarray(ret)
|
def applyInvVocab(x, vocab):
x = applyVocab(x, utils.invertDict(vocab))
return ''.join(x)
|
def invertDict(x):
return {v: k for (k, v) in x.items()}
|
def loadDict(fName):
with open(fName) as f:
s = eval(f.read())
return s
|
def norm(x, n=2):
return ((np.sum((np.abs(x) ** n)) ** (1.0 / n)) / np.prod(x.shape))
|
class Perm():
def __init__(self, n):
self.inds = np.random.permutation(np.arange(n))
self.m = n
self.pos = 0
def next(self, n):
assert ((self.pos + n) < self.m)
ret = self.inds[self.pos:(self.pos + n)]
self.pos += n
return ret
|
class CMA():
def __init__(self):
self.t = 0.0
self.cma = 0.0
def update(self, x):
self.cma = ((x + (self.t * self.cma)) / (self.t + 1))
self.t += 1.0
|
class EDA():
def __init__(self, k=0.99):
self.k = k
self.eda = 0.0
def update(self, x):
self.eda = (((1 - self.k) * x) + (self.k * self.eda))
|
def modelSize(net):
params = 0
for e in net.parameters():
params += np.prod(e.size())
params = int((params / 1000))
print('Network has ', params, 'K params')
|
def Conv2d(fIn, fOut, k):
pad = int(((k - 1) / 2))
return nn.Conv2d(fIn, fOut, k, padding=pad)
|
def list(module, *args, n=1):
return nn.ModuleList([module(*args) for i in range(n)])
|
def var(xNp, volatile=False, cuda=False):
x = Variable(t.from_numpy(xNp), volatile=volatile)
if cuda:
x = x.cuda()
return x
|
def initWeights(net, scheme='orthogonal'):
print('Initializing weights. Warning: may overwrite sensitive bias parameters (e.g. batchnorm)')
for e in net.parameters():
if (scheme == 'orthogonal'):
if (len(e.size()) >= 2):
init.orthogonal(e)
elif (scheme == 'normal'):... |
class SaveManager():
def __init__(self, root):
(self.tl, self.ta, self.vl, self.va) = ([], [], [], [])
self.root = root
self.stateDict = None
self.lock = False
def update(self, net, tl, ta, vl, va):
nan = np.isnan(sum([t.sum(e) for e in net.state_dict().values()]))
... |
def _sequence_mask(sequence_length, max_len=None):
if (max_len is None):
max_len = sequence_length.data.max()
batch_size = sequence_length.size(0)
seq_range = t.range(0, (max_len - 1)).long()
seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
seq_range_expand = Variable(... |
def maskedCE(logits, target, length):
'\n Args:\n logits: A Variable containing a FloatTensor of size\n (batch, max_len, num_classes) which contains the\n unnormalized probability for each class.\n target: A Variable containing a LongTensor of size\n (batch, max_len) wh... |
def runMinibatch(net, batcher, cuda=True, volatile=False, trainable=False):
(x, y, mask) = batcher.next()
x = [var(e, volatile=volatile, cuda=cuda) for e in x]
y = [var(e, volatile=volatile, cuda=cuda) for e in y]
if (mask is not None):
mask = var(mask, volatile=volatile, cuda=cuda)
if (le... |
def runData(net, opt, batcher, criterion=maskedCE, trainable=False, verbose=False, cuda=True, gradClip=10.0, minContext=0, numPrints=10):
iters = batcher.batches
meanAcc = CMA()
meanLoss = CMA()
for i in range(iters):
try:
if (verbose and ((i % int((iters / numPrints))) == 0)):
... |
def stats(criterion, a, y, mask):
if (mask is not None):
(_, preds) = t.max(a.data, 2)
(batch, sLen, c) = a.size()
loss = criterion(a.view((- 1), c), y.view((- 1)))
m = t.sum(mask)
mask = _sequence_mask(mask, sLen)
acc = (t.sum((mask.data.float() * (y.data == preds)... |
class ExecutionEngine(nn.Module):
def __init__(self, numUnary, numBinary, numClasses):
super(ExecutionEngine, self).__init__()
self.arities = (((2 * [0]) + ([1] * numUnary)) + ([2] * numBinary))
unaries = [UnaryModule() for i in range(numUnary)]
binaries = [BinaryModule() for i in... |
class EngineClassifier(nn.Module):
def __init__(self, numClasses):
super(EngineClassifier, self).__init__()
self.conv1 = utils.Conv2d(128, 512, 1)
self.fc1 = nn.Linear(((512 * 7) * 7), 1024)
self.pool = nn.MaxPool2d(2)
self.fc2 = nn.Linear(1024, numClasses)
def forwar... |
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = utils.Conv2d(1024, 128, 3)
self.conv2 = utils.Conv2d(128, 128, 3)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
return x
|
class UnaryModule(nn.Module):
def __init__(self):
super(UnaryModule, self).__init__()
self.conv1 = utils.Conv2d(128, 128, 3)
self.conv2 = utils.Conv2d(128, 128, 3)
def forward(self, x):
inp = x
x = F.relu(self.conv1(x))
x = self.conv2(x)
x += inp
... |
class BinaryModule(nn.Module):
def __init__(self):
super(BinaryModule, self).__init__()
self.conv1 = utils.Conv2d(256, 128, 1)
self.conv2 = utils.Conv2d(128, 128, 3)
self.conv3 = utils.Conv2d(128, 128, 3)
def forward(self, x1, x2):
x = t.cat((x1, x2), 1)
x = F... |
class Upscale(nn.Module):
def __init__(self):
super(Upscale, self).__init__()
self.fc = nn.Linear(1, ((128 * 14) * 14))
def forward(self, x):
x = x.view(1, 1)
x = self.fc(x)
x = x.view((- 1), 128, 14, 14)
return x
|
class Node():
def __init__(self, prev):
self.prev = prev
self.inpData = []
def build(self, cellInd, mul, arity):
self.next = ([None] * arity)
self.arity = arity
self.cellInd = cellInd
self.mul = mul
|
class Program():
def __init__(self, prog, mul, imgFeats, arities):
self.prog = prog
self.mul = mul
self.imgFeats = imgFeats
self.arities = arities
self.root = Node(None)
def build(self, ind=0):
self.buildInternal(self.root)
def buildInternal(self, cur=Non... |
class HighArcESort():
def __init__(self):
self.out = {}
def __call__(self, root):
assert (not self.out)
self.highArcESortInternal(root, 0)
return self.out
def highArcESortInternal(self, cur, rank):
for nxt in cur.next:
ret = self.highArcESortInternal(... |
class FasterExecutioner():
def __init__(self, progs, cells):
self.cells = cells
self.progs = progs
self.roots = [p.root for p in progs]
self.sortProgs()
self.maxKey = max(list(self.progs.keys()))
def sortProgs(self):
progs = {}
for prog in self.progs:
... |
class FastExecutioner():
def __init__(self, progs, cells):
self.cells = cells
self.progs = progs
self.sortProgs()
def sortProgs(self):
for i in range(len(self.progs)):
self.progs[i] = self.progs[i].topologicalSort()
def execute(self):
maxLen = max([le... |
class Executioner():
def __init__(self, prog, cells):
self.prog = prog
self.cells = cells
def execute(self):
return self.executeInternal(self.prog.root)
def executeInternal(self, cur):
if (cur.arity == 0):
return cur.inpData[0]
elif (cur.arity == 1):
... |
class ProgramGenerator(nn.Module):
def __init__(self, embedDim, hGen, qLen, qVocab, pVocab):
super(ProgramGenerator, self).__init__()
self.embed = nn.Embedding(qVocab, embedDim)
self.encoder = t.nn.LSTM(embedDim, hGen, 2, batch_first=True)
self.decoder = t.nn.LSTM(hGen, hGen, 2, b... |
def ResNetFeatureExtractor():
resnet = torchvision.models.resnet101(pretrained=True)
return nn.Sequential(resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1, resnet.layer2, resnet.layer3).eval()
|
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, bias=False)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 ... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, p... |
class BottleneckFinal(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BottleneckFinal, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d... |
class ResNet(nn.Module):
def __init__(self, num_classes=1000):
block = Bottleneck
layers = [3, 4, 5]
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
... |
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 = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet... |
class Node():
def __init__(self, cell):
self.nxt = cell['inputs'][::(- 1)]
self.func = cell['function']
if (len(cell['value_inputs']) > 0):
self.func += ('_' + cell['value_inputs'][0])
|
class BTree():
def __init__(self, cells):
self.root = Node(cells[(- 1)])
self.addNodes(cells[:(- 1)], self.root)
def addNodes(self, cells, cur):
for i in range(len(cur.nxt)):
e = cur.nxt[i]
node = Node(cells[e])
cur.nxt[i] = node
self.a... |
def loadDat():
with open('../data/clevr/questions/CLEVR_val_questions.json') as dataF:
questions = json.load(dataF)['questions']
return questions
|
def getFuncs(dat):
vocab = []
for p in dat:
p = p['program']
for e in p:
func = e['function']
append = e['value_inputs']
if (len(append) > 0):
func += ('_' + append[0])
func = ((str(len(e['inputs'])) + '_') + func)
voc... |
def getAllWords(fName):
dat = open(fName).read()
dat = json.loads(dat)
dat = dat['questions']
wordsX = []
wordsY = []
for e in dat:
wordsX += e['question'].lower()[:(- 1)].split()
if ('answer' in e.keys()):
wordsY += e['answer'].lower().split()
return ((wordsX +... |
def name(split):
return (('../data/clevr/questions/CLEVR_' + split) + '_questions.json')
|
def plotResults():
batch = [1, 32, 64, 320, 640, 850]
fVanilla = [0.0031771, 0.0031694, 0.0026328, 0.00238375, 0.0023333]
fOurs = [0.003963, 0.00248858, 0.001686116, 0.000710902, 0.0005151, 0.00042235]
cVanilla = [0.002315934, 0.00287098, 0.00249189, 0.002322, 0.002199]
cOurs = [0.002244463, 0.001... |
class _NNMFBase(object):
def __init__(self, num_users, num_items, D=10, Dprime=60, hidden_units_per_layer=50, latent_normal_init_params={'mean': 0.0, 'stddev': 0.1}, model_filename='model/nnmf.ckpt'):
self.num_users = num_users
self.num_items = num_items
self.D = D
self.Dprime = D... |
class NNMF(_NNMFBase):
def __init__(self, *args, **kwargs):
if ('lam' in kwargs):
self.lam = float(kwargs['lam'])
del kwargs['lam']
else:
self.lam = 0.01
super(NNMF, self).__init__(*args, **kwargs)
def _init_vars(self):
self.U = tf.Variable... |
class SVINNMF(_NNMFBase):
num_latent_samples = 1
num_data_samples = 3
def __init__(self, *args, **kwargs):
if ('r_var' in kwargs):
self.r_var = float(kwargs['r_var'])
del kwargs['r_sigma']
else:
self.r_var = 1.0
if ('U_prior_var' in kwargs):
... |
def KL(mean, log_var, prior_var):
'Computes KL divergence for a group of univariate normals (ie. every dimension of a latent).'
return tf.reduce_sum((tf.log((math.sqrt(prior_var) / tf.sqrt(tf.exp(log_var)))) + ((tf.exp(log_var) + tf.square(mean)) / (2.0 * prior_var))), reduction_indices=[0, 1])
|
def _weight_init_range(n_in, n_out):
'Calculates range for picking initial weight values from a uniform distribution.'
range = ((4.0 * math.sqrt(6.0)) / math.sqrt((n_in + n_out)))
return {'minval': (- range), 'maxval': range}
|
def build_mlp(f_input_layer, hidden_units_per_layer):
'Builds a feed-forward NN (MLP) with 3 hidden layers.'
num_f_inputs = f_input_layer.get_shape().as_list()[1]
mlp_weights = {'h1': tf.Variable(tf.random_uniform([num_f_inputs, hidden_units_per_layer], **_weight_init_range(num_f_inputs, hidden_units_per_... |
def get_kl_weight(curr_iter, on_epoch=100):
"Outputs sigmoid scheduled KL weight term (to be fully on at 'on_epoch')"
return (1.0 / (1 + math.exp(((- (25.0 / on_epoch)) * (curr_iter - (on_epoch / 2.0))))))
|
def chunk_df(df, size):
'Splits a Pandas dataframe into chunks of size `size`.\n\n See here: https://stackoverflow.com/a/25701576/1424734\n '
return (df[pos:(pos + size)] for pos in xrange(0, len(df), size))
|
def load_data(train_filename, valid_filename, test_filename, delimiter='\t', col_names=['user_id', 'item_id', 'rating']):
'Helper function to load in/preprocess dataframes'
train_data = pd.read_csv(train_filename, delimiter=delimiter, header=None, names=col_names)
train_data['user_id'] = (train_data['user... |
def train(model, sess, saver, train_data, valid_data, batch_size, max_epochs, use_early_stop, early_stop_max_epoch):
batch = (train_data.sample(batch_size) if batch_size else train_data)
train_error = model.eval_loss(batch)
train_rmse = model.eval_rmse(batch)
valid_rmse = model.eval_rmse(valid_data)
... |
def test(model, sess, saver, test_data, train_data=None, log=True):
if (train_data is not None):
train_rmse = model.eval_rmse(train_data)
if log:
print('Final train RMSE: {}'.format(train_rmse))
test_rmse = model.eval_rmse(test_data)
if log:
print('Final test RMSE: {}'.... |
def squash(cap_input):
'\n squash function for keep the length of capsules between 0 - 1\n :arg\n cap_input: total input of capsules,\n with shape: [None, h, w, c] or [None, n, d]\n :return\n cap_output: output of each capsules, which has the shape as cap_input\n '
... |
class CapsNet(object):
def __init__(self, mnist):
'initial class with mnist dataset'
self._mnist = mnist
self._dim = 28
self._num_caps = [0]
def _capsule(self, input, i_c, o_c, idx):
'\n compute a capsule,\n conv op with kernel: 9x9, stride: 2,\n ... |
def model_test():
model = CapsNet(None)
model.creat_architecture()
print('pass')
|
def main(_):
eps = (((1.0 * FLAGS.max_epsilon) / 256.0) / FLAGS.max_iter)
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
tf.reset_default_graph()
caps_net = CapsNet(mnist)
caps_net.creat_architecture()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tr... |
def model_test():
model = CapsNet(None)
model.creat_architecture()
print('pass')
|
def main(_):
eps = (((1.0 * FLAGS.max_epsilon) / 256.0) / FLAGS.max_iter)
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
tf.reset_default_graph()
caps_net = CapsNet(mnist)
caps_net.creat_architecture()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tr... |
def model_test():
model = CapsNet(None)
model.creat_architecture()
print('pass')
|
def main(_):
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
tf.reset_default_graph()
caps_net = CapsNet(mnist)
caps_net.creat_architecture()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
train_dir = cfg.TRAIN_DIR
ckpt = tf.train.get_checkpoint_state(... |
def download(url, dirpath):
filename = url.split('/')[(- 1)]
filepath = os.path.join(dirpath, filename)
u = urllib.request.urlopen(url)
f = open(filepath, 'wb')
filesize = int(u.headers['Content-Length'])
print(('Downloading: %s Bytes: %s' % (filename, filesize)))
downloaded = 0
block_... |
def download_file_from_google_drive(id, destination):
URL = 'https://docs.google.com/uc?export=download'
session = requests.Session()
response = session.get(URL, params={'id': id}, stream=True)
token = get_confirm_token(response)
if token:
params = {'id': id, 'confirm': token}
resp... |
def get_confirm_token(response):
for (key, value) in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
|
def save_response_content(response, destination, chunk_size=(32 * 1024)):
total_size = int(response.headers.get('content-length', 0))
with open(destination, 'wb') as f:
for chunk in tqdm(response.iter_content(chunk_size), total=total_size, unit='B', unit_scale=True, desc=destination):
if c... |
def unzip(filepath):
print(('Extracting: ' + filepath))
dirpath = os.path.dirname(filepath)
with zipfile.ZipFile(filepath) as zf:
zf.extractall(dirpath)
os.remove(filepath)
|
def download_celeb_a(dirpath):
data_dir = 'celebA'
if os.path.exists(os.path.join(dirpath, data_dir)):
print('Found Celeb-A - skip')
return
(filename, drive_id) = ('img_align_celeba.zip', '0B7EVK8r0v71pZjFTYXZWM3FlRnM')
save_path = os.path.join(dirpath, filename)
if os.path.exists(... |
def _list_categories(tag):
url = ('http://lsun.cs.princeton.edu/htbin/list.cgi?tag=' + tag)
f = urllib.request.urlopen(url)
return json.loads(f.read())
|
def _download_lsun(out_dir, category, set_name, tag):
url = 'http://lsun.cs.princeton.edu/htbin/download.cgi?tag={tag}&category={category}&set={set_name}'.format(**locals())
print(url)
if (set_name == 'test'):
out_name = 'test_lmdb.zip'
else:
out_name = '{category}_{set_name}_lmdb.zip'... |
def download_lsun(dirpath):
data_dir = os.path.join(dirpath, 'lsun')
if os.path.exists(data_dir):
print('Found LSUN - skip')
return
else:
os.mkdir(data_dir)
tag = 'latest'
categories = ['bedroom']
for category in categories:
_download_lsun(data_dir, category, 't... |
def download_mnist(dirpath):
data_dir = os.path.join(dirpath, 'mnist')
if os.path.exists(data_dir):
print('Found MNIST - skip')
return
else:
os.mkdir(data_dir)
url_base = 'http://yann.lecun.com/exdb/mnist/'
file_names = ['train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyt... |
def prepare_data_dir(path='./data'):
if (not os.path.exists(path)):
os.mkdir(path)
|
def main(_):
pp.pprint(flags.FLAGS.__flags)
if (FLAGS.input_width is None):
FLAGS.input_width = FLAGS.input_height
if (FLAGS.output_width is None):
FLAGS.output_width = FLAGS.output_height
if (not os.path.exists(FLAGS.checkpoint_dir)):
os.makedirs(FLAGS.checkpoint_dir)
if (... |
class batch_norm(object):
def __init__(self, epsilon=1e-05, momentum=0.9, name='batch_norm'):
with tf.variable_scope(name):
self.epsilon = epsilon
self.momentum = momentum
self.name = name
def __call__(self, x, train=True):
return tf.contrib.layers.batch_n... |
def conv_cond_concat(x, y):
'Concatenate conditioning vector on feature map axis.'
x_shapes = x.get_shape()
y_shapes = y.get_shape()
return concat([x, (y * tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]]))], 3)
|
def conv2d(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='conv2d'):
with tf.variable_scope(name):
w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[(- 1)], output_dim], initializer=tf.truncated_normal_initializer(stddev=stddev))
conv = tf.nn.conv2d(input_, w, strides=[1, d... |
def deconv2d(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='deconv2d', with_w=False):
with tf.variable_scope(name):
w = tf.get_variable('w', [k_h, k_w, output_shape[(- 1)], input_.get_shape()[(- 1)]], initializer=tf.random_normal_initializer(stddev=stddev))
try:
d... |
def lrelu(x, leak=0.2, name='lrelu'):
return tf.maximum(x, (leak * x))
|
def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False):
shape = input_.get_shape().as_list()
with tf.variable_scope((scope or 'Linear')):
matrix = tf.get_variable('Matrix', [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev))
bias = ... |
def create_dataset(file_path):
with h5py.File(file_path, 'r') as f, h5py.File('cuhk-03.h5') as fw:
val_index = (f[f['testsets'][0][0]][:].T - 1).tolist()
tes_index = (f[f['testsets'][0][1]][:].T - 1).tolist()
fwa = fw.create_group('a')
fwb = fw.create_group('b')
fwat = fwa.... |
class DataGenerator(Dataset):
def __init__(self, root, data_transform=None, image_dir=None, target_transform=None):
super(DataGenerator, self).__init__()
assert (image_dir is not None)
self.image_dir = image_dir
self.samples = []
self.img_label = []
self.img_flag =... |
class Dataset():
def __init__(self, root='/home/paul/datasets', dataset='market1501'):
self.dataset = dataset
self.root = root
def train_path(self):
if ((self.dataset == 'market1501') or (self.dataset == 'duke')):
return os.path.join(self.root, self.dataset, 'bounding_box... |
def read_image(img_path):
'Keep reading image until succeed.\n This can avoid IOError incurred by heavy IO process.'
got_img = False
if (not osp.exists(img_path)):
raise IOError('{} does not exist'.format(img_path))
while (not got_img):
try:
img = Image.open(img_path).co... |
class ImageDataset(Dataset):
'Image Person ReID Dataset'
def __init__(self, dataset, transform=None):
self.dataset = dataset
self.transform = transform
def __len__(self):
return len(self.dataset)
def __getitem__(self, index):
(img_path, pid, camid) = self.dataset[ind... |
class VideoDataset(Dataset):
'Video Person ReID Dataset.\n Note batch data has shape (batch, seq_len, channel, height, width).\n '
sample_methods = ['evenly', 'random', 'all']
def __init__(self, dataset, seq_len=15, sample='evenly', transform=None):
self.dataset = dataset
self.seq_l... |
def evaluate(qf, ql, qc, gf, gl, gc):
query = qf
score = np.dot(gf, query)
index = np.argsort(score)
index = index[::(- 1)]
query_index = np.argwhere((gl == ql))
camera_index = np.argwhere((gc == qc))
good_index = np.setdiff1d(query_index, camera_index, assume_unique=True)
junk_index1 ... |
def compute_mAP(index, good_index, junk_index):
ap = 0
cmc = torch.IntTensor(len(index)).zero_()
if (good_index.size == 0):
cmc[0] = (- 1)
return (ap, cmc)
mask = np.in1d(index, junk_index, invert=True)
index = index[mask]
ngood = len(good_index)
mask = np.in1d(index, good_... |
def weights_init_kaiming(m):
classname = m.__class__.__name__
if (classname.find('Conv') != (- 1)):
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
elif (classname.find('Linear') != (- 1)):
init.kaiming_normal_(m.weight.data, a=0, mode='fan_out')
init.constant_(m.bias.data,... |
def weights_init_classifier(m):
classname = m.__class__.__name__
if (classname.find('Linear') != (- 1)):
init.normal_(m.weight.data, std=0.001)
init.constant_(m.bias.data, 0.0)
|
class ClassBlock(nn.Module):
def __init__(self, input_dim, class_num, dropout=True, relu=True, num_bottleneck=512):
super(ClassBlock, self).__init__()
add_block = []
add_block += [nn.Linear(input_dim, num_bottleneck)]
add_block += [nn.BatchNorm1d(num_bottleneck)]
if relu:
... |
class ft_net(nn.Module):
def __init__(self, class_num):
super(ft_net, self).__init__()
model_ft = models.resnet50(pretrained=True)
model_ft.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.model = model_ft
self.classifier = ClassBlock(2048, class_num)
def forward(self, x):... |
class ft_net_dense(nn.Module):
def __init__(self, class_num):
super().__init__()
model_ft = models.densenet121(pretrained=True)
model_ft.features.avgpool = nn.AdaptiveAvgPool2d((1, 1))
model_ft.fc = nn.Sequential()
self.model = model_ft
self.classifier = ClassBlock... |
class ft_net_middle(nn.Module):
def __init__(self, class_num):
super(ft_net_middle, self).__init__()
model_ft = models.resnet50(pretrained=True)
model_ft.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.model = model_ft
self.classifier = ClassBlock((2048 + 1024), class_num)
... |
def generate_labels_for_gan():
image_labels = {}
f = open('/home/paul/datasets/viper/train.list', 'r')
old_lbl = (- 1)
for line in f:
line = line.strip()
(img, lbl) = line.split()
lbl = int(lbl)
if (lbl != old_lbl):
splt = img.split('_')
image_la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.