code stringlengths 17 6.64M |
|---|
class CrisprGenerator(Sequence):
def __init__(self, ref_store, out_store, samp_list, minproba=1):
self.ref_store = ref_store
self.out_store = out_store
self.samp_list = samp_list
self.minproba = minproba
def __getitem__(self, item):
samp_id = self.samp_list[item]
... |
def batched_pearson_loss(y_true, y_pred):
'Custom loss function for computing negative Pearson correlation within\n each batch.\n\n Parameters\n ----------\n y_true : tf.Tensor\n ground-truth; expect shape to be (None, 1).\n y_pred : tf.Tensor\n predicted values; expect shape to be (N... |
def get_branch_ms(ns):
branch_ms = ModelSpace.from_dict([[{'Layer_type': 'conv1d', 'filters': 32, 'kernel_size': 12, 'activation': 'relu', 'name': ('%s_L1_relu12' % ns)}, {'Layer_type': 'conv1d', 'filters': 32, 'kernel_size': 12, 'activation': 'tanh', 'name': ('%s_L1_tanh12' % ns)}, {'Layer_type': 'conv1d', 'filt... |
def get_model_space(out_filters=64, num_layers=9):
model_space = ModelSpace()
num_pool = 4
expand_layers = [((num_layers // 4) - 1), (((num_layers // 4) * 2) - 1), (((num_layers // 4) * 3) - 1)]
for i in range(num_layers):
model_space.add_layer(i, [Operation('conv1d', filters=out_filters, kern... |
def get_model_space(out_filters=64, num_layers=9):
model_space = ModelSpace()
num_pool = 4
expand_layers = [((num_layers // 4) - 1), (((num_layers // 4) * 2) - 1), (((num_layers // 4) * 3) - 1)]
for i in range(num_layers):
model_space.add_layer(i, [Operation('conv1d', filters=out_filters, kern... |
def get_model_space(out_filters=64, num_layers=9):
model_space = ModelSpace()
num_pool = 4
expand_layers = [((num_layers // 4) - 1), (((num_layers // 4) * 2) - 1), (((num_layers // 4) * 3) - 1)]
for i in range(num_layers):
model_space.add_layer(i, [Operation('conv1d', filters=out_filters, kern... |
class Tokenizer(object):
def __init__(self, chars='abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:’"/|_#$%ˆ&*˜‘+=<>()[]{} ', unk_token=True):
self.chars = chars
self.unk_token = (69 if unk_token else None)
self.build()
def build(self):
'Build up char2idx.\n '
self.... |
def utf8_to_sequence(text, maxlen=1014):
text = text.decode('utf-8')
text = text.lower()
data = np.zeros((maxlen, 1)).astype(int)
for i in range(len(text)):
if (i >= maxlen):
return data
data[i] = ord(text[i])
return data
|
def get_model_space(out_filters=64, num_layers=9):
model_space = ModelSpace()
num_pool = 4
expand_layers = [((num_layers // 4) - 1), (((num_layers // 4) * 2) - 1), (((num_layers // 4) * 3) - 1)]
for i in range(num_layers):
model_space.add_layer(i, [Operation('conv1d', filters=out_filters, kern... |
def get_model_space(out_filters=64, num_layers=9):
model_space = ModelSpace()
num_pool = 4
expand_layers = [((num_layers // 4) - 1), (((num_layers // 4) * 2) - 1), (((num_layers // 4) * 3) - 1)]
for i in range(num_layers):
model_space.add_layer(i, [Operation('conv1d', filters=out_filters, kern... |
def get_data_config_amber_encoded(fp, feat_name, batch_size, shuffle):
'Prepare the kwargs for BatchedHDF5Generator\n\n Note\n ------\n Only works for the layout of `data/zero_shot/amber_encoded.train_feats.train.h5`\n '
d = {'hdf5_fp': fp, 'x_selector': Selector('x'), 'y_selector': Selector(('lab... |
def get_data_config_deepsea_compiled(fp, feat_name, batch_size, shuffle):
'Equivalent for amber encoded but for deepsea 919 compiled hdf5\n '
meta = read_metadata()
d = {'hdf5_fp': fp, 'x_selector': Selector(label='x'), 'y_selector': Selector(label='y', index=meta.loc[feat_name].col_idx), 'batch_size':... |
def amber_app(wd, feat_name, run=False):
type_dict = {'controller_type': 'GeneralController', 'knowledge_fn_type': 'zero', 'reward_fn_type': 'LossAucReward', 'modeler_type': 'KerasModelBuilder', 'manager_type': 'DistributedManager', 'env_type': 'ControllerTrainEnv'}
train_data_kwargs = get_data_config_deepsea... |
class RocCallback(keras.callbacks.Callback):
def __init__(self, training_data, validation_data):
self.x = training_data[0]
self.y = training_data[1]
self.x_val = validation_data[0]
self.y_val = validation_data[1]
def on_train_begin(self, logs={}):
return
def on_t... |
class Metrics(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self._data = []
def on_epoch_end(self, batch, logs={}):
(X_val, y_val) = (self.validation_data[0], self.validation_data[1])
y_predict = np.asarray(model.predict(X_val))
y_val = np.argmax(y_val, axis=1... |
def sigmoid(z):
return (1 / (1 + np.exp((- z))))
|
def get_model_space(out_filters=64, num_layers=9):
model_space = ModelSpace()
num_pool = 4
expand_layers = [((num_layers // 4) - 1), (((num_layers // 4) * 2) - 1), (((num_layers // 4) * 3) - 1)]
for i in range(num_layers):
model_space.add_layer(i, [Operation('conv1d', filters=out_filters, kern... |
def get_flops():
run_meta = tf.RunMetadata()
opts = tf.profiler.ProfileOptionBuilder.float_operation()
flops = tf.profiler.profile(graph=K.get_session().graph, run_meta=run_meta, cmd='op', options=opts)
return flops.total_float_ops
|
def main():
args = sys.argv[1:]
wd = '.'
if (args[0] == 'ECG'):
input_node = Operation('input', shape=(1000, 1), name='input')
output_node = Operation('dense', units=4, activation='softmax')
(X_train, Y_train, X_test, Y_test, pid_test) = read_data_physionet_4(wd)
Y_train = ... |
def download_dbpedia():
dbpedia_url = 'https://github.com/le-scientifique/torchDatasets/raw/master/dbpedia_csv.tar.gz'
wget.download(dbpedia_url)
with tarfile.open('dbpedia_csv.tar.gz', 'r:gz') as tar:
tar.extractall()
|
def clean_str(text):
text = re.sub('[^A-Za-z0-9(),!?\\\'\\`\\"]', ' ', text)
text = re.sub('\\s{2,}', ' ', text)
text = text.strip().lower()
return text
|
def build_char_dataset(step, document_max_len):
alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:’\'"/|_#$%ˆ&*˜‘+=<>()[]{} '
if (step == 'train'):
df = pd.read_csv(TRAIN_PATH, names=['class', 'title', 'content'])
else:
df = pd.read_csv(TEST_PATH, names=['class', 'title', 'content'])
... |
def read_data_physionet_4_with_val(path, window_size=1000, stride=500):
with open(os.path.join(path, 'challenge2017.pkl'), 'rb') as fin:
res = pickle.load(fin)
all_data = res['data']
for i in range(len(all_data)):
tmp_data = all_data[i]
tmp_std = np.std(tmp_data)
tmp_mean =... |
def read_data_physionet_4(path, window_size=1000, stride=500):
with open(os.path.join(path, 'challenge2017.pkl'), 'rb') as fin:
res = pickle.load(fin)
all_data = res['data']
for i in range(len(all_data)):
tmp_data = all_data[i]
tmp_std = np.std(tmp_data)
tmp_mean = np.mean(... |
def slide_and_cut(X, Y, window_size, stride, output_pid=False, datatype=4):
out_X = []
out_Y = []
out_pid = []
n_sample = X.shape[0]
mode = 0
for i in range(n_sample):
tmp_ts = X[i]
tmp_Y = Y[i]
if (tmp_Y == 0):
i_stride = stride
elif (tmp_Y == 1):
... |
def f1_score(y_true, y_pred, pid_test):
final_pred = []
final_gt = []
for i_pid in np.unique(pid_test):
tmp_pred = y_pred[(pid_test == i_pid)]
tmp_gt = y_true[(pid_test == i_pid)]
final_pred.append(Counter(tmp_pred).most_common(1)[0][0])
final_gt.append(Counter(tmp_gt).most... |
def custom_f1(y_true, y_pred):
def recall_m(y_true, y_pred):
TP = K.sum(K.round(K.clip((y_true * y_pred), 0, 1)))
Positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = (TP / (Positives + K.epsilon()))
return recall
def precision_m(y_true, y_pred):
TP = K.sum(K.rou... |
def load_satellite_data(path, train):
train_file = os.path.join(path, 'satellite_train.npy')
test_file = os.path.join(path, 'satellite_test.npy')
(all_train_data, all_train_labels) = (np.load(train_file, allow_pickle=True)[()]['data'], np.load(train_file, allow_pickle=True)[()]['label'])
(test_data, t... |
def get_controller(state_space, sess):
'Test function for building controller network. A controller is a LSTM cell that predicts the next\n layer given the previous layer and all previous layers (as stored in the hidden cell states). The\n controller model is trained by policy gradients as in reinforcement ... |
def get_mock_manager(history_fn_list, Lambda=1.0, wd='./tmp_mock'):
'Test function for building a mock manager. A mock manager\n returns a loss and knowledge instantly based on previous\n training history.\n Args:\n train_history_fn_list: a list of\n '
manager = MockManager(history_fn_list=... |
def get_environment(controller, manager, should_plot, logger=None, wd='./tmp_mock/'):
'Test function for getting a training environment for controller.\n Args:\n controller: a built controller net\n manager: a manager is a function that manages child-networks. Manager is built upon `model_fn` and... |
def train_simple_controller(should_plot=False, logger=None, Lambda=1.0, wd='./outputs/mock_nas/'):
sess = tf.Session()
state_space = get_state_space()
hist_file_list = [('./data/mock_black_box/tmp_%i/train_history.csv' % i) for i in range(1, 21)]
manager = get_mock_manager(hist_file_list, Lambda=Lambd... |
def num_of_val_pos(wd):
managers = [x for x in os.listdir(wd) if x.startswith('manager')]
manager_pos_cnt = {}
for m in managers:
trials = os.listdir(os.path.join(wd, m, 'weights'))
pred = pd.read_table(os.path.join(wd, m, 'weights', trials[0], 'pred.txt'), comment='#')
manager_pos... |
def plot_zs_hist(hist_fp, config_fp, save_prefix, zoom_first_n=None):
zs_hist = pd.read_table(hist_fp, header=None, sep=',')
configs = pd.read_table(config_fp)
zs_hist['task'] = zs_hist[0].apply((lambda x: ('Manager:%i' % int(x.split('-')[0]))))
zs_hist['task_int'] = zs_hist[0].apply((lambda x: int(x.... |
def plot_single_run(feat_dirs, save_fp, zoom_first_n=None):
dfs = []
for d in feat_dirs:
hist = pd.read_table(os.path.join(d, 'train_history.csv'), header=None, sep=',')
hist['task'] = os.path.basename(d)
hist['trial'] = hist[0]
hist['auc'] = sma(hist[2], window=20)
his... |
def get_controller(model_space, session, data_description_len=3, layer_embedding_sharing=None):
with tf.device('/cpu:0'):
controller = ZeroShotController(data_description_config={'length': data_description_len}, share_embedding=layer_embedding_sharing, model_space=model_space, session=session, with_skip_c... |
def get_manager_distributed(train_data, val_data, controller, model_space, wd, data_description, verbose=0, devices=None, train_data_kwargs=None, validate_data_kwargs=None, **kwargs):
reward_fn = LossAucReward(method='auc')
input_node = State('input', shape=(1000, 4), name='input', dtype='float32')
output... |
def get_manager_common(train_data, val_data, controller, model_space, wd, data_description, verbose=2, n_feats=1, **kwargs):
input_node = State('input', shape=(1000, 4), name='input', dtype='float32')
output_node = State('dense', units=n_feats, activation='sigmoid')
model_compile_dict = {'loss': 'binary_c... |
def read_configs(arg):
dfeature_names = list()
with open(arg.dfeature_name_file, 'r') as read_file:
for line in read_file:
line = line.strip()
if line:
dfeature_names.append(line)
wd = arg.wd
(model_space, layer_embedding_sharing) = get_model_space_commo... |
def train_nas(arg):
wd = arg.wd
logger = setup_logger(wd, verbose_level=logging.INFO)
gpus = get_available_gpus()
(configs, config_keys, controller, model_space) = read_configs(arg)
tmp = dict(data_descriptive_features=np.stack([configs[k]['dfeatures'] for k in config_keys]), controller=controller... |
def get_controller(model_space, session, data_description_len=3, layer_embedding_sharing=None, use_ppo_loss=False, is_training=True):
with tf.device('/cpu:0'):
controller = ZeroShotController(data_description_config={'length': data_description_len, 'hidden_layer': {'units': 16, 'activation': 'relu'}, 'reg... |
def get_manager_distributed(train_data, val_data, controller, model_space, wd, data_description, verbose=0, devices=None, train_data_kwargs=None, validate_data_kwargs=None, **kwargs):
reward_fn = LossAucReward(method='auc')
input_node = State('input', shape=(1000, 4), name='input', dtype='float32')
output... |
def read_configs(arg, is_training=True):
meta = read_metadata()
dfeature_names = list()
with open(arg.dfeature_name_file, 'r') as read_file:
for line in read_file:
line = line.strip()
if line:
dfeature_names.append(line)
wd = arg.wd
model_spaces_mapp... |
def train_nas(arg):
wd = arg.wd
logger = setup_logger(wd, verbose_level=logging.INFO)
gpus = get_available_gpus()
(configs, config_keys, controller, model_space) = read_configs(arg)
tmp = dict(data_descriptive_features=np.stack([configs[k]['dfeatures'] for k in config_keys]), controller=controller... |
def get_manager(train_data, val_data, controller, model_space, wd, motif_name, verbose=2, **kwargs):
input_node = State('input', shape=(1000, 4), name='input', dtype='float32')
output_node = State('dense', units=1, activation='sigmoid')
model_compile_dict = {'loss': 'binary_crossentropy', 'optimizer': 'ad... |
def main(arg):
model_space = get_model_space()
(dataset1, dataset2) = read_data()
if (arg.dataset == 1):
(train_data, validation_data) = (dataset1['train'], dataset1['val'])
elif (arg.dataset == 2):
(train_data, validation_data) = (dataset2['train'], dataset2['val'])
else:
... |
def get_model_space_simple():
state_space = ModelSpace()
default_params = {'kernel_initializer': 'glorot_uniform', 'activation': 'relu'}
param_list = [[{'filters': 256, 'kernel_size': 8}, {'filters': 256, 'kernel_size': 14}, {'filters': 256, 'kernel_size': 20}]]
layer_embedding_sharing = {}
conv_s... |
def get_model_space_long():
state_space = ModelSpace()
default_params = {'kernel_initializer': 'glorot_uniform', 'activation': 'relu'}
param_list = [[{'filters': 16, 'kernel_size': 8}, {'filters': 16, 'kernel_size': 14}, {'filters': 16, 'kernel_size': 20}], [{'filters': 64, 'kernel_size': 8}, {'filters': ... |
def get_model_space_long_and_dilation():
state_space = ModelSpace()
default_params = {'kernel_initializer': 'glorot_uniform', 'activation': 'relu'}
param_list = [[{'filters': 16, 'kernel_size': 8}, {'filters': 16, 'kernel_size': 14}, {'filters': 16, 'kernel_size': 20}, {'filters': 16, 'kernel_size': 8, 'd... |
def read_metadata():
meta = pd.read_table('./data/zero_shot/full_metadata.tsv')
meta = meta.loc[(meta['molecule'] == 'DNA')]
indexer = pd.read_table('./data/zero_shot_deepsea/label_index_with_category_annot.tsv')
indexer['labels'] = ['_'.join(x.split('--')).replace('\xa0', '') for x in indexer['labels... |
def get_zs_controller_configs():
_holder = OrderedDict({'lstm_size': [32, 128], 'temperature': [0.5, 1, 2], 'use_ppo_loss': [True, False]})
_rollout = [x for x in itertools.product(*_holder.values())]
_keys = [k for k in _holder]
configs_all = [{_keys[i]: x[i] for i in range(len(x))} for x in _rollout... |
def analyze_sim_data(wd):
df = pd.read_table(os.path.join(wd, 'sum_df.tsv'))
d = json.loads(df.iloc[0]['config_str'].replace("'", '"').replace('True', 'true').replace('False', 'false'))
config_keys = [k for k in d]
configs = [[] for _ in range(len(config_keys))]
efficiency = []
specificity = [... |
class AutoDeeplab(nn.Module):
def __init__(self, num_classes, num_layers, criterion=None, filter_multiplier=8, block_multiplier=5, step=5, cell=cell_level_search.Cell, input_channels=3):
super(AutoDeeplab, self).__init__()
self.cells = nn.ModuleList()
self._num_layers = num_layers
... |
def main():
model = AutoDeeplab(7, 12, None)
x = torch.tensor(torch.ones(4, 3, 224, 224))
resultdfs = model.decode_dfs()
resultviterbi = model.decode_viterbi()[0]
print(resultviterbi)
print(model.genotype())
|
class MixedOp(nn.Module):
def __init__(self, C, stride):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in PRIMITIVES:
op = OPS[primitive](C, stride, False, False)
if ('pool' in primitive):
op = nn.Sequential(op, nn.BatchN... |
class Cell(nn.Module):
def __init__(self, steps, block_multiplier, prev_prev_fmultiplier, prev_fmultiplier_down, prev_fmultiplier_same, prev_fmultiplier_up, filter_multiplier):
super(Cell, self).__init__()
self.C_in = (block_multiplier * filter_multiplier)
self.C_out = filter_multiplier
... |
def obtain_decode_args():
parser = argparse.ArgumentParser(description='PyTorch DeeplabV3Plus Training')
parser.add_argument('--backbone', type=str, default='resnet', choices=['resnet', 'xception', 'drn', 'mobilenet'], help='backbone name (default: resnet)')
parser.add_argument('--dataset', type=str, defa... |
def obtain_evaluate_args():
parser = argparse.ArgumentParser(description='---------------------evaluate args---------------------')
parser.add_argument('--train', action='store_true', default=False, help='training mode')
parser.add_argument('--exp', type=str, default='bnlr7e-3', help='name of experiment')... |
def obtain_retrain_autodeeplab_args():
parser = argparse.ArgumentParser(description='PyTorch Autodeeplabv3+ Training')
parser.add_argument('--train', action='store_true', default=True, help='training mode')
parser.add_argument('--exp', type=str, default='bnlr7e-3', help='name of experiment')
parser.ad... |
def obtain_retrain_deeplab_v3plus_args():
parser = argparse.ArgumentParser(description='PyTorch DeeplabV3Plus Training')
parser.add_argument('--backbone', type=str, default='resnet', choices=['resnet', 'xception', 'drn', 'mobilenet'], help='backbone name (default: resnet)')
parser.add_argument('--out-stri... |
class Config(object):
def __init__(self):
self.ignore_label = 255
self.aspp_global_feature = False
self.n_classes = 19
self.datapth = '/dataset/Cityscapes_dataset'
self.gpus = 8
self.crop_size = (769, 769)
self.mean = (0.485, 0.456, 0.406)
self.std ... |
def obtain_search_args():
parser = argparse.ArgumentParser(description='PyTorch DeeplabV3Plus Training')
parser.add_argument('--backbone', type=str, default='resnet', choices=['resnet', 'xception', 'drn', 'mobilenet'], help='backbone name (default: resnet)')
parser.add_argument('--opt_level', type=str, de... |
class Loader(object):
def __init__(self, args):
self.args = args
self.args.nclass = 1
self.best_pred = 0.0
assert (args.resume is not None), RuntimeError("No model to decode in resume path: '{:}'".format(args.resume))
assert os.path.isfile(args.resume), RuntimeError("=> no... |
def get_new_network_cell():
args = obtain_decode_args()
args.cuda = ((not args.no_cuda) and torch.cuda.is_available())
load_model = Loader(args)
(result_paths, result_paths_space) = load_model.decode_architecture()
network_path = result_paths
network_path_space = result_paths_space
genotyp... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = BatchNorm2d(planes)
self.conv2 = nn.Conv2d(... |
class ResNet(nn.Module):
def __init__(self, nInputChannels, block, layers, os=16, pretrained=False):
self.inplanes = 64
super(ResNet, self).__init__()
if (os == 16):
strides = [1, 2, 2, 1]
dilations = [1, 1, 1, 2]
blocks = [1, 2, 4]
elif (os == ... |
def ResNet101(nInputChannels=3, os=16, pretrained=False):
model = ResNet(nInputChannels, Bottleneck, [3, 4, 23, 3], os, pretrained=pretrained)
return model
|
class ASPP_module(nn.Module):
def __init__(self, inplanes, planes, dilation):
super(ASPP_module, self).__init__()
if (dilation == 1):
kernel_size = 1
padding = 0
else:
kernel_size = 3
padding = dilation
self.atrous_convolution = nn.C... |
class DeepLabv3_plus(nn.Module):
def __init__(self, nInputChannels=3, n_classes=21, os=16, pretrained=False, freeze_bn=False, _print=True):
if _print:
print('Constructing DeepLabv3+ model...')
print('Backbone: Resnet-101')
print('Number of classes: {}'.format(n_classes... |
def get_1x_lr_params(model):
'\n This generator returns all the parameters of the net except for\n the last classification layer. Note that for each batchnorm layer,\n requires_grad is set to False in deeplab_resnet.py, therefore this function does not return\n any batchnorm parameter\n '
b = [... |
def get_10x_lr_params(model):
'\n This generator returns all the parameters for the last layer of the net,\n which does the classification of pixel into classes\n '
b = [model.aspp1, model.aspp2, model.aspp3, model.aspp4, model.conv1, model.conv2, model.last_conv]
for j in range(len(b)):
... |
class SeparableConv2d(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, padding=0, dilation=1, bias=False):
super(SeparableConv2d, self)._init_()
self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size, stride, padding, dilation, groups=inplanes, bias=bias)
self.poi... |
def fixed_padding(inputs, kernel_size, dilation):
kernel_size_effective = (kernel_size + ((kernel_size - 1) * (dilation - 1)))
pad_total = (kernel_size_effective - 1)
pad_beg = (pad_total // 2)
pad_end = (pad_total - pad_beg)
padded_inputs = F.pad(inputs, (pad_beg, pad_end, pad_beg, pad_end))
... |
class SeparableConv2d_same(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False):
super(SeparableConv2d_same, self).__init__()
self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size, stride, 0, dilation, groups=inplanes, bias=bias)
self.pointwis... |
class Block(nn.Module):
def __init__(self, inplanes, planes, reps, stride=1, dilation=1, start_with_relu=True, grow_first=True, is_last=False):
super(Block, self).__init__()
if ((planes != inplanes) or (stride != 1)):
self.skip = nn.Conv2d(inplanes, planes, 1, stride=stride, bias=Fals... |
class Xception(nn.Module):
'\n Modified Alighed Xception\n '
def __init__(self, inplanes=3, os=16, pretrained=False):
super(Xception, self).__init__()
if (os == 16):
entry_block3_stride = 2
middle_block_dilation = 1
exit_block_dilations = (1, 2)
... |
class ASPP_module(nn.Module):
def __init__(self, inplanes, planes, dilation):
super(ASPP_module, self).__init__()
if (dilation == 1):
kernel_size = 1
padding = 0
else:
kernel_size = 3
padding = dilation
self.atrous_convolution = nn.C... |
class DeepLabv3_plus(nn.Module):
def __init__(self, nInputChannels=3, n_classes=21, os=16, pretrained=False, freeze_bn=False, _print=True):
if _print:
print('Constructing DeepLabv3+ model...')
print('Backbone: Xception')
print('Number of classes: {}'.format(n_classes))... |
def get_1x_lr_params(model):
'\n This generator returns all the parameters of the net except for\n the last classification layer. Note that for each batchnorm layer,\n requires_grad is set to False in deeplab_resnet.py, therefore this function does not return\n any batchnorm parameter\n '
b = [... |
def get_10x_lr_params(model):
'\n This generator returns all the parameters for the last layer of the net,\n which does the classification of pixel into classes\n '
b = [model.aspp1, model.aspp2, model.aspp3, model.aspp4, model.conv1, model.conv2, model.last_conv]
for j in range(len(b)):
... |
def download_data_from_s3(task):
'Download pde data from s3 to store in temp directory'
s3_base = 'https://pde-xd.s3.amazonaws.com'
download_directory = '.'
if (task == 'darcyflow'):
data_files = ['piececonst_r421_N1024_smooth1.mat', 'piececonst_r421_N1024_smooth2.mat']
s3_path = None
... |
def main():
task = sys.argv[1]
download_data_from_s3(task)
|
def main(start_epoch, epochs):
assert torch.cuda.is_available(), NotImplementedError('No cuda available ')
if (not osp.exists('data/')):
os.mkdir('data/')
if (not osp.exists('log/')):
os.mkdir('log/')
args = obtain_evaluate_args()
torch.backends.cudnn.benchmark = True
model_fna... |
def SeparateConv(C_in, C_out, kernel_size, stride, padding, dilation, bias, BatchNorm):
return nn.Sequential(nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, groups=C_in, bias=False), BatchNorm(C_in), nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False))
|
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm, separate=False):
super(_ASPPModule, self).__init__()
if separate:
self.atrous_conv = SeparateConv(inplanes, planes, kernel_size, 1, padding, dilation, False, BatchNorm)
... |
class ASPP_train(nn.Module):
def __init__(self, backbone, output_stride, filter_multiplier=20, steps=5, BatchNorm=ABN, separate=False):
super(ASPP_train, self).__init__()
if (backbone == 'drn'):
inplanes = 512
elif (backbone == 'mobilenet'):
inplanes = 320
... |
def build_aspp(backbone, output_stride, BatchNorm, args, separate):
return ASPP_train(backbone, output_stride, args.filter_multiplier, 5, BatchNorm, separate)
|
def build_backbone(backbone, output_stride, BatchNorm, args):
if (backbone == 'resnet'):
return resnet.ResNet101(output_stride, BatchNorm)
elif (backbone == 'xception'):
return xception.AlignedXception(output_stride, BatchNorm)
elif (backbone == 'drn'):
return drn.drn_d_54(BatchNor... |
def conv3x3(in_planes, out_planes, stride=1, padding=1, dilation=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=padding, bias=False, dilation=dilation)
|
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=(1, 1), residual=True, BatchNorm=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride, padding=dilation[0], dilation=dilation[0])
self... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=(1, 1), residual=True, BatchNorm=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = BatchNorm(plane... |
class DRN(nn.Module):
def __init__(self, block, layers, arch='D', channels=(16, 32, 64, 128, 256, 512, 512, 512), BatchNorm=None):
super(DRN, self).__init__()
self.inplanes = channels[0]
self.out_dim = channels[(- 1)]
self.arch = arch
if (arch == 'C'):
self.con... |
class DRN_A(nn.Module):
def __init__(self, block, layers, BatchNorm=None):
self.inplanes = 64
super(DRN_A, self).__init__()
self.out_dim = (512 * block.expansion)
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = BatchNorm(64)
... |
def drn_a_50(BatchNorm, pretrained=True):
model = DRN_A(Bottleneck, [3, 4, 6, 3], BatchNorm=BatchNorm)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model
|
def drn_c_26(BatchNorm, pretrained=True):
model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch='C', BatchNorm=BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-26'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrain... |
def drn_c_42(BatchNorm, pretrained=True):
model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch='C', BatchNorm=BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-42'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrain... |
def drn_c_58(BatchNorm, pretrained=True):
model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch='C', BatchNorm=BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-c-58'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrain... |
def drn_d_22(BatchNorm, pretrained=True):
model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch='D', BatchNorm=BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-22'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrain... |
def drn_d_24(BatchNorm, pretrained=True):
model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 2, 2], arch='D', BatchNorm=BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-24'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrain... |
def drn_d_38(BatchNorm, pretrained=True):
model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch='D', BatchNorm=BatchNorm)
if pretrained:
pretrained = model_zoo.load_url(model_urls['drn-d-38'])
del pretrained['fc.weight']
del pretrained['fc.bias']
model.load_state_dict(pretrain... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.