code stringlengths 17 6.64M |
|---|
def ResNeXt29_4x64d():
return ResNeXt(num_blocks=[3, 3, 3], cardinality=4, bottleneck_width=64)
|
def ResNeXt29_8x64d():
return ResNeXt(num_blocks=[3, 3, 3], cardinality=8, bottleneck_width=64)
|
def ResNeXt29_32x4d():
return ResNeXt(num_blocks=[3, 3, 3], cardinality=32, bottleneck_width=4)
|
def test_resnext():
net = ResNeXt29_2x64d()
x = torch.randn(1, 3, 32, 32)
y = net(x)
print(y.size())
|
class BasicBlock(nn.Module):
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, ... |
class PreActBlock(nn.Module):
def __init__(self, in_planes, planes, stride=1):
super(PreActBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
... |
class SENet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(SENet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_layer(block... |
def SENet18():
return SENet(PreActBlock, [2, 2, 2, 2])
|
def test():
net = SENet18()
y = net(torch.randn(1, 3, 32, 32))
print(y.size())
|
class ShuffleBlock(nn.Module):
def __init__(self, groups):
super(ShuffleBlock, self).__init__()
self.groups = groups
def forward(self, x):
'Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]'
(N, C, H, W) = x.size()
g = self.groups
retur... |
class Bottleneck(nn.Module):
def __init__(self, in_planes, out_planes, stride, groups):
super(Bottleneck, self).__init__()
self.stride = stride
mid_planes = (out_planes / 4)
g = (1 if (in_planes == 24) else groups)
self.conv1 = nn.Conv2d(in_planes, mid_planes, kernel_size=... |
class ShuffleNet(nn.Module):
def __init__(self, cfg):
super(ShuffleNet, self).__init__()
out_planes = cfg['out_planes']
num_blocks = cfg['num_blocks']
groups = cfg['groups']
self.conv1 = nn.Conv2d(3, 24, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(24)
... |
def ShuffleNetG2():
cfg = {'out_planes': [200, 400, 800], 'num_blocks': [4, 8, 4], 'groups': 2}
return ShuffleNet(cfg)
|
def ShuffleNetG3():
cfg = {'out_planes': [240, 480, 960], 'num_blocks': [4, 8, 4], 'groups': 3}
return ShuffleNet(cfg)
|
def test():
net = ShuffleNetG2()
x = torch.randn(1, 3, 32, 32)
y = net(x)
print(y)
|
class VGG(nn.Module):
def __init__(self, vgg_name):
super(VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, 10)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), (- 1))
out = self.cla... |
def test():
net = VGG('VGG11')
x = torch.randn(2, 3, 32, 32)
y = net(x)
print(y.size())
|
def narcissus_gen(dataset_path=dataset_path, lab=lab):
noise_size = 32
l_inf_r = (16 / 255)
surrogate_model = ResNet18_201().cuda()
generating_model = ResNet18_201().cuda()
surrogate_epochs = 200
generating_lr_warmup = 0.1
warmup_round = 5
generating_lr_tri = 0.01
gen_round = 1000
... |
class AISModel(nn.Module):
def __init__(self, model, init_dist):
super().__init__()
self.model = model
self.init_dist = init_dist
def forward(self, x, beta):
logpx = self.model(x).squeeze()
logpi = self.init_dist.log_prob(x).sum((- 1))
return ((logpx * beta) +... |
def evaluate(model, init_dist, sampler, train_loader, val_loader, test_loader, preprocess, device, n_iters, n_samples, steps_per_iter=1, viz_every=100):
model = AISModel(model, init_dist)
model.to(device)
betas = np.linspace(0.0, 1.0, n_iters)
samples = init_dist.sample((n_samples,))
log_w = torch... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def main(args):
makedirs(args.save_dir)
logger = open('{}/log.txt'.format(args.save_dir), 'w')
def my_print(s):
print(s)
logger.write((str(s) + '\n'))
torch.manual_seed(args.seed)
np.random.seed(args.seed)
if (args.model == 'lattice_potts'):
model = rbm.LatticePottsMod... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def main(args):
makedirs(args.save_dir)
logger = open('{}/log.txt'.format(args.save_dir), 'w')
def my_print(s):
print(s)
logger.write((str(s) + '\n'))
torch.manual_seed(args.seed)
np.random.seed(args.seed)
my_print('Loading data')
(train_loader, val_loader, test_loader, ar... |
class Swish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return (x * torch.sigmoid(x))
|
def mlp_ebm(nin, nint=256, nout=1):
return nn.Sequential(nn.Linear(nin, nint), Swish(), nn.Linear(nint, nint), Swish(), nn.Linear(nint, nint), Swish(), nn.Linear(nint, nout))
|
class MLPEBM_cat(nn.Module):
def __init__(self, nin, n_proj, n_cat=256, nint=256, nout=1):
super().__init__()
self.proj = nn.Linear(n_cat, n_proj)
self.n_proj = n_proj
self.net = mlp_ebm((nin * n_proj), nint, nout=nout)
def forward(self, x):
xr = x.view((x.size(0) * x... |
def conv_transpose_3x3(in_planes, out_planes, stride=1):
return nn.ConvTranspose2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, output_padding=1, bias=True)
|
def conv3x3(in_planes, out_planes, stride=1):
if (stride < 0):
return conv_transpose_3x3(in_planes, out_planes, stride=(- stride))
else:
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, out_nonlin=True):
super(BasicBlock, self).__init__()
self.nonlin1 = Swish()
self.nonlin2 = Swish()
self.conv1 = conv3x3(in_planes, planes, stride)
self.conv2 = conv3x3(planes, pl... |
class ResNetEBM(nn.Module):
def __init__(self, n_channels=64):
super().__init__()
self.proj = nn.Conv2d(1, n_channels, 3, 1, 1)
downsample = [BasicBlock(n_channels, n_channels, 2), BasicBlock(n_channels, n_channels, 2)]
main = [BasicBlock(n_channels, n_channels, 1) for _ in range(... |
class MNISTConvNet(nn.Module):
def __init__(self, nc=16):
super().__init__()
self.net = nn.Sequential(nn.Conv2d(1, nc, 3, 1, 1), Swish(), nn.Conv2d(nc, (nc * 2), 4, 2, 1), Swish(), nn.Conv2d((nc * 2), (nc * 2), 3, 1, 1), Swish(), nn.Conv2d((nc * 2), (nc * 4), 4, 2, 1), Swish(), nn.Conv2d((nc * 4)... |
class ResNetEBM_cat(nn.Module):
def __init__(self, shape, n_proj, n_cat=256, n_channels=64):
super().__init__()
self.shape = shape
self.n_cat = n_cat
self.proj = nn.Conv2d(n_cat, n_proj, 1, 1, 0)
self.proj2 = nn.Conv2d(n_proj, n_channels, 3, 1, 1)
downsample = [Bas... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def l1(module):
loss = 0.0
for p in module.parameters():
loss += p.abs().sum()
return loss
|
def main(args):
makedirs(args.save_dir)
logger = open('{}/log.txt'.format(args.save_dir), 'w')
def my_print(s):
print(s)
logger.write((str(s) + '\n'))
torch.manual_seed(args.seed)
np.random.seed(args.seed)
if ((args.data == 'mnist') or (args.data_file is not None)):
(t... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def main(args):
makedirs(args.save_dir)
torch.manual_seed(args.seed)
np.random.seed(args.seed)
model = rbm.BernoulliRBM(args.n_visible, args.n_hidden)
model.to(device)
print(device)
if (args.data == 'mnist'):
assert (args.n_visible == 784)
(train_loader, test_loader, plot, ... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def main(args):
makedirs(args.save_dir)
torch.manual_seed(args.seed)
np.random.seed(args.seed)
model = rbm.BernoulliRBM(args.n_visible, args.n_hidden)
model.to(device)
print(device)
if (args.data == 'mnist'):
assert (args.n_visible == 784)
(train_loader, test_loader, plot, ... |
def load_static_mnist(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = False
def lines_to_np_array(lines):
return np.array([[int(i) for i in line.split()] for line in lines])
with open(os.path.join('datasets', 'MNIST_static', 'binarized... |
def load_dynamic_mnist(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = True
from torchvision import datasets, transforms
train_loader = torch.utils.data.DataLoader(datasets.MNIST('../data', train=True, download=True, transform=transforms.Compos... |
def load_omniglot(args, n_validation=1345, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = True
def reshape_data(data):
return data.reshape(((- 1), 28, 28)).reshape(((- 1), (28 * 28)), order='F')
omni_raw = loadmat(os.path.join('datasets', '... |
def load_caltech101silhouettes(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = False
def reshape_data(data):
return data.reshape(((- 1), 28, 28)).reshape(((- 1), (28 * 28)), order='F')
caltech_raw = loadmat(os.path.join('datasets', 'Ca... |
def load_histopathologyGray(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'gray'
args.dynamic_binarization = False
with open('datasets/HistopathologyGray/histopathology.pkl', 'rb') as f:
data = pickle.load(f, encoding='latin1')
x_train = np.asarray(data['training']).resh... |
def load_freyfaces(args, TRAIN=1565, VAL=200, TEST=200, **kwargs):
args.input_size = [1, 28, 20]
args.input_type = 'gray'
args.dynamic_binarization = False
import scipy.io
data = scipy.io.loadmat('datasets/Freyfaces/frey_rawface')['ff'].T
data = (data / 256.0)
np.random.shuffle(data)
x... |
def load_cifar10(args, **kwargs):
args.input_size = [3, 32, 32]
args.input_type = 'continuous'
args.dynamic_binarization = False
from torchvision import datasets, transforms
transform = transforms.Compose([transforms.ToTensor()])
training_dataset = datasets.CIFAR10('datasets/Cifar10/', train=T... |
def load_dataset(args, **kwargs):
if (args.dataset_name == 'static_mnist'):
(train_loader, val_loader, test_loader, args) = load_static_mnist(args, **kwargs)
elif (args.dataset_name == 'dynamic_mnist'):
(train_loader, val_loader, test_loader, args) = load_dynamic_mnist(args, **kwargs)
elif... |
class AISModel(nn.Module):
def __init__(self, model, init_dist):
super().__init__()
self.model = model
self.init_dist = init_dist
def forward(self, x, beta):
logpx = self.model(x).squeeze()
logpi = self.init_dist.log_prob(x).sum((- 1))
return ((logpx * beta) +... |
def evaluate(model, init_dist, sampler, train_loader, val_loader, test_loader, preprocess, device, n_iters, n_samples, steps_per_iter=1, viz_every=100):
model = AISModel(model, init_dist)
model.to(device)
betas = np.linspace(0.0, 1.0, n_iters)
samples = init_dist.sample((n_samples,))
log_w = torch... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def main(args):
makedirs(args.save_dir)
logger = open('{}/log.txt'.format(args.save_dir), 'w')
def my_print(s):
print(s)
logger.write((str(s) + '\n'))
torch.manual_seed(args.seed)
np.random.seed(args.seed)
my_print('Loading data')
(train_loader, val_loader, test_loader, ar... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def get_ess(chain, burn_in):
c = chain
l = c.shape[0]
bi = int((burn_in * l))
c = c[bi:]
cv = tfp.mcmc.effective_sample_size(c).numpy()
cv[np.isnan(cv)] = 1.0
return cv
|
def get_log_rmse(x, gt_mean):
x = ((2.0 * x) - 1.0)
x2 = ((x - gt_mean) ** 2).mean().sqrt()
return x2.log().detach().cpu().numpy()
|
def tv(samples):
gt_probs = np.load('{}/gt_prob_{}_{}.npy'.format(args.save_dir, args.dim, args.bias))
(arrs, uniq_cnt) = np.unique(samples, axis=0, return_counts=True)
sample_probs = np.zeros_like(gt_probs)
for i in range(arrs.shape[0]):
sample_probs[i] = (((uniq_cnt[i] * 1.0) - 1.0) / sample... |
def get_gt_mean(args, model):
dim = (args.dim ** 2)
A = model.J
b = args.bias
lst = torch.tensor(list(itertools.product([(- 1.0), 1.0], repeat=dim))).to(device)
f = (lambda x: torch.exp((((x @ A) * x).sum((- 1)) + torch.sum((b * x), dim=(- 1)))))
flst = f(lst)
plst = (flst / torch.sum(flst... |
def main(args):
makedirs(args.save_dir)
torch.manual_seed(args.seed)
np.random.seed(args.seed)
model = rbm.LatticeIsingModel(args.dim, args.sigma, args.bias)
model.to(device)
gt_mean = get_gt_mean(args, model)
plot = (lambda p, x: torchvision.utils.save_image(x.view(x.size(0), 1, args.dim,... |
class Swish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return (x * torch.sigmoid(x))
|
def mlp_ebm(nin, nint=256, nout=1):
return nn.Sequential(nn.Linear(nin, nint), Swish(), nn.Linear(nint, nint), Swish(), nn.Linear(nint, nint), Swish(), nn.Linear(nint, nout))
|
class MLPEBM_cat(nn.Module):
def __init__(self, nin, n_proj, n_cat=256, nint=256, nout=1):
super().__init__()
self.proj = nn.Linear(n_cat, n_proj)
self.n_proj = n_proj
self.net = mlp_ebm((nin * n_proj), nint, nout=nout)
def forward(self, x):
xr = x.view((x.size(0) * x... |
def conv_transpose_3x3(in_planes, out_planes, stride=1):
return nn.ConvTranspose2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, output_padding=1, bias=True)
|
def conv3x3(in_planes, out_planes, stride=1):
if (stride < 0):
return conv_transpose_3x3(in_planes, out_planes, stride=(- stride))
else:
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, out_nonlin=True):
super(BasicBlock, self).__init__()
self.nonlin1 = Swish()
self.nonlin2 = Swish()
self.conv1 = conv3x3(in_planes, planes, stride)
self.conv2 = conv3x3(planes, pl... |
class ResNetEBM(nn.Module):
def __init__(self, n_channels=64):
super().__init__()
self.proj = nn.Conv2d(1, n_channels, 3, 1, 1)
downsample = [BasicBlock(n_channels, n_channels, 2), BasicBlock(n_channels, n_channels, 2)]
main = [BasicBlock(n_channels, n_channels, 1) for _ in range(... |
class MNISTConvNet(nn.Module):
def __init__(self, nc=16):
super().__init__()
self.net = nn.Sequential(nn.Conv2d(1, nc, 3, 1, 1), Swish(), nn.Conv2d(nc, (nc * 2), 4, 2, 1), Swish(), nn.Conv2d((nc * 2), (nc * 2), 3, 1, 1), Swish(), nn.Conv2d((nc * 2), (nc * 4), 4, 2, 1), Swish(), nn.Conv2d((nc * 4)... |
class ResNetEBM_cat(nn.Module):
def __init__(self, shape, n_proj, n_cat=256, n_channels=64):
super().__init__()
self.shape = shape
self.n_cat = n_cat
self.proj = nn.Conv2d(n_cat, n_proj, 1, 1, 0)
self.proj2 = nn.Conv2d(n_proj, n_channels, 3, 1, 1)
downsample = [Bas... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def l1(module):
loss = 0.0
for p in module.parameters():
loss += p.abs().sum()
return loss
|
def main(args):
makedirs(args.save_dir)
logger = open('{}/log.txt'.format(args.save_dir), 'w')
def my_print(s):
print(s)
logger.write((str(s) + '\n'))
torch.manual_seed(args.seed)
np.random.seed(args.seed)
if ((args.data == 'mnist') or (args.data_file is not None)):
(t... |
def makedirs(dirname):
"\n Make directory only if it's not already there.\n "
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def get_ess(chain, burn_in):
c = chain
l = c.shape[0]
bi = int((burn_in * l))
c = c[bi:]
cv = tfp.mcmc.effective_sample_size(c).numpy()
cv[np.isnan(cv)] = 1.0
return cv
|
def main(args):
makedirs(args.save_dir)
torch.manual_seed(args.seed)
np.random.seed(args.seed)
model = rbm.BernoulliRBM(args.n_visible, args.n_hidden)
model.to(device)
if (args.data == 'mnist'):
assert (args.n_visible == 784)
(train_loader, test_loader, plot, viz) = utils.get_d... |
def load_static_mnist(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = False
def lines_to_np_array(lines):
return np.array([[int(i) for i in line.split()] for line in lines])
with open(os.path.join('datasets', 'MNIST_static', 'binarized... |
def load_dynamic_mnist(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = True
from torchvision import datasets, transforms
train_loader = torch.utils.data.DataLoader(datasets.MNIST('../data', train=True, download=True, transform=transforms.Compos... |
def load_omniglot(args, n_validation=1345, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = True
def reshape_data(data):
return data.reshape(((- 1), 28, 28)).reshape(((- 1), (28 * 28)), order='F')
omni_raw = loadmat(os.path.join('datasets', '... |
def load_caltech101silhouettes(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'binary'
args.dynamic_binarization = False
def reshape_data(data):
return data.reshape(((- 1), 28, 28)).reshape(((- 1), (28 * 28)), order='F')
caltech_raw = loadmat(os.path.join('datasets', 'Ca... |
def load_histopathologyGray(args, **kwargs):
args.input_size = [1, 28, 28]
args.input_type = 'gray'
args.dynamic_binarization = False
with open('datasets/HistopathologyGray/histopathology.pkl', 'rb') as f:
data = pickle.load(f, encoding='latin1')
x_train = np.asarray(data['training']).resh... |
def load_freyfaces(args, TRAIN=1565, VAL=200, TEST=200, **kwargs):
args.input_size = [1, 28, 20]
args.input_type = 'gray'
args.dynamic_binarization = False
import scipy.io
data = scipy.io.loadmat('datasets/Freyfaces/frey_rawface')['ff'].T
data = (data / 256.0)
np.random.shuffle(data)
x... |
def load_cifar10(args, **kwargs):
args.input_size = [3, 32, 32]
args.input_type = 'continuous'
args.dynamic_binarization = False
from torchvision import datasets, transforms
transform = transforms.Compose([transforms.ToTensor()])
training_dataset = datasets.CIFAR10('datasets/Cifar10/', train=T... |
def load_dataset(args, **kwargs):
if (args.dataset_name == 'static_mnist'):
(train_loader, val_loader, test_loader, args) = load_static_mnist(args, **kwargs)
elif (args.dataset_name == 'dynamic_mnist'):
(train_loader, val_loader, test_loader, args) = load_dynamic_mnist(args, **kwargs)
elif... |
def tf_to_pth(tensorflow_model):
reader = pywrap_tensorflow.NewCheckpointReader(tensorflow_model)
var_to_shape_map = reader.get_variable_to_shape_map()
var_dict = {k: reader.get_tensor(k) for k in var_to_shape_map.keys()}
if ('beta1_power' in var_dict):
del var_dict['beta1_power']
if ('bet... |
def sparse_dropout(x, keep_prob, noise_shape):
'Dropout for sparse tensors.'
random_tensor = keep_prob
random_tensor += tf.random_uniform(noise_shape)
dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool)
pre_out = tf.sparse_retain(x, dropout_mask)
return (pre_out * (1.0 / keep_prob))... |
class Dense(Module):
'Dense layer.'
def __init__(self, input_dim, output_dim, support_num=0, dropout=0.0, bias=False):
super(Dense, self).__init__()
self.dropout = dropout
self.weights = Parameter(torch.Tensor(input_dim, output_dim))
if bias:
self.bias = torch.zero... |
class SparseMM(torch.autograd.Function):
'\n Sparse x dense matrix multiplication with autograd support.\n Implementation by Soumith Chintala:\n https://discuss.pytorch.org/t/\n does-pytorch-support-autograd-on-sparse-matrix/6156/7\n '
def __init__(self, sparse):
super(SparseMM, self).... |
class GraphConvolution(Module):
'Graph convolution layer.'
def __init__(self, input_dim, output_dim, support_num, dropout=0.0, bias=False):
super(GraphConvolution, self).__init__()
self.input_dim = input_dim
self.outptu_dim = output_dim
self.dropout = dropout
for i in ... |
def masked_softmax_cross_entropy(preds, labels, mask):
'Softmax cross-entropy loss with masking.'
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss)
|
def masked_accuracy(preds, labels, mask):
'Accuracy with masking.'
correct_prediction = tf.equal(tf.argmax(preds, 1), tf.argmax(labels, 1))
accuracy_all = tf.cast(correct_prediction, tf.float32)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
accuracy_all *= mask
return... |
def masked_sigmoid_cross_entropy(preds, labels, mask):
'Sigmoid cross-entropy loss with masking.'
loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return tf.reduce_mean(loss)
|
def mask_mse_loss(preds, labels, mask):
'Sigmoid cross-entropy loss with masking.'
mask = mask.float()
mask /= mask.mean()
labels = (labels * mask)
preds = (preds * mask)
loss = (F.mse_loss(labels, preds, size_average=False) / 2)
return loss
|
def parse_hiddens(dim_in, dim_out):
hidden_layers = FLAGS.hiddens
if (len(hidden_layers) == 0):
hidden_layers = str(dim_out)
elif (len(hidden_layers) == 1):
hidden_layers = (str(dim_out) + 'd')
elif ((hidden_layers[(- 1)] == ',') or (hidden_layers[(- 2)] == ',')):
hidden_layers... |
class Model_dense_mse(nn.Module):
def __init__(self, layer_func, input_dim, output_dim, support_num, dropout, logging, features=None):
super(Model_dense_mse, self).__init__()
if FLAGS.trainable_embedding:
self.register_parameter('features', nn.Parameter(torch.from_numpy(features).floa... |
class GCN_dense_mse(Model_dense_mse):
def __init__(self, *args, **kwargs):
super(GCN_dense_mse, self).__init__(GraphConvolution, *args, **kwargs)
|
class Pure_dense_mse(Model_dense_mse):
def __init__(self, *args, **kwargs):
super(Pure_dense_mse, self).__init__(Dense, *args, **kwargs)
|
def to_sparse(x):
' converts dense tensor x to sparse format '
return torch.sparse.FloatTensor(torch.from_numpy(x[0]).long().t(), torch.from_numpy(x[1]).float(), x[2])
|
def test_imagenet_zero(fc_file_pred, has_train=1):
with open(classids_file_retrain) as fp:
classids = json.load(fp)
with open(word2vec_file, 'rb') as fp:
word2vec_feat = pkl.load(fp)
testlist = []
testlabels = []
with open(vallist_folder) as fp:
for line in fp:
... |
class Dummy(torch.utils.data.Dataset):
def __init__(self, testlist, testlabel, valid_clss, labels_train):
self.inv_labels_train = {v: k for (k, v) in enumerate(labels_train)}
(self.testlist, self.testlabel) = zip(*[(_, __) for (_, __) in zip(testlist, testlabel) if (valid_clss[__] != 0)])
de... |
def accuracy(output, target, topk=(1,)):
'Computes the precision@k for the specified values of k'
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expa... |
def test_imagenet_zero(fc_file_pred, has_train=1):
with open(classids_file_retrain) as fp:
classids = json.load(fp)
with open(word2vec_file, 'rb') as fp:
word2vec_feat = pkl.load(fp)
testlist = []
testlabels = []
with open(vallist_folder) as fp:
for line in fp:
... |
class Dummy(torch.utils.data.Dataset):
def __init__(self, testlist, testlabel, valid_clss, labels_train):
self.inv_labels_train = {v: k for (k, v) in enumerate(labels_train)}
(self.testlist, self.testlabel) = zip(*[(_, __) for (_, __) in zip(testlist, testlabel) if (valid_clss[__] != 0)])
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.