code stringlengths 17 6.64M |
|---|
class Machine():
def __init__(self, max_features=20000, maxlen=80):
self.data = Data(max_features, maxlen)
self.model = RNN_LSTM(max_features, maxlen)
def run(self, epochs=3, batch_size=32):
data = self.data
model = self.model
print('Training stage')
print('==... |
def main():
m = Machine()
m.run()
|
class AE(models.Model):
def __init__(self, x_nodes=784, z_dim=36):
x_shape = (x_nodes,)
x = layers.Input(shape=x_shape)
z = layers.Dense(z_dim, activation='relu')(x)
y = layers.Dense(x_nodes, activation='sigmoid')(z)
super().__init__(x, y)
self.x = x
self.z... |
def show_ae(autoencoder):
encoder = autoencoder.Encoder()
decoder = autoencoder.Decoder()
encoded_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
n = 10
plt.figure(figsize=(20, 6))
for i in range(n):
ax = plt.subplot(3, n, (i + 1))
plt.imshow(x_t... |
def main():
x_nodes = 784
z_dim = 36
autoencoder = AE(x_nodes, z_dim)
history = autoencoder.fit(x_train, x_train, epochs=10, batch_size=256, shuffle=True, validation_data=(x_test, x_test))
plot_acc(history)
plt.show()
plot_loss(history)
plt.show()
show_ae(autoencoder)
plt.show(... |
def Conv2D(filters, kernel_size, padding='same', activation='relu'):
return layers.Conv2D(filters, kernel_size, padding=padding, activation=activation)
|
class AE(models.Model):
def __init__(self, org_shape=(1, 28, 28)):
original = layers.Input(shape=org_shape)
x = Conv2D(4, (3, 3))(original)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3))(x)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
... |
def show_ae(autoencoder, data):
x_test = data.x_test
decoded_imgs = autoencoder.predict(x_test)
print(decoded_imgs.shape, data.x_test.shape)
if (backend.image_data_format() == 'channels_first'):
(N, n_ch, n_i, n_j) = x_test.shape
else:
(N, n_i, n_j, n_ch) = x_test.shape
x_test ... |
def main(epochs=20, batch_size=128):
data = DATA()
autoencoder = AE(data.input_shape)
history = autoencoder.fit(data.x_train, data.x_train, epochs=epochs, batch_size=batch_size, shuffle=True, validation_split=0.2)
plot_acc(history)
plt.show()
plot_loss(history)
plt.show()
show_ae(autoe... |
def add_decorate(x):
'\n axis = -1 --> last dimension in an array\n '
m = K.mean(x, axis=(- 1), keepdims=True)
d = K.square((x - m))
return K.concatenate([x, d], axis=(- 1))
|
def add_decorate_shape(input_shape):
shape = list(input_shape)
assert (len(shape) == 2)
shape[1] *= 2
return tuple(shape)
|
def model_compile(model):
return model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
|
class GAN():
def __init__(self, ni_D, nh_D, nh_G):
self.ni_D = ni_D
self.nh_D = nh_D
self.nh_G = nh_G
self.D = self.gen_D()
self.G = self.gen_G()
self.GD = self.make_GD()
def gen_D(self):
ni_D = self.ni_D
nh_D = self.nh_D
D = models.Seq... |
class Data():
def __init__(self, mu, sigma, ni_D):
self.real_sample = (lambda n_batch: np.random.normal(mu, sigma, (n_batch, ni_D)))
self.in_sample = (lambda n_batch: np.random.rand(n_batch, ni_D))
|
class Machine():
def __init__(self, n_batch=10, ni_D=100):
data_mean = 4
data_stddev = 1.25
self.n_iter_D = 1
self.n_iter_G = 5
self.data = Data(data_mean, data_stddev, ni_D)
self.gan = GAN(ni_D=ni_D, nh_D=50, nh_G=50)
self.n_batch = n_batch
def train_... |
class GAN_Pure(GAN):
def __init__(self, ni_D, nh_D, nh_G):
'\n Discriminator input is not added\n '
super().__init__(ni_D, nh_D, nh_G)
def gen_D(self):
ni_D = self.ni_D
nh_D = self.nh_D
D = models.Sequential()
D.add(Dense(nh_D, activation='relu',... |
class Machine_Pure(Machine):
def __init__(self, n_batch=10, ni_D=100):
data_mean = 4
data_stddev = 1.25
self.data = Data(data_mean, data_stddev, ni_D)
self.gan = GAN_Pure(ni_D=ni_D, nh_D=50, nh_G=50)
self.n_batch = n_batch
|
def main():
machine = Machine(n_batch=1, ni_D=100)
machine.run(n_repeat=200, n_show=200, n_test=100)
|
def Conv2D(filters, kernel_size, padding='same', activation='relu'):
return layers.Conv2D(filters, kernel_size, padding=padding, activation=activation)
|
class AE(models.Model):
def __init__(self, org_shape=(1, 28, 28)):
original = layers.Input(shape=org_shape)
x = Conv2D(4, (3, 3))(original)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3))(x)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
... |
class DATA():
def __init__(self):
num_classes = 10
((x_train, y_train), (x_test, y_test)) = datasets.mnist.load_data()
(img_rows, img_cols) = x_train.shape[1:]
if (backend.image_data_format() == 'channels_first'):
x_train = x_train.reshape(x_train.shape[0], 1, img_rows... |
def plot_loss(history):
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
|
class ANN(models.Model):
def __init__(self, Nin, Nh, Nout):
hidden = layers.Dense(Nh)
output = layers.Dense(Nout)
relu = layers.Activation('relu')
x = layers.Input(shape=(Nin,))
h = relu(hidden(x))
y = output(h)
super().__init__(x, y)
self.compile(l... |
def Data_func():
((X_train, y_train), (X_test, y_test)) = datasets.boston_housing.load_data()
scaler = preprocessing.MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
return ((X_train, y_train), (X_test, y_test))
|
def main():
Nin = 13
Nh = 5
Nout = 1
model = ANN(Nin, Nh, Nout)
((X_train, y_train), (X_test, y_test)) = Data_func()
history = model.fit(X_train, y_train, epochs=100, batch_size=100, validation_split=0.2, verbose=2)
performace_test = model.evaluate(X_test, y_test, batch_size=100)
print... |
def ANN_models_func(Nin, Nh, Nout):
x = layers.Input(shape=(Nin,))
h = layers.Activation('relu')(layers.Dense(Nh)(x))
y = layers.Activation('softmax')(layers.Dense(Nout)(h))
model = models.Model(x, y)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return... |
def ANN_seq_func(Nin, Nh, Nout):
model = models.Sequential()
model.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,)))
model.add(layers.Dense(Nout, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
|
class ANN_models_class(models.Model):
def __init__(self, Nin, Nh, Nout):
hidden = layers.Dense(Nh)
output = layers.Dense(Nout)
relu = layers.Activation('relu')
softmax = layers.Activation('softmax')
x = layers.Input(shape=(Nin,))
h = relu(hidden(x))
y = sof... |
class ANN_seq_class(models.Sequential):
def __init__(self, Nin, Nh, Nout):
super().__init__()
self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,)))
self.add(layers.Dense(Nout, activation='softmax'))
self.compile(loss='categorical_crossentropy', optimizer='adam', metric... |
def Data_func():
((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data()
Y_train = np_utils.to_categorical(y_train)
Y_test = np_utils.to_categorical(y_test)
(L, W, H) = X_train.shape
X_train = X_train.reshape((- 1), (W * H))
X_test = X_test.reshape((- 1), (W * H))
X_train = (X_... |
def plot_loss(history):
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc=0)
|
def plot_acc(history):
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc=0)
|
def main():
Nin = 784
Nh = 100
number_of_class = 10
Nout = number_of_class
model = ANN_seq_class(Nin, Nh, Nout)
((X_train, Y_train), (X_test, Y_test)) = Data_func()
history = model.fit(X_train, Y_train, epochs=15, batch_size=100, validation_split=0.2)
performace_test = model.evaluate(X... |
def plot_acc(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['accuracy'])
plt.plot(history['val_accuracy'])
if (title is not None):
plt.title(title)
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Veri... |
def plot_loss(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['loss'])
plt.plot(history['val_loss'])
if (title is not None):
plt.title(title)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Verification'],... |
class History():
def __init__(self):
self.history = {'accuracy': [], 'loss': [], 'val_accuracy': [], 'val_loss': []}
|
class Metrics_Mean():
def __init__(self):
self.reset_states()
def __call__(self, loss):
self.buff.append(loss.data)
def reset_states(self):
self.buff = []
def result(self):
return np.mean(self.buff)
|
class Metrics_CategoricalAccuracy():
def __init__(self):
self.reset_states()
def __call__(self, labels, predictions):
decisions = predictions.data.max(1)[1]
self.correct += decisions.eq(labels.data).cpu().sum()
self.L += len(labels.data)
def reset_states(self):
(... |
class ANN_models_class(nn.Module):
def __init__(self, Nin, Nh, Nout):
super().__init__()
self.hidden = nn.Linear(Nin, Nh)
self.last = nn.Linear(Nh, Nout)
self.Nin = Nin
def forward(self, x):
x = x.view((- 1), self.Nin)
h = F.relu(self.hidden(x))
y = F.... |
def Data_func():
train_dataset = datasets.MNIST('~/pytorch_data', train=True, download=True, transform=transforms.ToTensor())
test_dataset = datasets.MNIST('~/pytorch_data', train=False, transform=transforms.ToTensor())
train_ds = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, s... |
def ANN_models_func(Nin, Nh, Nout):
x = layers.Input(shape=(Nin,))
h = layers.Activation('relu')(layers.Dense(Nh)(x))
y = layers.Activation('softmax')(layers.Dense(Nout)(h))
model = models.Model(x, y)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return... |
def ANN_seq_func(Nin, Nh, Nout):
model = models.Sequential()
model.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,)))
model.add(layers.Dense(Nout, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
|
class ANN_models_class(models.Model):
def __init__(self, Nin, Nh, Nout):
hidden = layers.Dense(Nh)
output = layers.Dense(Nout)
relu = layers.Activation('relu')
softmax = layers.Activation('softmax')
x = layers.Input(shape=(Nin,))
h = relu(hidden(x))
y = sof... |
class ANN_seq_class(models.Sequential):
def __init__(self, Nin, Nh, Nout):
super().__init__()
self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,)))
self.add(layers.Dense(Nout, activation='softmax'))
self.compile(loss='categorical_crossentropy', optimizer='adam', metric... |
def Data_func():
((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data()
Y_train = utils.to_categorical(y_train)
Y_test = utils.to_categorical(y_test)
(L, W, H) = X_train.shape
X_train = X_train.reshape((- 1), (W * H))
X_test = X_test.reshape((- 1), (W * H))
X_train = (X_train ... |
def plot_acc(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['acc'])
plt.plot(history['val_acc'])
if (title is not None):
plt.title(title)
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Verification']... |
def plot_loss(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['loss'])
plt.plot(history['val_loss'])
if (title is not None):
plt.title(title)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Verification'],... |
def main():
Nin = 784
Nh = 100
number_of_class = 10
Nout = number_of_class
model = ANN_seq_class(Nin, Nh, Nout)
((X_train, Y_train), (X_test, Y_test)) = Data_func()
history = model.fit(X_train, Y_train, epochs=15, batch_size=100, validation_split=0.2)
performace_test = model.evaluate(X... |
def ANN_models_func(Nin, Nh, Nout):
x = layers.Input(shape=(Nin,))
h = layers.Activation('relu')(layers.Dense(Nh)(x))
y = layers.Activation('softmax')(layers.Dense(Nout)(h))
model = models.Model(x, y)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return... |
def ANN_seq_func(Nin, Nh, Nout):
model = models.Sequential()
model.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,)))
model.add(layers.Dense(Nout, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
|
class ANN_models_class(models.Model):
def __init__(self, Nin, Nh, Nout):
hidden = layers.Dense(Nh)
output = layers.Dense(Nout)
relu = layers.Activation('relu')
softmax = layers.Activation('softmax')
x = layers.Input(shape=(Nin,))
h = relu(hidden(x))
y = sof... |
class ANN_seq_class(models.Sequential):
def __init__(self, Nin, Nh, Nout):
super().__init__()
self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,)))
self.add(layers.Dense(Nout, activation='softmax'))
self.compile(loss='categorical_crossentropy', optimizer='adam', metric... |
def Data_func():
((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data()
Y_train = utils.to_categorical(y_train)
Y_test = utils.to_categorical(y_test)
(L, W, H) = X_train.shape
X_train = X_train.reshape((- 1), (W * H))
X_test = X_test.reshape((- 1), (W * H))
X_train = (X_train ... |
def plot_acc(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['accuracy'])
plt.plot(history['val_accuracy'])
if (title is not None):
plt.title(title)
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Veri... |
def plot_loss(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['loss'])
plt.plot(history['val_loss'])
if (title is not None):
plt.title(title)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Verification'],... |
class ANN_models_class(models.Model):
def __init__(self, Nin, Nh, Nout):
super().__init__()
self.hidden = layers.Dense(Nh)
self.last = layers.Dense(Nout)
def call(self, x):
relu = layers.Activation('relu')
softmax = layers.Activation('softmax')
h = relu(self.h... |
def Data_func():
((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data()
Y_train = utils.to_categorical(y_train)
Y_test = utils.to_categorical(y_test)
(L, W, H) = X_train.shape
X_train = X_train.reshape((- 1), (W * H))
X_test = X_test.reshape((- 1), (W * H))
X_train = (X_train ... |
def plot_acc(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['accuracy'])
plt.plot(history['val_accuracy'])
if (title is not None):
plt.title(title)
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Veri... |
def plot_loss(history, title=None):
if (not isinstance(history, dict)):
history = history.history
plt.plot(history['loss'])
plt.plot(history['val_loss'])
if (title is not None):
plt.title(title)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Verification'],... |
class History():
def __init__(self):
self.history = {'accuracy': [], 'loss': [], 'val_accuracy': [], 'val_loss': []}
|
class _ANN_models_class(models.Model):
def __init__(self, Nin, Nh, Nout):
hidden = layers.Dense(Nh)
output = layers.Dense(Nout)
relu = layers.Activation('relu')
softmax = layers.Activation('softmax')
x = layers.Input(shape=(Nin,))
h = relu(hidden(x))
y = so... |
@tf2.function
def ep_train(xx, yy):
with tf2.GradientTape() as tape:
yp = model(xx)
loss = Loss_object(yy, yp)
gradients = tape.gradient(loss, model.trainable_variables)
Optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
train_accuracy(yy, yp)
|
@tf2.function
def ep_test(xx, yy):
yp = model(xx)
t_loss = Loss_object(yy, yp)
test_loss(t_loss)
test_accuracy(yy, yp)
|
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.conv1... |
@tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
predictions = model(images)
loss = loss_object(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(lo... |
@tf.function
def test_step(images, labels):
predictions = model(images)
t_loss = loss_object(labels, predictions)
test_loss(t_loss)
test_accuracy(labels, predictions)
|
class MultiHeadAttn(nn.Module):
def __init__(self, dim_q, dim_k, dim_v, dim_out, num_heads=8):
super().__init__()
self.num_heads = num_heads
self.dim_out = dim_out
self.fc_q = nn.Linear(dim_q, dim_out, bias=False)
self.fc_k = nn.Linear(dim_k, dim_out, bias=False)
s... |
class SelfAttn(MultiHeadAttn):
def __init__(self, dim_in, dim_out, num_heads=8):
super().__init__(dim_in, dim_in, dim_in, dim_out, num_heads)
def forward(self, x, mask=None):
return super().forward(x, x, x, mask=mask)
|
def build_mlp(dim_in, dim_hid, dim_out, depth):
modules = [nn.Linear(dim_in, dim_hid), nn.ReLU(True)]
for _ in range((depth - 2)):
modules.append(nn.Linear(dim_hid, dim_hid))
modules.append(nn.ReLU(True))
modules.append(nn.Linear(dim_hid, dim_out))
return nn.Sequential(*modules)
|
class PoolingEncoder(nn.Module):
def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=False, pre_depth=4, post_depth=2):
super().__init__()
self.use_lat = (dim_lat is not None)
self.net_pre = (build_mlp((dim_x + dim_y), dim_hid, dim_hid, pre_depth) if (not self_attn) ... |
class CrossAttnEncoder(nn.Module):
def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=True, v_depth=4, qk_depth=2):
super().__init__()
self.use_lat = (dim_lat is not None)
if (not self_attn):
self.net_v = build_mlp((dim_x + dim_y), dim_hid, dim_hid, v_de... |
class Decoder(nn.Module):
def __init__(self, dim_x=1, dim_y=1, dim_enc=128, dim_hid=128, depth=3):
super().__init__()
self.fc = nn.Linear((dim_x + dim_enc), dim_hid)
self.dim_hid = dim_hid
modules = [nn.ReLU(True)]
for _ in range((depth - 2)):
modules.append(nn... |
def get_logger(filename, mode='a'):
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger()
logger.addHandler(logging.FileHandler(filename, mode=mode))
return logger
|
class RunningAverage(object):
def __init__(self, *keys):
self.sum = OrderedDict()
self.cnt = OrderedDict()
self.clock = time.time()
for key in keys:
self.sum[key] = 0
self.cnt[key] = 0
def update(self, key, val):
if isinstance(val, torch.Tensor... |
def gen_load_func(parser, func):
def load(args, cmdline):
(sub_args, cmdline) = parser.parse_known_args(cmdline)
for (k, v) in sub_args.__dict__.items():
args.__dict__[k] = v
return (func(**sub_args.__dict__), cmdline)
return load
|
def load_module(filename):
module_name = os.path.splitext(os.path.basename(filename))[0]
return SourceFileLoader(module_name, filename).load_module()
|
def logmeanexp(x, dim=0):
return (x.logsumexp(dim) - math.log(x.shape[dim]))
|
def stack(x, num_samples=None, dim=0):
return (x if (num_samples is None) else torch.stack(([x] * num_samples), dim=dim))
|
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--mode', choices=['train', 'eval', 'plot', 'ensemble'], default='train')
parser.add_argument('--expid', type=str, default='trial')
parser.add_argument('--resume', action='store_true', default=False)
parser.add_argument('--gpu', ty... |
def train(args, model):
if (not osp.isdir(args.root)):
os.makedirs(args.root)
with open(osp.join(args.root, 'args.yaml'), 'w') as f:
yaml.dump(args.__dict__, f)
train_ds = CelebA(train=True)
eval_ds = CelebA(train=False)
train_loader = torch.utils.data.DataLoader(train_ds, batch_si... |
def gen_evalset(args):
torch.manual_seed(args.eval_seed)
torch.cuda.manual_seed(args.eval_seed)
eval_ds = CelebA(train=False)
eval_loader = torch.utils.data.DataLoader(eval_ds, batch_size=args.eval_batch_size, shuffle=False, num_workers=4)
batches = []
for (x, _) in tqdm(eval_loader):
... |
def eval(args, model):
if (args.mode == 'eval'):
ckpt = torch.load(osp.join(args.root, 'ckpt.tar'))
model.load_state_dict(ckpt.model)
if (args.eval_logfile is None):
eval_logfile = f'eval'
if (args.t_noise is not None):
eval_logfile += f'_{args.t_noi... |
def ensemble(args, model):
num_runs = 5
models = []
for i in range(num_runs):
model_ = deepcopy(model)
ckpt = torch.load(osp.join(results_path, 'celeba', args.model, f'run{(i + 1)}', 'ckpt.tar'))
model_.load_state_dict(ckpt['model'])
model_.cuda()
model_.eval()
... |
class CelebA(object):
def __init__(self, train=True):
(self.data, self.targets) = torch.load(osp.join(datasets_path, 'celeba', ('train.pt' if train else 'eval.pt')))
self.data = (self.data.float() / 255.0)
if train:
(self.data, self.targets) = (self.data, self.targets)
... |
class EMNIST(tvds.EMNIST):
def __init__(self, train=True, class_range=[0, 47], device='cpu', download=True):
super().__init__(datasets_path, train=train, split='balanced', download=download)
self.data = self.data.unsqueeze(1).float().div(255).transpose((- 1), (- 2)).to(device)
self.target... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--mode', choices=['train', 'eval', 'plot', 'ensemble'], default='train')
parser.add_argument('--expid', type=str, default='trial')
parser.add_argument('--resume', action='store_true', default=False)
parser.add_argument('--gpu', ty... |
def train(args, model):
if (not osp.isdir(args.root)):
os.makedirs(args.root)
with open(osp.join(args.root, 'args.yaml'), 'w') as f:
yaml.dump(args.__dict__, f)
train_ds = EMNIST(train=True, class_range=args.class_range)
eval_ds = EMNIST(train=False, class_range=args.class_range)
t... |
def gen_evalset(args):
torch.manual_seed(args.eval_seed)
torch.cuda.manual_seed(args.eval_seed)
eval_ds = EMNIST(train=False, class_range=args.class_range)
eval_loader = torch.utils.data.DataLoader(eval_ds, batch_size=args.eval_batch_size, shuffle=False, num_workers=4)
batches = []
for (x, _) ... |
def eval(args, model):
if (args.mode == 'eval'):
ckpt = torch.load(osp.join(args.root, 'ckpt.tar'))
model.load_state_dict(ckpt.model)
if (args.eval_logfile is None):
(c1, c2) = args.class_range
eval_logfile = f'eval_{c1}-{c2}'
if (args.t_noise is not Non... |
def ensemble(args, model):
num_runs = 5
models = []
for i in range(num_runs):
model_ = deepcopy(model)
ckpt = torch.load(osp.join(results_path, 'emnist', args.model, f'run{(i + 1)}', 'ckpt.tar'))
model_.load_state_dict(ckpt['model'])
model_.cuda()
model_.eval()
... |
class MultiHeadAttn(nn.Module):
def __init__(self, dim_q, dim_k, dim_v, dim_out, num_heads=8):
super().__init__()
self.num_heads = num_heads
self.dim_out = dim_out
self.fc_q = nn.Linear(dim_q, dim_out, bias=False)
self.fc_k = nn.Linear(dim_k, dim_out, bias=False)
s... |
class SelfAttn(MultiHeadAttn):
def __init__(self, dim_in, dim_out, num_heads=8):
super().__init__(dim_in, dim_in, dim_in, dim_out, num_heads)
def forward(self, x, mask=None):
return super().forward(x, x, x, mask=mask)
|
def build_mlp(dim_in, dim_hid, dim_out, depth):
modules = [nn.Linear(dim_in, dim_hid), nn.ReLU(True)]
for _ in range((depth - 2)):
modules.append(nn.Linear(dim_hid, dim_hid))
modules.append(nn.ReLU(True))
modules.append(nn.Linear(dim_hid, dim_out))
return nn.Sequential(*modules)
|
class PoolingEncoder(nn.Module):
def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=False, pre_depth=4, post_depth=2):
super().__init__()
self.use_lat = (dim_lat is not None)
self.net_pre = (build_mlp((dim_x + dim_y), dim_hid, dim_hid, pre_depth) if (not self_attn) ... |
class CrossAttnEncoder(nn.Module):
def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=True, v_depth=4, qk_depth=2):
super().__init__()
self.use_lat = (dim_lat is not None)
if (not self_attn):
self.net_v = build_mlp((dim_x + dim_y), dim_hid, dim_hid, v_de... |
class Decoder(nn.Module):
def __init__(self, dim_x=1, dim_y=1, dim_enc=128, dim_hid=128, depth=3):
super().__init__()
self.fc = nn.Linear((dim_x + dim_enc), dim_hid)
self.dim_hid = dim_hid
modules = [nn.ReLU(True)]
for _ in range((depth - 2)):
modules.append(nn... |
def get_logger(filename, mode='a'):
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger()
logger.addHandler(logging.FileHandler(filename, mode=mode))
return logger
|
class RunningAverage(object):
def __init__(self, *keys):
self.sum = OrderedDict()
self.cnt = OrderedDict()
self.clock = time.time()
for key in keys:
self.sum[key] = 0
self.cnt[key] = 0
def update(self, key, val):
if isinstance(val, torch.Tensor... |
def gen_load_func(parser, func):
def load(args, cmdline):
(sub_args, cmdline) = parser.parse_known_args(cmdline)
for (k, v) in sub_args.__dict__.items():
args.__dict__[k] = v
return (func(**sub_args.__dict__), cmdline)
return load
|
def load_module(filename):
module_name = os.path.splitext(os.path.basename(filename))[0]
return SourceFileLoader(module_name, filename).load_module()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.