code stringlengths 17 6.64M |
|---|
class Trainer(object):
'This class implemetns the training and validation functionality for training ML model for medical imaging'
def __init__(self, opts):
super(Trainer, self).__init__()
self.opts = opts
self.best_acc = 0
self.start_epoch = 0
self.max_bsz_cnn_gpu0 = ... |
def build_criteria(opts, class_weights):
'\n Build the criterian function\n :param opts: arguments\n :return: Loss function\n '
criteria = None
if (opts.loss_fn == 'ce'):
if opts.label_smoothing:
from criterions.cross_entropy import CrossEntropyWithLabelSmoothing
... |
def get_criteria_opts(parser):
'Loss function details'
group = parser.add_argument_group('Criteria options')
group.add_argument('--loss-fn', default='ce', choices=supported_loss_fns, help='Loss function')
group.add_argument('--label-smoothing', action='store_true', default=False, help='Smooth labels o... |
def get_data_loader(opts):
'\n Create data loaders\n :param opts: arguments\n :param base_feature_extractor: base feature extractor that transforms RGB words to vectors\n :return: train and validation dataloaders along with number of diagnostic classes\n '
(train_loader, val_loader, diag_classe... |
def get_test_data_loader(opts):
'\n Creates a data loader for test images\n :param opts: Arguments\n :param base_feature_extractor: base feature extractor that transforms RGB words to vectors\n :return: test dataloader along with number of diagnostic classes\n '
test_loader = None
diag_clas... |
def get_dataset_opts(parser):
'\n Medical imaging Dataset details\n '
group = parser.add_argument_group('Dataset general details')
group.add_argument('--img-dir', type=str, default='./data', required=True, help='Dataset location')
group.add_argument('--img-extn', type=str, default='tiff', he... |
def build_model(opts, diag_classes, base_feature_odim):
'\n This function is to load the Medical Imaging Model\n\n :param opts: Arguments\n :param diag_classes: Number of diagnostic classes\n :param base_feature_odim: Output dimension of base feature extractor such as CNN\n :return:\n '
mi_m... |
def get_model_opts(parser):
'Model details'
group = parser.add_argument_group('Medical Imaging Model Details')
group.add_argument('--out-features', type=int, default=128, help='Number of output features after merging bags and words')
group.add_argument('--checkpoint', type=str, default='', help='Check... |
def build_optimizer(opts, model):
'\n Creates the optimizer\n :param opts: Arguments\n :param model: Medical imaging model.\n :return: Optimizer\n '
optimizer = None
params = [p for p in model.parameters() if p.requires_grad]
if (opts.optim == 'sgd'):
print_info_message('Using S... |
def update_optimizer(optimizer, lr_value):
'\n Update the Learning rate in optimizer\n :param optimizer: Optimizer\n :param lr_value: Learning rate value to be used\n :return: Updated Optimizer\n '
optimizer.param_groups[0]['lr'] = lr_value
return optimizer
|
def read_lr_from_optimzier(optimizer):
'\n Utility to read the current LR value of an optimizer\n :param optimizer: Optimizer\n :return: learning rate\n '
return optimizer.param_groups[0]['lr']
|
def get_optimizer_opts(parser):
'Loss function details'
group = parser.add_argument_group('Optimizer options')
group.add_argument('--optim', default='sgd', type=str, choices=supported_optimziers, help='Optimizer')
group.add_argument('--adam-beta1', default=0.9, type=float, help='Beta1 for ADAM')
g... |
class ColorEncoder(object):
def __init__(self):
super(ColorEncoder, self).__init__()
def get_colors(self, dataset_name):
if (dataset_name == 'bbwsi'):
class_colors = [((228 / 255.0), (26 / 255.0), (28 / 255.0)), ((55 / 255.0), (126 / 255.0), (184 / 255.0)), ((77 / 255.0), (175 / ... |
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return sup... |
class CyclicLR(object):
'\n CLass that defines cyclic learning rate with warm restarts that decays the learning rate linearly till the end of cycle and then restarts\n at the maximum value.\n See https://arxiv.org/abs/1811.11431 for more details\n '
def __init__(self, min_lr=0.1, cycle_len=5, ste... |
class MultiStepLR(object):
'\n Fixed LR scheduler with steps\n '
def __init__(self, base_lr=0.1, steps=[30, 60, 90], gamma=0.1, step=True):
super(MultiStepLR, self).__init__()
assert (len(steps) >= 1), 'Please specify step intervals.'
self.base_lr = base_lr
self.step... |
class PolyLR(object):
'\n Polynomial LR scheduler with steps\n '
def __init__(self, base_lr, max_epochs, power=0.99):
super(PolyLR, self).__init__()
assert (0 < power < 1)
self.base_lr = base_lr
self.power = power
self.max_epochs = max_epochs
def step(se... |
class LinearLR(object):
def __init__(self, base_lr, max_epochs):
super(LinearLR, self).__init__()
self.base_lr = base_lr
self.max_epochs = max_epochs
def step(self, epoch):
curr_lr = (self.base_lr - (self.base_lr * (epoch / self.max_epochs)))
return round(curr_lr, 6)
... |
class HybirdLR(object):
def __init__(self, base_lr, clr_max, max_epochs, cycle_len=5):
super(HybirdLR, self).__init__()
self.linear_epochs = ((max_epochs - clr_max) + 1)
steps = [clr_max]
self.clr = CyclicLR(min_lr=base_lr, cycle_len=cycle_len, steps=steps, gamma=1)
self.d... |
class CosineLR(object):
def __init__(self, base_lr, max_epochs):
super(CosineLR, self).__init__()
self.base_lr = base_lr
self.max_epochs = max_epochs
def step(self, epoch):
return round(((self.base_lr * (1 + math.cos(((math.pi * epoch) / self.max_epochs)))) / 2), 6)
def ... |
class FixedLR(object):
def __init__(self, base_lr):
self.base_lr = base_lr
def step(self, epoch):
return self.base_lr
def __repr__(self):
fmt_str = (('Scheduler ' + self.__class__.__name__) + '\n')
fmt_str += ' Base LR : {}\n'.format(self.base_lr)
return fmt_s... |
def get_lr_scheduler(opts):
if (opts.scheduler == 'multistep'):
step_size = (opts.step_size if isinstance(opts.step_size, list) else [opts.step_size])
if (len(step_size) == 1):
step_size = step_size[0]
step_sizes = [(step_size * i) for i in range(1, int(math.ceil((opts.epoc... |
def get_scheduler_opts(parser):
' Scheduler Details'
group = parser.add_argument_group('Learning rate scheduler')
group.add_argument('--scheduler', default='hybrid', choices=supported_schedulers, help='Learning rate scheduler (e.g. fixed, clr, poly)')
group.add_argument('--step-size', default=[51], ty... |
def get_curr_time_stamp():
return time.strftime('%Y-%m-%d %H:%M:%S')
|
def print_error_message(message):
time_stamp = get_curr_time_stamp()
error_str = (((text_colors['error'] + text_colors['bold']) + 'ERROR ') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, error_str, message))
print('{} - {} - {}'.format(time_stamp, error_str, 'Exiting!!!'))
ex... |
def print_log_message(message):
time_stamp = get_curr_time_stamp()
log_str = (((text_colors['logs'] + text_colors['bold']) + 'LOGS ') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, log_str, message))
|
def print_warning_message(message):
time_stamp = get_curr_time_stamp()
warn_str = (((text_colors['warning'] + text_colors['bold']) + 'WARNING') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, warn_str, message))
|
def print_info_message(message):
time_stamp = get_curr_time_stamp()
info_str = (((text_colors['info'] + text_colors['bold']) + 'INFO ') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, info_str, message))
|
class DictWriter(object):
def __init__(self, file_name, format='csv'):
super(DictWriter, self).__init__()
assert (format in ['csv', 'json', 'txt'])
self.file_name = '{}.{}'.format(file_name, format)
self.format = format
def write(self, data_dict: dict):
if (self.forma... |
class SummaryWriter(object):
def __init__(self, log_dir, format='csv', *args, **kwargs):
super(SummaryWriter, self).__init__()
self.summary_dict = dict()
if (not os.path.isdir(log_dir)):
os.makedirs(log_dir)
self.log_dir = log_dir
self.file_name = '{}/logs'.for... |
def save_checkpoint(epoch, model_state, optimizer_state, best_perf, save_dir, is_best, keep_best_k_models=(- 1)):
best_perf = round(best_perf, 3)
checkpoint = {'epoch': epoch, 'state_dict': model_state, 'optim_dict': optimizer_state, 'best_perf': best_perf}
ckpt_fname = '{}/checkpoint_last.pth'.format(sav... |
def load_checkpoint(checkpoint_dir, device='cpu'):
ckpt_fname = '{}/checkpoint_last.pth'.format(checkpoint_dir)
checkpoint = torch.load(ckpt_fname, map_location=device)
epoch = checkpoint['epoch']
model_state = checkpoint['state_dict']
optim_state = checkpoint['optim_dict']
best_perf = checkpo... |
def save_arguments(args, save_loc, json_file_name='arguments.json'):
argparse_dict = vars(args)
arg_fname = '{}/{}'.format(save_loc, json_file_name)
writer = DictWriter(file_name=arg_fname, format='json')
writer.write(argparse_dict)
print_log_message('Arguments are dumped here: {}'.format(arg_fnam... |
def load_arguments(parser, dumped_arg_loc, json_file_name='arguments.json'):
arg_fname = '{}/{}'.format(dumped_arg_loc, json_file_name)
parser = argparse.ArgumentParser(parents=[parser], add_help=False)
with open(arg_fname, 'r') as fp:
json_dict = json.load(fp)
parser.set_defaults(**json_d... |
def load_arguments_file(parser, arg_fname):
parser = argparse.ArgumentParser(parents=[parser], add_help=False)
with open(arg_fname, 'r') as fp:
json_dict = json.load(fp)
parser.set_defaults(**json_dict)
updated_args = parser.parse_args()
return updated_args
|
def shuffle_samples(X, y):
zipped = list(zip(X, y))
np.random.shuffle(zipped)
(X_result, y_result) = zip(*zipped)
return (np.asarray(X_result), np.asarray(y_result))
|
def prepare_dataset(K):
(n_clusters, N, L, dt) = (4, 150, 100, 0.1)
t = np.arange(0, (L * dt), dt)[:L]
(seq_list, label_list) = ([], [])
for i in range(n_clusters):
n_sinusoids = np.random.random_integers(1, 4)
sample_parameters = [[np.random.normal(loc=1, scale=2, size=K), np.random.n... |
class Dataset(object):
'docstring for Dataset'
def __init__(self, dataset):
self.K = 3
if (dataset == 'synthetic'):
(seq_list, label_list) = prepare_dataset(self.K)
else:
assert False, 'does not exists dataset: {}.'.format(dataset)
self.L = seq_list[0].... |
def print_shape(name, tensor):
print('shape of {} is {}'.format(name, tensor.shape))
|
class AutoEncoder(object):
'docstring for AutoEncoder'
def __init__(self, args):
self.__dict__ = args.copy()
self.input_ = tf.placeholder(tf.float32, shape=[None, self.L, self.K])
self.input_batch_size = tf.placeholder(tf.int32, shape=[])
self.layers = []
with tf.name_... |
class DeepTemporalClustering(object):
'docstring for DeepTemporalClustering'
def __init__(self, params):
self.__dict__ = params.copy()
self.kmeans = KMeans(n_clusters=self.n_clusters, n_init=20)
self.auto_encoder = AutoEncoder(self.__dict__)
self.z = self.auto_encoder.encoder
... |
class InferenceLearnedModel():
'docstring for InferenceLearnedModel'
def __init__(self, args):
self.__dict__ = args.copy()
self.data = Dataset(self.dataset)
model = DeepTemporalClustering(params={'n_clusters': 4, 'L': self.data.L, 'K': self.data.K, 'n_filters_CNN': 100, 'kernel_size':... |
def main():
args = generate_args()
ilm = InferenceLearnedModel(args)
ilm.plot_decoded_sequences(stop_idx=10)
params = {'dimensions': 2, 'perplexity': 30.0, 'theta': 0.5, 'rand_seed': (- 1)}
bhtsne = BHTSNE(params)
bhtsne.fit_and_plot(ilm.z_list.reshape((len(ilm.z_list), (- 1))), ilm.data.label... |
def print_result(cur, total, loss_all_train, loss_seq_train, loss_train, loss_all_val, loss_seq_val, loss_val):
print('{0:d} / {1:d}\t train ({2:5.3f}, {3:5.3f}, {4:5.3f})\t val({5:5.3f}, {6:5.3f}, {7:5.3f})\t in order (total, seq, lat)'.format(cur, total, loss_all_train, loss_seq_train, loss_train, loss_all_val,... |
def train(args, batch_size=8, finetune_iteration=100, optimization_iteration=100, pretrained_ae_ckpt_path=None):
dataset = args['dataset']
data = Dataset(dataset)
model = DeepTemporalClustering(params={'n_clusters': args['n_clusters'], 'L': data.L, 'K': data.K, 'n_filters_CNN': 100, 'kernel_size': 10, 'P'... |
def main():
args = generate_args()
train(args)
|
class AttentionWeightedAverage(Layer):
'\n Computes a weighted average of the different channels across timesteps.\n Uses 1 parameter pr. channel to compute the attention value for a single timestep.\n '
def __init__(self, return_attention=False, **kwargs):
self.init = initializers.get('unif... |
def elsa_doc_model(hidden_dim=64, dropout=0.5, mode='train'):
I_en = Input(shape=(nb_maxlen[0], nb_feature[1]), dtype='float32')
en_out = AttentionWeightedAverage()(I_en)
I_ot = Input(shape=(nb_maxlen[1], nb_feature[0]), dtype='float32')
jp_out = AttentionWeightedAverage()(I_ot)
O_to = concatenate... |
def elsa_architecture(nb_classes, nb_tokens, maxlen, feature_output=False, embed_dropout_rate=0, final_dropout_rate=0, embed_dim=300, embed_l2=1e-06, return_attention=False, load_embedding=False, pre_embedding=None, high=False, LSTM_hidden=512, LSTM_drop=0.5):
'\n Returns the DeepMoji architecture uninitialize... |
class VocabBuilder():
' Create vocabulary with words extracted from sentences as fed from a\n word generator.\n '
def __init__(self, word_gen):
self.word_counts = defaultdict((lambda : 0), {})
self.word_length_limit = 30
for token in SPECIAL_TOKENS:
assert (len(t... |
class MasterVocab():
' Combines vocabularies.\n '
def __init__(self):
self.master_vocab = {}
def populate_master_vocab(self, vocab_path, min_words=1, force_appearance=None):
' Populates the master vocabulary using all vocabularies found in the\n given path. Vocabularies sho... |
def all_words_in_sentences(sentences):
' Extracts all unique words from a given list of sentences.\n\n # Arguments:\n sentences: List or word generator of sentences to be processed.\n\n # Returns:\n List of all unique words contained in the given sentences.\n '
vocab = []
if isinsta... |
def extend_vocab_in_file(vocab, max_tokens=10000, vocab_path=VOCAB_PATH):
' Extends JSON-formatted vocabulary with words from vocab that are not\n present in the current vocabulary. Adds up to max_tokens words.\n Overwrites file in vocab_path.\n\n # Arguments:\n new_vocab: Vocabulary to be... |
def extend_vocab(current_vocab, new_vocab, max_tokens=10000):
' Extends current vocabulary with words from vocab that are not\n present in the current vocabulary. Adds up to max_tokens words.\n\n # Arguments:\n current_vocab: Current dictionary of tokens.\n new_vocab: Vocabulary to be adde... |
def is_special_token(word):
equal = False
for spec in SPECIAL_TOKENS:
if (word == spec):
equal = True
break
return equal
|
def mostly_english(words, english, pct_eng_short=0.5, pct_eng_long=0.6, ignore_special_tokens=True, min_length=2):
' Ensure text meets threshold for containing English words '
n_words = 0
n_english = 0
if (english is None):
return (True, 0, 0)
for w in words:
if (len(w) < min_lengt... |
def correct_length(words, min_words, max_words, ignore_special_tokens=True):
" Ensure text meets threshold for containing English words\n and that it's within the min and max words limits. "
if (min_words is None):
min_words = 0
if (max_words is None):
max_words = 99999
n_words ... |
def punct_word(word, punctuation=string.punctuation):
return all([(True if (c in punctuation) else False) for c in word])
|
def load_non_english_user_set():
non_english_user_set = set(np.load('uids.npz')['data'])
return non_english_user_set
|
def non_english_user(userid, non_english_user_set):
neu_found = (int(userid) in non_english_user_set)
return neu_found
|
def separate_emojis_and_text(text):
emoji_chars = []
non_emoji_chars = []
for c in text:
if (c in emoji.UNICODE_EMOJI):
emoji_chars.append(c)
else:
non_emoji_chars.append(c)
return (''.join(emoji_chars), ''.join(non_emoji_chars))
|
def extract_emojis(text, wanted_emojis):
text = remove_variation_selectors(text)
return [c for c in text if (c in wanted_emojis)]
|
def remove_variation_selectors(text):
' Remove styling glyph variants for Unicode characters.\n For instance, remove skin color from emojis.\n '
for var in VARIATION_SELECTORS:
text = text.replace(var, u'')
return text
|
def shorten_word(word):
" Shorten groupings of 3+ identical consecutive chars to 2, e.g. '!!!!' --> '!!'\n "
isascii = (lambda s: (len(s) == len(s.encode())))
if (not isascii):
return word
if (len(word) < 3):
return word
letter_groups = [list(g) for (k, g) in groupby(word)]
... |
def detect_special_tokens(word):
try:
int(word)
word = SPECIAL_TOKENS[4]
except ValueError:
if AtMentionRegex.findall(word):
word = SPECIAL_TOKENS[2]
elif urlRegex.findall(word):
word = SPECIAL_TOKENS[3]
return word
|
def process_word(word):
' Shortening and converting the word to a special token if relevant.\n '
word = shorten_word(word)
word = detect_special_tokens(word)
return word
|
def remove_control_chars(text):
return CONTROL_CHAR_REGEX.sub('', text)
|
def convert_nonbreaking_space(text):
for r in [u'\\\\xc2', u'\\xc2', u'Â', u'\\\\xa0', u'\\xa0', u'\xa0']:
text = text.replace(r, u' ')
return text
|
def convert_linebreaks(text):
for r in [u'\\\\n', u'\\n', u'\n', u'\\\\r', u'\\r', u'\r', '<br>']:
text = text.replace(r, ((u' ' + SPECIAL_TOKENS[5]) + u' '))
return text
|
def tokenize(text):
'Splits given input string into a list of tokens.\n\n # Arguments:\n text: Input string to be tokenized.\n\n # Returns:\n List of strings (tokens).\n '
result = RE_PATTERN.findall(text)
result = [t for t in result if t.strip()]
return result
|
def check_ascii(word):
try:
word.decode('ascii')
return True
except (UnicodeDecodeError, UnicodeEncodeError):
return False
|
class TDrumorGCN(torch.nn.Module):
def __init__(self, in_feats, hid_feats, out_feats):
super(TDrumorGCN, self).__init__()
self.conv1 = GCNConv(in_feats, hid_feats)
self.conv2 = GCNConv((hid_feats + in_feats), out_feats)
def forward(self, data):
(x, edge_index) = (data.x, data... |
class BUrumorGCN(torch.nn.Module):
def __init__(self, in_feats, hid_feats, out_feats):
super(BUrumorGCN, self).__init__()
self.conv1 = GCNConv(in_feats, hid_feats)
self.conv2 = GCNConv((hid_feats + in_feats), out_feats)
def forward(self, data):
(x, edge_index) = (data.x, data... |
class Net(torch.nn.Module):
def __init__(self, in_feats, hid_feats, out_feats):
super(Net, self).__init__()
self.TDrumorGCN = TDrumorGCN(in_feats, hid_feats, out_feats)
self.BUrumorGCN = BUrumorGCN(in_feats, hid_feats, out_feats)
self.fc = torch.nn.Linear(((out_feats + hid_feats) ... |
def compute_test(loader, verbose=False):
model.eval()
loss_test = 0.0
out_log = []
with torch.no_grad():
for data in loader:
if (not args.multi_gpu):
data = data.to(args.device)
out = model(data)
if args.multi_gpu:
y = torch.c... |
class Net(torch.nn.Module):
def __init__(self, concat=False):
super(Net, self).__init__()
self.num_features = dataset.num_features
self.num_classes = args.num_classes
self.nhid = args.nhid
self.concat = concat
self.conv1 = GATConv(self.num_features, (self.nhid * 2)... |
@torch.no_grad()
def compute_test(loader, verbose=False):
model.eval()
loss_test = 0.0
out_log = []
for data in loader:
if (not args.multi_gpu):
data = data.to(args.device)
out = model(data)
if args.multi_gpu:
y = torch.cat([d.y.unsqueeze(0) for d in dat... |
class Model(torch.nn.Module):
def __init__(self, args, concat=False):
super(Model, self).__init__()
self.args = args
self.num_features = args.num_features
self.nhid = args.nhid
self.num_classes = args.num_classes
self.dropout_ratio = args.dropout_ratio
self... |
@torch.no_grad()
def compute_test(loader, verbose=False):
model.eval()
loss_test = 0.0
out_log = []
for data in loader:
if (not args.multi_gpu):
data = data.to(args.device)
out = model(data)
if args.multi_gpu:
y = torch.cat([d.y.unsqueeze(0) for d in dat... |
class GNN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, normalize=False, lin=True):
super(GNN, self).__init__()
self.conv1 = DenseSAGEConv(in_channels, hidden_channels, normalize)
self.bn1 = torch.nn.BatchNorm1d(hidden_channels)
self.conv2 = Dens... |
class Net(torch.nn.Module):
def __init__(self, in_channels=3, num_classes=6):
super(Net, self).__init__()
num_nodes = ceil((0.25 * max_nodes))
self.gnn1_pool = GNN(in_channels, 64, num_nodes)
self.gnn1_embed = GNN(in_channels, 64, 64, lin=False)
num_nodes = ceil((0.25 * nu... |
def train():
model.train()
loss_all = 0
out_log = []
for data in train_loader:
data = data.to(device)
optimizer.zero_grad()
(out, _, _) = model(data.x, data.adj, data.mask)
out_log.append([F.softmax(out, dim=1), data.y])
loss = F.nll_loss(out, data.y.view((- 1))... |
@torch.no_grad()
def test(loader):
model.eval()
loss_test = 0
out_log = []
for data in loader:
data = data.to(device)
(out, _, _) = model(data.x, data.adj, data.mask)
out_log.append([F.softmax(out, dim=1), data.y])
loss_test += (data.y.size(0) * F.nll_loss(out, data.y.v... |
def read_file(folder, name, dtype=None):
path = osp.join(folder, '{}.txt'.format(name))
return read_txt_array(path, sep=',', dtype=dtype)
|
def split(data, batch):
'\n\tPyG util code to create graph batches\n\t'
node_slice = torch.cumsum(torch.from_numpy(np.bincount(batch)), 0)
node_slice = torch.cat([torch.tensor([0]), node_slice])
(row, _) = data.edge_index
edge_slice = torch.cumsum(torch.from_numpy(np.bincount(batch[row])), 0)
... |
def read_graph_data(folder, feature):
'\n\tPyG util code to create PyG data instance from raw graph data\n\t'
node_attributes = sp.load_npz((folder + f'new_{feature}_feature.npz'))
edge_index = read_file(folder, 'A', torch.long).t()
node_graph_id = np.load((folder + 'node_graph_id.npy'))
graph_lab... |
class ToUndirected():
def __init__(self):
'\n\t\tPyG util code to transform the graph to the undirected graph\n\t\t'
pass
def __call__(self, data):
edge_attr = None
edge_index = to_undirected(data.edge_index, data.x.size(0))
num_nodes = ((edge_index.max().item() + 1) ... |
class DropEdge():
def __init__(self, tddroprate, budroprate):
'\n\t\tDrop edge operation from BiGCN (Rumor Detection on Social Media with Bi-Directional Graph Convolutional Networks)\n\t\t1) Generate TD and BU edge indices\n\t\t2) Drop out edges\n\t\tCode from https://github.com/TianBian95/BiGCN/blob/mas... |
class FNNDataset(InMemoryDataset):
'\n\t\tThe Graph datasets built upon FakeNewsNet data\n\n\tArgs:\n\t\troot (string): Root directory where the dataset should be saved.\n\t\tname (string): The `name\n\t\t\t<https://chrsmrrs.github.io/datasets/docs/datasets/>`_ of the\n\t\t\tdataset.\n\t\ttransform (callable, opt... |
class FdGars(Algorithm):
def __init__(self, session, nodes, class_size, gcn_output1, gcn_output2, meta, embedding, encoding):
self.nodes = nodes
self.meta = meta
self.class_size = class_size
self.gcn_output1 = gcn_output1
self.embedding = embedding
self.encoding = ... |
def arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=123, help='Random seed.')
parser.add_argument('--dataset_str', type=str, default='dblp', help="['dblp','example']")
parser.add_argument('--epoch_num', type=int, default=30, help='Number of epochs to tr... |
def set_env(args):
tf.reset_default_graph()
np.random.seed(args.seed)
tf.set_random_seed(args.seed)
|
def get_data(ix, int_batch, train_size):
if ((ix + int_batch) >= train_size):
ix = (train_size - int_batch)
end = train_size
else:
end = (ix + int_batch)
return (train_data[ix:end], train_label[ix:end])
|
def load_data(args):
if (args.dataset_str == 'dblp'):
(adj_list, features, train_data, train_label, test_data, test_label) = load_data_dblp()
node_size = features.shape[0]
node_embedding = features.shape[1]
class_size = train_label.shape[1]
train_size = len(train_data)
... |
def train(args, adj_list, features, train_data, train_label, test_data, test_label, paras):
with tf.Session() as sess:
adj_data = [normalize_adj(adj) for adj in adj_list]
meta_size = len(adj_list)
net = FdGars(session=sess, class_size=paras[2], gcn_output1=args.hidden1, gcn_output2=args.hi... |
class GAS(Algorithm):
def __init__(self, session, nodes, class_size, embedding_i, embedding_u, embedding_r, h_u_size, h_i_size, encoding1, encoding2, encoding3, encoding4, gcn_dim, meta=1, concat=True, **kwargs):
super().__init__(**kwargs)
self.meta = meta
self.nodes = nodes
self.... |
def arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=123, help='Random seed.')
parser.add_argument('--dataset_str', type=str, default='example', help="['dblp','example']")
parser.add_argument('--epoch_num', type=int, default=30, help='Number of epochs to... |
def set_env(args):
tf.reset_default_graph()
np.random.seed(args.seed)
tf.set_random_seed(args.seed)
|
def get_data(ix, int_batch, train_size):
if ((ix + int_batch) >= train_size):
ix = (train_size - int_batch)
end = train_size
else:
end = (ix + int_batch)
return (train_data[ix:end], train_label[ix:end])
|
def load_data(args):
if (args.dataset_str == 'example'):
(adj_list, features, train_data, train_label, test_data, test_label) = load_data_gas()
node_embedding_r = features[0].shape[1]
node_embedding_u = features[1].shape[1]
node_embedding_i = features[2].shape[1]
node_size ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.