code stringlengths 17 6.64M |
|---|
def file_exists(file_path):
return os.path.isfile(file_path)
|
def assert_file_exists(file_path):
if file_exists(file_path):
return
else:
raise FileNotFoundError('Cannot find file: {:s}'.format(os.path.abspath(file_path)))
|
def assert_path_exists(file_or_dir):
if os.path.exists(file_or_dir):
return
else:
raise FileNotFoundError('Cannot find file or dir: {:s}'.format(os.path.abspath(file_or_dir)))
|
def before_save(file_or_dir):
'\n make sure that the dedicated path exists (create if not exist)\n :param file_or_dir:\n :return:\n '
dir_name = os.path.dirname(os.path.abspath(file_or_dir))
if (not os.path.exists(dir_name)):
os.makedirs(dir_name)
|
def get_ext(filename):
(_, ext) = os.path.splitext(filename)
return ext
|
def register_file_handling(ext: str, saver: Saver, loader: Loader):
assert (ext not in _ext_table)
_ext_table[ext] = (saver, loader)
|
def save_file(obj, filename, *args, **kwargs):
ext = get_ext(filename)
if (ext in _ext_table):
before_save(filename)
return _ext_table[ext][0](obj, filename, *args, **kwargs)
else:
raise ValueError('Unsupported file {} with file extension {}'.format(filename, ext))
|
def load_file(filename, *args, **kwargs):
ext = get_ext(filename)
if (ext in _ext_table):
return _ext_table[ext][1](filename, *args, **kwargs)
else:
raise ValueError('Unsupported file {} with file extension {}'.format(filename, ext))
|
def get_discretizer(method='mdlp', *args, **kwargs):
if (method == 'mdlp'):
return MDLP(*args, **kwargs)
else:
raise ValueError(('Not supporting method %s' % method))
|
def compute_mdlp_all_intervals(mdlp_discretizer):
category_names = []
for (i, cut_points) in enumerate(mdlp_discretizer.cut_points_):
if (cut_points is None):
category_names.append(None)
continue
idxs = np.arange((len(cut_points) + 1))
names = mdlp_discretizer.a... |
class RuleList(BayesianRuleList):
def __init__(self, min_rule_len=1, max_rule_len=2, min_support=0.02, lambda_=20, eta=1, iters=30000, n_chains=30, alpha=1, fim_method='eclat', feature_names=None, category_names=None, seed=None, verbose=0, discretize_method='mdlp', numeric_features=None):
'\n Simi... |
def surrogate(student, teacher, X, verbose=False):
'\n Fit a model that surrogates the target_predict function\n :param student: An object (sklearn style model) that has fit, predict method.\n The fit method: (train_x, train_y, **kwargs)\n The predict method: (x) -> y (np.int)\n :param teac... |
def fidelity(teacher, student, X):
y_target = teacher(X)
y_pred = student.predict(X)
return accuracy(y_target, y_pred)
|
class Surrogate(object):
'\n A factory like implementation of the surrogate algorithm\n Suitable for creating a Pipeline Surrogate model\n '
def __init__(self, teacher, student=None, is_continuous=None, is_categorical=None, is_integer=None, ranges=None, cov_factor=1.0, sampling_rate=2.0, seed=None, ... |
def rule_surrogate(target, train_x, is_continuous=None, is_categorical=None, is_integer=None, ranges=None, cov_factor=1.0, sampling_rate=2.0, seed=None, rlargs=None):
n_features = train_x.shape[1]
(is_continuous, is_categorical, is_integer) = check_input_constraints(n_features, is_continuous, is_categorical, ... |
def get_url(name, remote=False, root_url=None):
if remote:
return _remote_urls[name]
if (root_url is None):
return (STATIC_LOCAL_URL + _local_urls[name])
return (root_url + _local_urls[name])
|
def get_id(obj, prefix='rm', suffix=''):
objid = ((prefix + str(id(obj))) + suffix)
return objid
|
def install_static(local_path=None, target_name=None, overwrite=False):
'\n Write the javascript libraries to the given location.\n This utility is used by the IPython notebook tools to enable easy use\n of pyLDAvis with no web connection.\n Parameters\n ----------\n local_path: string (optional... |
def load_model(filename: str):
if (not os.path.isfile(filename)):
raise FileNotFoundError('Cannot find file: {:s}'.format(os.path.abspath(filename)))
with open(filename, 'rb') as f:
mdl = pickle.load(f)
return mdl
|
def save_model(mdl, filename):
dir_name = os.path.dirname(os.path.abspath(filename))
if (not os.path.exists(dir_name)):
os.makedirs(dir_name)
with open(filename, 'wb') as f:
return pickle.dump(mdl, f)
|
def train_nn(dataset, neurons=(20,), **kwargs):
(train_x, train_y, test_x, test_y) = (dataset['train_x'], dataset['train_y'], dataset['test_x'], dataset['test_y'])
is_categorical = dataset.get('is_categorical', None)
model = MLPClassifier(hidden_layer_sizes=neurons, **kwargs)
if (is_categorical is not... |
def train_surrogate(model, dataset, sampling_rate=2.0, **kwargs):
(train_x, train_y, test_x, test_y) = (dataset['train_x'], dataset['train_y'], dataset['test_x'], dataset['test_y'])
is_continuous = dataset.get('is_continuous', None)
is_categorical = dataset.get('is_categorical', None)
is_integer = dat... |
def prepare_data(name_or_path):
if (name_or_path == 'iris'):
dataset = load_iris()
elif (name_or_path == 'breast_cancer'):
dataset = load_breast_cancer()
else:
try:
with open(name_or_path, 'rb') as f:
dataset = pickle.load(f)
except FileNotFoundE... |
def main():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--dataset', type=str, default='iris')
parser.add_argument('--sample_rate', type=float, default=2.0)
args = parser.parse_args()
dataset = prepare_data(args.dataset)
nn = train_nn(dataset, (20, 20)... |
def normalize(data):
meanv = np.mean(data, axis=0)
stdv = np.std(data, axis=0)
delta = (data - meanv)
data = (delta / stdv)
return data
|
def load_dataset(norm_flag=True):
imgX = sio.loadmat('river/river_before.mat')['river_before']
imgY = sio.loadmat('river/river_after.mat')['river_after']
imgX = np.reshape(imgX, newshape=[(- 1), imgX.shape[(- 1)]])
imgY = np.reshape(imgY, newshape=[(- 1), imgY.shape[(- 1)]])
GT = sio.loadmat('rive... |
def cva(X, Y):
diff = (X - Y)
diff_s = (diff ** 2).sum(axis=(- 1))
return np.sqrt(diff_s)
|
def SFA(X, Y):
'\n see http://sigma.whu.edu.cn/data/res/files/SFACode.zip\n '
norm_flag = True
(m, n) = np.shape(X)
meanX = np.mean(X, axis=0)
meanY = np.mean(Y, axis=0)
stdX = np.std(X, axis=0)
stdY = np.std(Y, axis=0)
Xc = ((X - meanX) / stdX)
Yc = ((Y - meanY) / stdY)
... |
class LeNetBBB(nn.Module):
def __init__(self, num_classes=10, var0=1, estimator='flipout'):
_check_estimator(estimator)
super().__init__()
Conv2dVB = (Conv2dReparameterization if (estimator == 'reparam') else Conv2dFlipout)
LinearVB = (LinearReparameterization if (estimator == 're... |
def _check_estimator(estimator):
assert (estimator in ['reparam', 'flipout']), 'Estimator must be either "reparam" or "flipout"'
|
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, var0=1, dropRate=0.0, estimator='reparam'):
_check_estimator(estimator)
super().__init__()
Conv2dVB = (Conv2dReparameterization if (estimator == 'reparam') else Conv2dFlipout)
self.bn1 = nn.BatchNorm2d(... |
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, var0=1, dropRate=0.0, estimator='reparam'):
_check_estimator(estimator)
super().__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, var0, dropRate)
... |
class WideResNetBBB(nn.Module):
def __init__(self, depth, widen_factor, num_classes, num_channel=3, var0=1, droprate=0, estimator='reparam', feature_extractor=False):
_check_estimator(estimator)
super().__init__()
Conv2dVB = (Conv2dReparameterization if (estimator == 'reparam') else Conv2... |
def _check_estimator(estimator):
assert (estimator in ['reparam', 'flipout']), 'Estimator must be either "reparam" or "flipout"'
|
class CSGHMCTrainer():
def __init__(self, model, n_cycles, n_samples_per_cycle, n_epochs, initial_lr, num_batch, total_iters, data_size, weight_decay=0.0005, alpha=0.9):
self.model = model
self.n_cycles = n_cycles
self.n_samples_per_cycle = n_samples_per_cycle
self.n_epochs = n_ep... |
class LeNet(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.net = nn.Sequential(torch.nn.Conv2d(1, 6, 5), torch.nn.ReLU(), torch.nn.MaxPool2d(2), torch.nn.Conv2d(6, 16, 5), torch.nn.ReLU(), torch.nn.MaxPool2d(2), torch.nn.Flatten(), torch.nn.Linear(((16 * 4) * 4), 120), to... |
class MLP(nn.Module):
def __init__(self, size, act='sigmoid'):
super(type(self), self).__init__()
self.num_layers = (len(size) - 1)
lower_modules = []
for i in range((self.num_layers - 1)):
lower_modules.append(nn.Linear(size[i], size[(i + 1)]))
if (act == ... |
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padd... |
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super(NetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
def _make_layer(self, block, in_planes, out_planes, ... |
class WideResNet(nn.Module):
def __init__(self, depth, widen_factor, num_classes=10, dropRate=0.0):
super(WideResNet, self).__init__()
nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)]
assert (((depth - 4) % 6) == 0)
n = ((depth - 4) // 6)
blo... |
class FixupBasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(FixupBasicBlock, self).__init__()
self.bias1 = Bias()
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, ... |
class FixupNetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super(FixupNetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
def _make_layer(self, block, in_planes, ou... |
class FixupWideResNet(nn.Module):
def __init__(self, depth, widen_factor, num_classes=10, dropRate=0.0):
super(FixupWideResNet, self).__init__()
nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)]
assert (((depth - 4) % 6) == 0)
n = ((depth - 4) // 6)
... |
def main(args):
device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu'))
util.set_seed(args.seed)
datagen = du.PermutedMnistGenerator(data_path=args.data_root, num_tasks=args.num_tasks, download=args.download)
model = util.get_model(model_class='MLP')
model.to(device)
backend ... |
def train(args, model, la, train_loader, task_id, device):
model.train()
N = len(train_loader.dataset)
loss_fn = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
n_steps = (args.num_epochs * len(train_loader))
scheduler = CosineAnnealingLR(optimizer, n_s... |
def optimize_marglik(la, train_loader):
prior_prec = la.prior_precision
hyper_la = deepcopy(la)
hyper_la.prior_mean = la.mean
hyper_la.fit(train_loader, override=False)
hyper_la.optimize_prior_precision(init_prior_prec=prior_prec)
la.prior_precision = hyper_la.prior_precision.clone()
retur... |
@torch.no_grad()
def test(args, laplace, test_loaders, device):
test_accs = list()
for test_loader in test_loaders:
correct = 0
for (X, y) in test_loader:
f = laplace(X.to(device))
correct += (y.to(device) == f.argmax(1)).sum()
acc = (correct.item() / len(test_l... |
def marglik_optimization(model, train_loader, valid_loader=None, likelihood='classification', prior_structure='layerwise', prior_prec_init=1.0, sigma_noise_init=1.0, temperature=1.0, n_epochs=500, lr=0.001, lr_min=None, optimizer='Adam', scheduler='exp', n_epochs_burnin=0, n_hypersteps=100, marglik_frequency=1, lr_hy... |
def valid_performance(model, test_loader, likelihood, device):
N = len(test_loader.dataset)
perf = 0
for (X, y) in test_loader:
(X, y) = (X.to(device), y.to(device))
if (likelihood == 'classification'):
perf += ((torch.argmax(model(X), dim=(- 1)) == y).sum() / N)
else:
... |
def main(base_config, config, temperature, seed, noda):
config_name = config.split('/')[(- 1)].split('.')[0]
if noda:
assert (temperature == 1)
run_name = ((('CIFARNODA' + '_') + config_name) + f'_{seed}')
else:
run_name = ((('CIFAR' + '_') + config_name) + f'_{temperature}_{seed}'... |
def main(base_config, config, seed):
config_name = config.split('/')[(- 1)].split('.')[0]
run_name = ((('FMNIST' + '_') + config_name) + f'_{seed}')
model_path = (('models/' + run_name) + '_model.pt')
delta_path = (('models/' + run_name) + '_delta.pt')
cmd_train = f'python marglik_training/train_m... |
def main(base_config, config, seed):
config_name = config.split('/')[(- 1)].split('.')[0]
run_name = ((('MNIST' + '_') + config_name) + f'_{seed}')
cmd_train = f'python marglik_training/train_marglik.py --run_name {run_name} --config {base_config} {config} --seed {seed}'
print('RUN:', cmd_train)
o... |
def get_laplace_class(flavor, last_layer):
if (flavor == 'diag'):
if last_layer:
return DiagLLLaplace
else:
return DiagLaplace
elif (flavor == 'kron'):
if last_layer:
return KronLLLaplace
else:
return KronLaplace
elif (flavor ... |
def get_backend(backend, approx_type):
if (backend == 'kazuki'):
if (approx_type == 'ggn'):
return AsdlGGN
else:
return AsdlEF
elif (backend == 'backpack'):
if (approx_type == 'ggn'):
return BackPackGGN
else:
return BackPackEF
... |
def main(args):
device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu'))
args.prior_precision = util.get_prior_precision(args, device)
util.set_seed(args.seed)
(in_data_loaders, ids, no_loss_acc) = du.get_in_distribution_data_loaders(args, device)
(train_loader, val_loader, in_tes... |
def fit_models(args, train_loader, val_loader, device):
' load pre-trained weights, fit inference methods, and tune hyperparameters '
mixture_components = list()
for model_idx in range(args.nr_components):
model = util.load_pretrained_model(args, model_idx, device)
if (args.method in ['lap... |
def evaluate_models(args, mixture_components, in_test_loader, ids, no_loss_acc, device):
' evaluate the models and return relevant evaluation metrics '
metrics = []
for (i, id) in enumerate(ids):
test_loader = (in_test_loader if (i == 0) else du.get_ood_test_loader(args, id))
(test_output,... |
def compute_metrics(i, id, all_y_prob, test_loader, all_y_prob_in, all_y_var, args):
' compute evaluation metrics '
metrics = {}
if ((args.benchmark in ['R-MNIST', 'R-FMNIST', 'CIFAR-10-C', 'ImageNet-C']) and (args.benchmark != 'WILDS-poverty')):
print(f'{args.benchmark} with distribution shift in... |
def get_in_distribution_data_loaders(args, device):
' load in-distribution datasets and return data loaders '
if (args.benchmark in ['R-MNIST', 'MNIST-OOD']):
if (args.benchmark == 'R-MNIST'):
no_loss_acc = False
ids = [0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180]
... |
def get_ood_test_loader(args, id):
' load out-of-distribution test data and return data loader '
if (args.benchmark == 'R-MNIST'):
(_, test_loader) = get_rotated_mnist_loaders(id, args.data_root, model_class=args.model, download=args.download)
elif (args.benchmark == 'R-FMNIST'):
(_, test_... |
def val_test_split(dataset, val_size=5000, batch_size=512, num_workers=5, pin_memory=False):
test_size = (len(dataset) - val_size)
(dataset_val, dataset_test) = data_utils.random_split(dataset, (val_size, test_size), generator=torch.Generator().manual_seed(42))
val_loader = data_utils.DataLoader(dataset_v... |
def get_cifar10_loaders(data_path, batch_size=512, val_size=2000, train_batch_size=128, download=False, data_augmentation=True):
mean = [(x / 255) for x in [125.3, 123.0, 113.9]]
std = [(x / 255) for x in [63.0, 62.1, 66.7]]
tforms = [transforms.ToTensor(), transforms.Normalize(mean, std)]
tforms_test... |
def get_imagenet_loaders(data_path, batch_size=128, val_size=2000, train_batch_size=128, num_workers=5):
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
tforms_test = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normaliz... |
def get_mnist_loaders(data_path, batch_size=512, model_class='LeNet', train_batch_size=128, val_size=2000, download=False, device='cpu'):
if (model_class == 'MLP'):
tforms = transforms.Compose([transforms.ToTensor(), ReshapeTransform(((- 1),))])
else:
tforms = transforms.ToTensor()
train_s... |
def get_fmnist_loaders(data_path, batch_size=512, model_class='LeNet', train_batch_size=128, val_size=2000, download=False, device='cpu'):
if (model_class == 'MLP'):
tforms = transforms.Compose([transforms.ToTensor(), ReshapeTransform(((- 1),))])
else:
tforms = transforms.ToTensor()
train_... |
def get_rotated_mnist_loaders(angle, data_path, model_class='LeNet', download=False):
if (model_class == 'MLP'):
shift_tforms = transforms.Compose([RotationTransform(angle), transforms.ToTensor(), ReshapeTransform(((- 1),))])
else:
shift_tforms = transforms.Compose([RotationTransform(angle), t... |
def get_rotated_fmnist_loaders(angle, data_path, model_class='LeNet', download=False):
if (model_class == 'MLP'):
shift_tforms = transforms.Compose([RotationTransform(angle), transforms.ToTensor(), ReshapeTransform(((- 1),))])
else:
shift_tforms = transforms.Compose([RotationTransform(angle), ... |
class ReshapeTransform():
def __init__(self, new_size):
self.new_size = new_size
def __call__(self, img):
return torch.reshape(img, self.new_size)
|
class RotationTransform():
'Rotate the given angle.'
def __init__(self, angle):
self.angle = angle
def __call__(self, x):
return TF.rotate(x, self.angle)
|
def uniform_noise(dataset, delta=1, size=5000, batch_size=512):
if (dataset in ['MNIST', 'FMNIST', 'R-MNIST']):
shape = (1, 28, 28)
elif (dataset in ['SVHN', 'CIFAR10', 'CIFAR100', 'CIFAR-10-C']):
shape = (3, 32, 32)
elif (dataset in ['ImageNet', 'ImageNet-C']):
shape = (3, 256, 25... |
class DatafeedImage(torch.utils.data.Dataset):
def __init__(self, x_train, y_train, transform=None):
self.x_train = x_train
self.y_train = y_train
self.transform = transform
def __getitem__(self, index):
img = self.x_train[index]
img = Image.fromarray(img)
if ... |
def load_corrupted_cifar10(severity, data_dir='data', batch_size=256, cuda=True, workers=1):
' load corrupted CIFAR10 dataset '
x_file = (data_dir + ('/CIFAR-10-C/CIFAR10_c%d.npy' % severity))
np_x = np.load(x_file)
y_file = (data_dir + '/CIFAR-10-C/CIFAR10_c_labels.npy')
np_y = np.load(y_file).as... |
def load_corrupted_imagenet(severity, data_dir='data', batch_size=128, cuda=True, workers=1):
' load corrupted ImageNet dataset '
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
transform = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), tran... |
def get_mnist_ood_loaders(ood_dataset, data_path='./data', batch_size=512, download=False):
'Get out-of-distribution val/test sets and val/test loaders (in-distribution: MNIST/FMNIST)'
tforms = transforms.ToTensor()
if (ood_dataset == 'FMNIST'):
fmnist_val_test_set = datasets.FashionMNIST(data_pat... |
def get_cifar10_ood_loaders(ood_dataset, data_path='./data', batch_size=512, download=False):
'Get out-of-distribution val/test sets and val/test loaders (in-distribution: CIFAR-10)'
if (ood_dataset == 'SVHN'):
svhn_tforms = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4376821, 0... |
class FastTensorDataLoader():
'\n Source: https://github.com/hcarlens/pytorch-tabular/blob/master/fast_tensor_data_loader.py\n and https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6\n '
def __init__(self, *tensors, batch_size=32, shuffle=False):
assert all(((t.... |
class PermutedMnistGenerator():
def __init__(self, data_path='./data', num_tasks=10, random_seed=0, download=False):
self.data_path = data_path
self.num_tasks = num_tasks
self.random_seed = random_seed
self.download = download
self.out_dim = 10
self.in_dim = 784
... |
@torch.no_grad()
def test(components, test_loader, prediction_mode, pred_type='glm', n_samples=100, link_approx='probit', no_loss_acc=False, device='cpu', likelihood='classification', sigma_noise=None):
temperature_scaling_model = None
if (prediction_mode in ['map', 'laplace', 'bbb', 'csghmc']):
model... |
@torch.no_grad()
def predict(dataloader, model):
py = []
for (x, y) in dataloader:
x = x.cuda()
py.append(torch.softmax(model(x), (- 1)))
return torch.cat(py, dim=0)
|
@torch.no_grad()
def predict_ensemble(dataloader, models):
py = []
for (x, y) in dataloader:
x = x.cuda()
_py = 0
for model in models:
_py += ((1 / len(models)) * torch.softmax(model(x), (- 1)))
py.append(_py)
return torch.cat(py, dim=0)
|
@torch.no_grad()
def predict_vb(dataloader, model, n_samples=1):
py = []
for (x, y) in dataloader:
x = x.cuda()
_py = 0
for _ in range(n_samples):
(f_s, _) = model(x)
_py += torch.softmax(f_s, 1)
_py /= n_samples
py.append(_py)
return torch.c... |
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
cudnn.deterministic = True
cudnn.benchmark = False
|
def load_pretrained_model(args, model_idx, device):
' Choose appropriate architecture and load pre-trained weights '
if ('WILDS' in args.benchmark):
dataset = args.benchmark[6:]
model = wu.load_pretrained_wilds_model(dataset, args.models_root, device, model_idx, args.model_seed)
else:
... |
def get_model(model_class, no_dropout=False):
if (model_class == 'MLP'):
model = mlp.MLP([784, 100, 100, 10], act='relu')
elif (model_class == 'LeNet'):
model = lenet.LeNet()
elif (model_class == 'LeNet-BBB-reparam'):
model = lenet_bbb.LeNetBBB(estimator='reparam')
elif (model_... |
def mixture_model_pred(components, x, mixture_weights, prediction_mode='mola', pred_type='glm', link_approx='probit', n_samples=100, likelihood='classification'):
if (prediction_mode == 'ensemble'):
return ensemble_pred(components, x, likelihood=likelihood)
out = 0.0
for (model, pi) in zip(compone... |
def ensemble_pred(components, x, likelihood='classification'):
' Make predictions for deep ensemble '
outs = []
for model in components:
model.eval()
out_prob = model(x).detach()
if (likelihood == 'classification'):
out_prob = out_prob.softmax(1)
outs.append(out... |
def expand_prior_precision(prior_prec, model):
theta = parameters_to_vector(model.parameters())
(device, P) = (theta.device, len(theta))
assert (prior_prec.ndim == 1)
if (len(prior_prec) == 1):
return (torch.ones(P, device=device) * prior_prec)
elif (len(prior_prec) == P):
return p... |
def prior_prec_to_tensor(args, prior_prec, model):
H = len(list(model.parameters()))
theta = parameters_to_vector(model.parameters())
(device, P) = (theta.device, len(theta))
if (args.prior_structure == 'scalar'):
log_prior_prec = torch.ones(1, device=device)
elif (args.prior_structure == ... |
def get_auroc(py_in, py_out):
(py_in, py_out) = (py_in.cpu().numpy(), py_out.cpu().numpy())
labels = np.zeros((len(py_in) + len(py_out)), dtype='int32')
labels[:len(py_in)] = 1
examples = np.concatenate([py_in.max(1), py_out.max(1)])
return roc_auc_score(labels, examples)
|
def get_fpr95(py_in, py_out):
(py_in, py_out) = (py_in.cpu().numpy(), py_out.cpu().numpy())
(conf_in, conf_out) = (py_in.max(1), py_out.max(1))
tpr = 95
perc = np.percentile(conf_in, (100 - tpr))
fp = np.sum((conf_out >= perc))
fpr = (np.sum((conf_out >= perc)) / len(conf_out))
return (fpr... |
def get_brier_score(probs, targets):
targets = F.one_hot(targets, num_classes=probs.shape[1])
return torch.mean(torch.sum(((probs - targets) ** 2), axis=1)).item()
|
def get_calib(pys, y_true, M=100):
(pys, y_true) = (pys.cpu().numpy(), y_true.cpu().numpy())
(_, bins) = np.histogram(pys, M, range=(0, 1))
labels = pys.argmax(1)
confs = np.max(pys, axis=1)
conf_idxs = np.digitize(confs, bins)
accs_bin = []
confs_bin = []
nitems_bin = []
for i in ... |
def get_calib_regression(pred_means, pred_stds, y_true, return_hist=False, M=10):
'\n Kuleshov et al. ICML 2018, eq. 9\n * pred_means, pred_stds, y_true must be np.array\'s\n * Set return_hist to True to also return the "histogram"---useful for visualization (see paper)\n '
T = len(y_true)
ps ... |
def get_sharpness(pred_stds):
'\n Kuleshov et al. ICML 2018, eq. 10\n\n pred_means be np.array\n '
return np.mean((pred_stds ** 2))
|
def timing(fun):
'\n Return the original output(s) and a wall-clock timing in second.\n '
if torch.cuda.is_available():
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
torch.cuda.synchronize()
start.record()
ret = fun()
... |
def save_results(args, metrics):
' Save the computed metrics '
if (args.run_name is None):
res_str = (f'_{args.subset_of_weights}_{args.hessian_structure}' if (args.method in ['laplace', 'mola']) else '')
temp_str = ('' if (args.temperature == 1.0) else f'_{args.temperature}')
method_s... |
def get_prior_precision(args, device):
' Obtain the prior precision parameter from the cmd arguments '
if (type(args.prior_precision) is str):
prior_precision = torch.load(args.prior_precision, map_location=device)
elif (type(args.prior_precision) is float):
prior_precision = args.prior_pr... |
class ProperDataLoader():
' This class defines an iterator that wraps a PyTorch DataLoader \n to only return the first two of three elements of the data tuples.\n\n This is used to make the data loaders from the WILDS benchmark\n (which return (X, y, metadata) tuples, where metadata for examp... |
def load_pretrained_wilds_model(dataset, model_dir, device, model_idx=0, model_seed=0):
' load pre-trained model '
config = get_default_config(dataset, algorithm=ALGORITHMS[model_idx])
is_featurizer = ((dataset in ['civilcomments', 'amazon']) and (ALGORITHMS[model_idx] == 'deepCORAL'))
model = initial... |
def get_wilds_loaders(dataset, data_dir, data_fraction=1.0, model_seed=0):
' load in-distribution datasets and return data loaders '
config = get_default_config(dataset, data_fraction=data_fraction)
dataset_kwargs = ({'fold': POVERTY_FOLDS[model_seed]} if (dataset == 'poverty') else {})
full_dataset =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.