code stringlengths 17 6.64M |
|---|
class JunctionTree():
' A JunctionTree is a transformation of a GraphicalModel into a tree structure. It is used\n to find the maximal cliques in the graphical model, and for specifying the message passing\n order for belief propagation. The JunctionTree is characterized by an elimination_order,\n... |
class LocalInference():
def __init__(self, domain, backend='numpy', structural_zeros={}, metric='L2', log=False, iters=1000, warm_start=False, marginal_oracle='convex', inner_iters=1):
'\n Class for learning a GraphicalModel from noisy measurements on a data distribution\n \n :param... |
def run(dataset, measurements, eps=1.0, delta=0.0, bounded=True, engine='MD', options={}, iters=10000, seed=None, metric='L2', elim_order=None, frequency=1, workload=None, oracle='exact'):
'\n Run a mechanism that measures the given measurements and runs inference.\n This is a convenience method for running... |
def estimate_total(measurements):
variances = np.array([])
estimates = np.array([])
for (Q, y, noise, proj) in measurements:
o = np.ones(Q.shape[1])
v = lsmr(Q.T, o, atol=0, btol=0)[0]
if np.allclose(Q.T.dot(v), o):
variances = np.append(variances, ((noise ** 2) * np.do... |
def adam(loss_and_grad, x0, iters=250):
a = 1.0
(b1, b2) = (0.9, 0.999)
eps = 1e-07
x = x0
m = np.zeros_like(x)
v = np.zeros_like(x)
for t in range(1, (iters + 1)):
(l, g) = loss_and_grad(x)
m = ((b1 * m) + ((1 - b1) * g))
v = ((b2 * v) + ((1 - b2) * (g ** 2)))
... |
def synthetic_col(counts, total):
counts *= (total / counts.sum())
(frac, integ) = np.modf(counts)
integ = integ.astype(int)
extra = (total - integ.sum())
if (extra > 0):
idx = np.random.choice(counts.size, extra, False, (frac / frac.sum()))
integ[idx] += 1
vals = np.repeat(np.... |
class MixtureOfProducts():
def __init__(self, products, domain, total):
self.products = products
self.domain = domain
self.total = total
self.num_components = next(iter(products.values())).shape[0]
def project(self, cols):
products = {col: self.products[col] for col i... |
class MixtureInference():
def __init__(self, domain, components=10, metric='L2', iters=2500, warm_start=False):
'\n :param domain: A Domain object\n :param components: The number of mixture components\n :metric: The metric to use for the loss function (can be callable)\n '
... |
def entropic_mirror_descent(loss_and_grad, x0, total, iters=250):
logP = ((np.log((x0 + np.nextafter(0, 1))) + np.log(total)) - np.log(x0.sum()))
P = np.exp(logP)
P = ((x0 * total) / x0.sum())
(loss, dL) = loss_and_grad(P)
alpha = 1.0
begun = False
for _ in range(iters):
logQ = (lo... |
def estimate_total(measurements):
variances = np.array([])
estimates = np.array([])
for (Q, y, noise, proj) in measurements:
o = np.ones(Q.shape[1])
v = lsmr(Q.T, o, atol=0, btol=0)[0]
if np.allclose(Q.T.dot(v), o):
variances = np.append(variances, ((noise ** 2) * np.do... |
class PublicInference():
def __init__(self, public_data, metric='L2'):
self.public_data = public_data
self.metric = metric
self.weights = np.ones(self.public_data.records)
def estimate(self, measurements, total=None):
if (total is None):
total = estimate_total(mea... |
class RegionGraph():
def __init__(self, domain, cliques, total=1.0, minimal=True, convex=True, iters=25, convergence=0.001, damping=0.5):
self.domain = domain
self.cliques = cliques
if (not convex):
self.cliques = []
for r in cliques:
if (not any(((... |
def estimate_kikuchi_marginal(domain, total, marginals):
marginals = dict(marginals)
regions = set(marginals.keys())
size = 0
while (len(regions) > size):
size = len(regions)
for (r1, r2) in itertools.combinations(regions, 2):
z = tuple(sorted((set(r1) & set(r2))))
... |
class Factor():
device = ('cuda' if torch.cuda.is_available() else 'cpu')
def __init__(self, domain, values):
' Initialize a factor over the given domain\n\n :param domain: the domain of the factor\n :param values: the ndarray or tensor of factor values (for each element of the domain)\... |
class TestDomain(unittest.TestCase):
def setUp(self):
attrs = ['a', 'b', 'c', 'd']
shape = [3, 4, 5, 6]
domain = Domain(attrs, shape)
self.data = Dataset.synthetic(domain, 100)
def test_project(self):
proj = self.data.project(['a', 'b'])
ans = Domain(['a', 'b'... |
class TestDomain(unittest.TestCase):
def setUp(self):
attrs = ['a', 'b', 'c', 'd']
shape = [10, 20, 30, 40]
self.domain = Domain(attrs, shape)
def test_eq(self):
attrs = ['a', 'b', 'c', 'd']
shape = [10, 20, 30, 40]
ans = Domain(attrs, shape)
self.asse... |
class TestFactor(unittest.TestCase):
def setUp(self):
attrs = ['a', 'b', 'c']
shape = [2, 3, 4]
domain = Domain(attrs, shape)
values = np.random.rand(*shape)
self.factor = Factor(domain, values)
def test_expand(self):
domain = Domain(['a', 'b', 'c', 'd'], [2, ... |
class TestGraphicalModel(unittest.TestCase):
def setUp(self):
attrs = ['a', 'b', 'c', 'd']
shape = [2, 3, 4, 5]
domain = Domain(attrs, shape)
cliques = [('a', 'b'), ('b', 'c'), ('c', 'd')]
self.model = GraphicalModel(domain, cliques)
zeros = {cl: Factor.zeros(domai... |
class TestInference(unittest.TestCase):
def setUp(self):
attrs = ['a', 'b', 'c', 'd', 'e']
shape = [2, 3, 4, 5, 6]
self.domain = Domain(attrs, shape)
self.measurements = []
for i in range(4):
I = np.eye(shape[i])
y = np.random.rand(shape[i])
... |
class TestJunctionTree(unittest.TestCase):
def setUp(self):
attrs = ['a', 'b', 'c', 'd']
shape = [10, 20, 30, 40]
domain = Domain(attrs, shape)
cliques = [('a', 'b'), ('b', 'c'), ('c', 'd')]
self.tree = JunctionTree(domain, cliques)
def test_maximal_cliques(self):
... |
class TestFactor(unittest.TestCase):
def setUp(self):
if skip:
raise unittest.SkipTest('PyTorch not installed')
attrs = ['a', 'b', 'c']
shape = [2, 3, 4]
domain = Domain(attrs, shape)
values = torch.rand(*shape)
self.factor = Factor(domain, values)
... |
class TestTorch(test_inference.TestInference):
def setUp(self):
if skip:
raise unittest.SkipTest('PyTorch not installed')
test_inference.TestInference.setUp(self)
self.engine = FactoredInference(self.domain, backend='torch', log=True)
|
class BasicBlock(nn.Module):
expansion = 1
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.Conv2... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_s... |
class ResNet(nn.Module):
def __init__(self, block, num_blocks, feature_dim=512):
super(ResNet, self).__init__()
self.in_planes = 64
self.feature_dim = feature_dim
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
... |
class ResNetControl(nn.Module):
def __init__(self, block, num_blocks, feature_dim=512):
super(ResNetControl, self).__init__()
self.in_planes = 64
self.feature_dim = feature_dim
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.Batc... |
def ResNet18(feature_dim=512):
return ResNet(BasicBlock, [2, 2, 2, 2], feature_dim)
|
def ResNet18Control(feature_dim=512):
return ResNetControl(BasicBlock, [2, 2, 2, 2], feature_dim)
|
class BasicBlock(nn.Module):
expansion = 1
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.Conv2... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_s... |
class ResNetMNIST(nn.Module):
def __init__(self, block, num_blocks, feature_dim=512):
super(ResNetMNIST, self).__init__()
self.in_planes = 64
self.feature_dim = feature_dim
self.conv1 = nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNor... |
def ResNet10MNIST(feature_dim=512):
return ResNetMNIST(BasicBlock, [1, 1, 1, 1], feature_dim)
|
class BasicBlock(nn.Module):
expansion = 1
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.Conv2... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_s... |
class ResNetSTL(nn.Module):
def __init__(self, block, num_blocks, feature_dim=512):
super(ResNetSTL, self).__init__()
self.in_planes = 32
self.feature_dim = feature_dim
self.conv1 = nn.Conv2d(3, 32, kernel_size=5, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(... |
def ResNet18STL(feature_dim=128):
return ResNetSTL(BasicBlock, [2, 2, 2, 2], feature_dim)
|
class Block(nn.Module):
'Grouped convolution block.'
expansion = 2
def __init__(self, in_planes, cardinality=32, bottleneck_width=4, stride=1):
super(Block, self).__init__()
group_width = (cardinality * bottleneck_width)
self.conv1 = nn.Conv2d(in_planes, group_width, kernel_size=1... |
class ResNeXt(nn.Module):
def __init__(self, num_blocks, cardinality, bottleneck_width, feature_dim=128):
super(ResNeXt, self).__init__()
self.cardinality = cardinality
self.bottleneck_width = bottleneck_width
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=1... |
def ResNeXt29_2x64d(feature_dim=128):
return ResNeXt(num_blocks=[3, 3, 3], cardinality=2, bottleneck_width=64, feature_dim=feature_dim)
|
def ResNeXt29_4x64d(feature_dim=128):
return ResNeXt(num_blocks=[3, 3, 3], cardinality=4, bottleneck_width=64, feature_dim=feature_dim)
|
def ResNeXt29_8x64d(feature_dim=128):
return ResNeXt(num_blocks=[3, 3, 3], cardinality=8, bottleneck_width=64, feature_dim=feature_dim)
|
def ResNeXt29_32x4d(feature_dim=128):
return ResNeXt(num_blocks=[3, 3, 3], cardinality=32, bottleneck_width=4, feature_dim=feature_dim)
|
class VGG(nn.Module):
def __init__(self, vgg_name='VGG11', feature_dim=128):
super(VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, 10)
self.reshape = torch.nn.Sequential(nn.Linear(512, 512, bias=False), nn.BatchNorm1d(512), n... |
def VGG11(feature_dim=128):
return VGG('VGG11', feature_dim=feature_dim)
|
class AugmentLoader():
"Dataloader that includes augmentation functionality.\n \n Parameters:\n dataset (torch.data.dataset): trainset or testset PyTorch object\n batch_size (int): the size of each batch, including augmentations\n sampler (str): choice of sampler ('balance' or 'random')... |
class _Iter():
def __init__(self, loader, sampler, num_img, num_aug, size=None):
self.loader = loader
self.sampler = sampler
self.num_img = num_img
self.num_aug = num_aug
self.size = size
def __next__(self):
if self.sampler.stop():
raise StopIterat... |
class BalanceSampler():
'Samples data such that each class has the same number of samples. Performs sampling \n by first sorting data then unfiormly sample from batch with replacement.'
def __init__(self, dataset):
self.dataset = dataset
self.size = len(self.dataset.targets)
self.n... |
class RandomSampler():
'Samples data randomly. Sampler initializes sample indices when Sampler is instantiated.\n Sample indices are shuffled if shuffle option is True. Performs sampling by popping off \n first index each time.'
def __init__(self, dataset, size, shuffle=False):
self.dataset = d... |
def svm(args, train_features, train_labels, test_features, test_labels):
svm = LinearSVC(verbose=0, random_state=10)
svm.fit(train_features, train_labels)
acc_train = svm.score(train_features, train_labels)
acc_test = svm.score(test_features, test_labels)
print('SVM: {}'.format(acc_test))
retu... |
def knn(args, train_features, train_labels, test_features, test_labels):
'Perform k-Nearest Neighbor classification using cosine similaristy as metric.\n\n Options:\n k (int): top k features for kNN\n \n '
sim_mat = (train_features @ test_features.T)
topk = sim_mat.topk(k=args.k, dim=0)
... |
def nearsub(args, train_features, train_labels, test_features, test_labels):
'Perform nearest subspace classification.\n \n Options:\n n_comp (int): number of components for PCA or SVD\n \n '
scores_pca = []
scores_svd = []
num_classes = (train_labels.numpy().max() + 1)
(feature... |
def kmeans(args, train_features, train_labels):
'Perform KMeans clustering. \n \n Options:\n n (int): number of clusters used in KMeans.\n\n '
return cluster.kmeans(args, train_features, train_labels)
|
def ensc(args, train_features, train_labels):
'Perform Elastic Net Subspace Clustering.\n \n Options:\n gam (float): gamma parameter in EnSC\n tau (float): tau parameter in EnSC\n\n '
return cluster.ensc(args, train_features, train_labels)
|
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, 'w:gz') as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
|
def gen_testloss(args):
params = utils.load_params(args.model_dir)
ckpt_dir = os.path.join(args.model_dir, 'checkpoints')
ckpt_paths = [int(e[11:(- 3)]) for e in os.listdir(ckpt_dir) if (e[(- 3):] == '.pt')]
ckpt_paths = np.sort(ckpt_paths)
headers = ['epoch', 'step', 'loss', 'discrimn_loss_e', 'c... |
def gen_training_accuracy(args):
params = utils.load_params(args.model_dir)
ckpt_dir = os.path.join(args.model_dir, 'checkpoints')
ckpt_paths = [int(e[11:(- 3)]) for e in os.listdir(ckpt_dir) if (e[(- 3):] == '.pt')]
ckpt_paths = np.sort(ckpt_paths)
headers = ['epoch', 'acc_train', 'acc_test']
... |
class MaximalCodingRateReduction(torch.nn.Module):
def __init__(self, gam1=1.0, gam2=1.0, eps=0.01):
super(MaximalCodingRateReduction, self).__init__()
self.gam1 = gam1
self.gam2 = gam2
self.eps = eps
def compute_discrimn_loss_empirical(self, W):
'Empirical Discrimina... |
def sort_dataset(data, labels, num_classes=10, stack=False):
'Sort dataset based on classes.\n \n Parameters:\n data (np.ndarray): data array\n labels (np.ndarray): one dimensional array of class labels\n num_classes (int): number of classes\n stack (bol): combine sorted data int... |
def init_pipeline(model_dir, headers=None):
'Initialize folder and .csv logger.'
os.makedirs(model_dir)
os.makedirs(os.path.join(model_dir, 'checkpoints'))
os.makedirs(os.path.join(model_dir, 'figures'))
os.makedirs(os.path.join(model_dir, 'plabels'))
if (headers is None):
headers = ['... |
def create_csv(model_dir, filename, headers):
'Create .csv file with filename in model_dir, with headers as the first line \n of the csv. '
csv_path = os.path.join(model_dir, filename)
if os.path.exists(csv_path):
os.remove(csv_path)
with open(csv_path, 'w+') as f:
f.write(','.join(... |
def save_params(model_dir, params):
'Save params to a .json file. Params is a dictionary of parameters.'
path = os.path.join(model_dir, 'params.json')
with open(path, 'w') as f:
json.dump(params, f, indent=2, sort_keys=True)
|
def update_params(model_dir, pretrain_dir):
'Updates architecture and feature dimension from pretrain directory \n to new directoy. '
params = load_params(model_dir)
old_params = load_params(pretrain_dir)
params['arch'] = old_params['arch']
params['fd'] = old_params['fd']
save_params(model_... |
def load_params(model_dir):
'Load params.json file in model directory and return dictionary.'
_path = os.path.join(model_dir, 'params.json')
with open(_path, 'r') as f:
_dict = json.load(f)
return _dict
|
def save_state(model_dir, *entries, filename='losses.csv'):
'Save entries to csv. Entries is list of numbers. '
csv_path = os.path.join(model_dir, filename)
assert os.path.exists(csv_path), 'CSV file is missing in project directory.'
with open(csv_path, 'a') as f:
f.write(('\n' + ','.join(map(... |
def save_ckpt(model_dir, net, epoch):
'Save PyTorch checkpoint to ./checkpoints/ directory in model directory. '
torch.save(net.state_dict(), os.path.join(model_dir, 'checkpoints', 'model-epoch{}.pt'.format(epoch)))
|
def save_labels(model_dir, labels, epoch):
'Save labels of a certain epoch to directory. '
path = os.path.join(model_dir, 'plabels', f'epoch{epoch}.npy')
np.save(path, labels)
|
def compute_accuracy(y_pred, y_true):
'Compute accuracy by counting correct classification. '
assert (y_pred.shape == y_true.shape)
return (1 - (np.count_nonzero((y_pred - y_true)) / y_true.size))
|
def clustering_accuracy(labels_true, labels_pred):
'Compute clustering accuracy.'
from sklearn.metrics.cluster import supervised
from scipy.optimize import linear_sum_assignment
(labels_true, labels_pred) = supervised.check_clusterings(labels_true, labels_pred)
value = supervised.contingency_matri... |
def svm(train_features, train_labels, test_features, test_labels):
svm = LinearSVC(verbose=0, random_state=10)
svm.fit(train_features, train_labels)
acc_train = svm.score(train_features, train_labels)
acc_test = svm.score(test_features, test_labels)
print('SVM: {}'.format(acc_test))
return (ac... |
def knn(train_features, train_labels, test_features, test_labels, k=5):
'Perform k-Nearest Neighbor classification using cosine similaristy as metric.\n Options:\n k (int): top k features for kNN\n \n '
sim_mat = (train_features @ test_features.T)
topk = torch.from_numpy(sim_mat).topk(k=k,... |
def nearsub(train_features, train_labels, test_features, test_labels, n_comp=10):
'Perform nearest subspace classification.\n \n Options:\n n_comp (int): number of components for PCA or SVD\n \n '
scores_svd = []
classes = np.unique(test_labels)
(features_sort, _) = utils.sort_datas... |
def nearsub_pca(train_features, train_labels, test_features, test_labels, n_comp=10):
'Perform nearest subspace classification.\n \n Options:\n n_comp (int): number of components for PCA or SVD\n \n '
scores_pca = []
classes = np.unique(test_labels)
(features_sort, _) = utils.sort_d... |
def compute_accuracy(y_pred, y_true):
'Compute accuracy by counting correct classification. '
assert (y_pred.shape == y_true.shape)
return (1 - (np.count_nonzero((y_pred - y_true)) / y_true.size))
|
def baseline(train_features, train_labels, test_features, test_labels):
test_models = {'log_l2': SGDClassifier(loss='log', max_iter=10000, random_state=42), 'SVM_linear': LinearSVC(max_iter=10000, random_state=42), 'SVM_RBF': SVC(kernel='rbf', random_state=42), 'DecisionTree': DecisionTreeClassifier(), 'RandomFor... |
class Architecture():
def __init__(self, blocks, model_dir, num_classes, batch_size=100):
self.blocks = blocks
self.model_dir = model_dir
self.num_classes = num_classes
self.batch_size = batch_size
def __call__(self, Z, y=None):
for (b, block) in enumerate(self.blocks... |
class Lift():
def __init__(self, kernels, stride=1, relu=True):
self.kernels = kernels
self.stride = stride
self.relu = relu
def load_arch(self, arch, block_id):
pass
def init(self, Z, y):
return self(Z)
def init_zero(self, Z):
return Z
def prep... |
class Lift1D(Lift):
def __init__(self, kernels, stride=1, relu=True):
assert (len(kernels.shape) == 3), 'kernel should have dimensions (out_channel, in_channel, kernel_size)'
super(Lift1D, self).__init__(kernels, stride, relu)
def __call__(self, Z, y=None, sgd=False):
ksize = self.ke... |
class Lift2D(Lift):
def __init__(self, kernels, stride=1, relu=True):
assert (len(kernels.shape) == 4), 'kernel should have dimensions (out_channel, in_channel, kernel_height, kernel_width)'
super(Lift2D, self).__init__(kernels, stride, relu)
def __call__(self, Z, y=None, sgd=False):
... |
def sort_dataset(data, labels, classes, stack=False):
'Sort dataset based on classes.\n \n Parameters:\n data (np.ndarray): data array\n labels (np.ndarray): one dimensional array of class labels\n classes (int): number of classes\n stack (bol): combine sorted data into one numpy... |
def save_params(model_dir, params, name='params.json'):
'Save params to a .json file. Params is a dictionary of parameters.'
path = os.path.join(model_dir, name)
with open(path, 'w') as f:
json.dump(params, f, indent=2, sort_keys=True)
|
def load_params(model_dir):
'Load params.json file in model directory and return dictionary.'
_path = os.path.join(model_dir, 'params.json')
with open(_path, 'r') as f:
_dict = json.load(f)
return _dict
|
def create_csv(model_dir, filename, headers):
'Create .csv file with filename in model_dir, with headers as the first line \n of the csv. '
csv_path = os.path.join(model_dir, filename)
if os.path.exists(csv_path):
os.remove(csv_path)
with open(csv_path, 'w+') as f:
f.write(','.join(... |
def save_loss(loss_dict, model_dir, name):
save_dir = os.path.join(model_dir, 'loss')
os.makedirs(save_dir, exist_ok=True)
file_path = os.path.join(save_dir, '{}.csv'.format(name))
pd.DataFrame(loss_dict).to_csv(file_path)
|
def save_features(model_dir, name, features, labels, layer=None):
save_dir = os.path.join(model_dir, 'features')
os.makedirs(save_dir, exist_ok=True)
np.save(os.path.join(save_dir, f'{name}_features.npy'), features)
np.save(os.path.join(save_dir, f'{name}_labels.npy'), labels)
|
def flatten(layers, num_classes):
net = ReduNet(*[Vector(eta=0.5, eps=0.1, lmbda=500, num_classes=num_classes, dimensions=784) for _ in range(layers)])
return net
|
def lift2d(channels, layers, num_classes, seed=0):
net = ReduNet(Lift2D(1, channels, 9, seed=seed), *[Fourier2D(eta=0.5, eps=0.1, lmbda=500, num_classes=num_classes, dimensions=(channels, 28, 28)) for _ in range(layers)])
return net
|
def mnist2d_10class(data_dir):
transform = transforms.Compose([transforms.ToTensor()])
trainset = datasets.MNIST(data_dir, train=True, transform=transform, download=True)
testset = datasets.MNIST(data_dir, train=False, transform=transform, download=True)
num_classes = 10
return (trainset, testset,... |
def mnist2d_5class(data_dir):
transform = transforms.Compose([transforms.ToTensor()])
trainset = datasets.MNIST(data_dir, train=True, transform=transform, download=True)
testset = datasets.MNIST(data_dir, train=False, transform=transform, download=True)
(trainset, num_classes) = filter_class(trainset,... |
def mnist2d_2class(data_dir):
transform = transforms.Compose([transforms.ToTensor()])
trainset = datasets.MNIST(data_dir, train=True, transform=transform, download=True)
testset = datasets.MNIST(data_dir, train=False, transform=transform, download=True)
(trainset, num_classes) = filter_class(trainset,... |
def mnistvector_10class(data_dir):
transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda((lambda x: x.flatten()))])
trainset = datasets.MNIST(data_dir, train=True, transform=transform, download=True)
testset = datasets.MNIST(data_dir, train=False, transform=transform, download=True)
... |
def mnistvector_5class(data_dir):
transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda((lambda x: x.flatten()))])
trainset = datasets.MNIST(data_dir, train=True, transform=transform, download=True)
testset = datasets.MNIST(data_dir, train=False, transform=transform, download=True)
... |
def mnistvector_2class(data_dir):
transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda((lambda x: x.flatten()))])
trainset = datasets.MNIST(data_dir, train=True, transform=transform, download=True)
testset = datasets.MNIST(data_dir, train=False, transform=transform, download=True)
... |
def filter_class(dataset, classes):
(data, labels) = (dataset.data, dataset.targets)
if (type(labels) == list):
labels = torch.tensor(labels)
data_filter = []
labels_filter = []
for _class in classes:
idx = (labels == _class)
data_filter.append(data[idx])
labels_fil... |
def load_architecture(data, arch, seed=0):
if (data == 'mnist2d'):
if (arch == 'lift2d_channels35_layers5'):
from architectures.mnist.lift2d import lift2d
return lift2d(channels=35, layers=5, num_classes=10, seed=seed)
if (arch == 'lift2d_channels35_layers10'):
... |
def load_dataset(choice, data_dir='./data/'):
if (choice == 'mnist2d'):
from datasets.mnist import mnist2d_10class
return mnist2d_10class(data_dir)
if (choice == 'mnist2d_2class'):
from datasets.mnist import mnist2d_2class
return mnist2d_2class(data_dir)
if (choice == 'mnis... |
def plot_loss_mcr(model_dir, name):
file_dir = os.path.join(model_dir, 'loss', f'{name}.csv')
data = pd.read_csv(file_dir)
loss_total = data['loss_total'].ravel()
loss_expd = data['loss_expd'].ravel()
loss_comp = data['loss_comp'].ravel()
num_iter = np.arange(len(loss_total))
(fig, ax) = p... |
def plot_loss(model_dir):
'Plot cross entropy loss. '
file_dir = os.path.join(model_dir, 'losses.csv')
data = pd.read_csv(file_dir)
epochs = data['epoch'].ravel()
loss = data['loss'].ravel()
(fig, ax) = plt.subplots(1, 1, figsize=(7, 5), sharey=True, sharex=True, dpi=400)
ax.plot(epochs, l... |
def plot_csv(model_dir, filename):
df = pd.read_csv(os.path.join(model_dir, f'{filename}.csv'))
colnames = df.columns
(fig, ax) = plt.subplots(1, 1, figsize=(7, 5))
for colname in colnames[1:]:
ax.plot(df[colnames[0]], df[colname], marker='x', label=colname)
ax.set_xlabel(colnames[0])
... |
def plot_loss_ce(model_dir, filename='loss_ce'):
df = pd.read_csv(os.path.join(model_dir, f'{filename}.csv'))
colnames = df.columns
(fig, ax) = plt.subplots(1, 1, figsize=(7, 5))
for colname in colnames[1:]:
ax.plot(np.arange(df.shape[0]), df['loss_ce'], label=colname)
ax.set_xlabel(colnam... |
def plot_acc(model_dir):
'Plot training and testing accuracy'
file_dir = os.path.join(model_dir, 'acc.csv')
data = pd.read_csv(file_dir)
epochs = data['epoch'].ravel()
acc_train = data['acc_train'].ravel()
acc_test = data['acc_test'].ravel()
(fig, ax) = plt.subplots(1, 1, figsize=(7, 5), s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.