code stringlengths 101 5.91M |
|---|
class Token(object):
def __init__(self, word, pos, idx):
self.word = word
self.pos = pos
self.idx = idx
self.parent = None
self.children = []
self.dep = None |
def cli_main(modify_parser=None):
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
if (args.distributed_init_method is None):
distributed_utils.infer_init_method(args)
if (args.distributed_init_method is not None):
if ((torch.... |
class TestSVNProjectCheckout():
def setup(self):
self.temp_dir = mkdtemp(prefix='mubench-checkout-svn_')
self.svn_url = Path(join(dirname(realpath(__file__)), 'test_svn')).as_uri()
self.checkouts_dir = join(self.temp_dir, 'checkouts')
self.uut = SVNProjectCheckout('-project-', '-vers... |
class AutoFeatureExtractor():
def __init__(self):
raise EnvironmentError('AutoFeatureExtractor is designed to be instantiated using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.')
_list_option_in_docstrings(FEATURE_EXTRACTOR_MAPPING_NAMES)
def from_pretrained(cls,... |
def plot_vs(pred_json, save_dir_i, base_json=None):
pred_saliency = np.array(pred_json['top_pred'])
gt_saliency = np.array(pred_json['gt'])
total_cells = pred_json['shots']
(t_min, t_max) = (0, total_cells)
x = np.arange(t_min, t_max, clip_len)
x = x[:len(pred_saliency)]
colors1 = (['white']... |
class BaseOptions(object):
def __init__(self):
self._parser = argparse.ArgumentParser()
self._initialized = False
def initialize(self):
self._parser.add_argument('--checkpoints_dir', type=str, default='./outputs/checkpoints/', help='models are saved here')
self._parser.add_argume... |
def stream_file_list(filenames, buffer_count=20, batch_size=10, chunk_size=1, shuffle=True):
filenames = filenames.copy()
if shuffle:
random.shuffle(filenames)
def _loaded_files():
for (i, fname) in enumerate(filenames):
(yield (i, load_file(fname)))
loaded_files = threaded(_... |
def _transform(parsed_date_data: ParsedDate, parsed_output_format_data: ParsedTargetFormat, output_format: str, output_timezone: str) -> str:
result = deepcopy(output_format)
if (output_timezone != ''):
parsed_date_data = _change_timezone(parsed_date_data, output_timezone)
result = _transform_year(r... |
_gloo()
class ReducerTest(TestCase):
def setUp(self):
self.file = tempfile.NamedTemporaryFile(delete=False)
self.store = c10d.FileStore(self.file.name, 1)
self.process_group = c10d.ProcessGroupGloo(self.store, 0, 1)
def test_single_dtype_single_bucket(self):
model = ReducerModule... |
class TimesformerConfig(PretrainedConfig):
model_type = 'timesformer'
def __init__(self, image_size=224, patch_size=16, num_channels=3, num_frames=8, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.... |
def Eva(n_neighbors, min_dist, log_file):
min_dist = min_dist
n_neighbors = n_neighbors
print({'min_dist': min_dist, 'n_neighbors': n_neighbors})
mp_new = loadmap('../fingerprint.mp')
mp_new.fit(method='umap', min_dist=min_dist, n_neighbors=n_neighbors)
X_new = mp2.rearrangement(X2, mp_new)
... |
def test_tfidf_vectorizer_setters():
(norm, use_idf, smooth_idf, sublinear_tf) = ('l2', False, False, False)
tv = TfidfVectorizer(norm=norm, use_idf=use_idf, smooth_idf=smooth_idf, sublinear_tf=sublinear_tf)
tv.fit(JUNK_FOOD_DOCS)
assert (tv._tfidf.norm == norm)
assert (tv._tfidf.use_idf == use_idf)... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
if (args.work_dir is not None):
cfg.work_dir = args.work_dir
if (args.resume_from is not None):
cfg.resume_from = args.resume_from
... |
class InfoGraph(nn.Module):
def __init__(self, hidden_dim, num_gc_layers, alpha=0.5, beta=1.0, gamma=0.1):
super(InfoGraph, self).__init__()
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.prior = args.prior
self.embedding_dim = mi_units = (hidden_dim * nu... |
class RoCBertConfig(PretrainedConfig):
model_type = 'roc_bert'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2,... |
class MixtureGroupNorm(nn.Module):
__constants__ = ['num_groups', 'num_channels', 'k', 'eps', 'weight', 'bias']
def __init__(self, num_channels, num_groups, k, eps=1e-05):
super(MixtureGroupNorm, self).__init__()
self.num_groups = num_groups
self.num_channels = num_channels
self.... |
def clean_module_name(name):
if name.startswith('sciann_applications'):
name = name.replace('sciann_applications', 'sciann.applications')
if name.startswith('sciann_preprocessing'):
name = name.replace('sciann_preprocessing', 'sciann.preprocessing')
return name |
class Communication():
def __init__(self, vehicle_type, vehicle_id):
self.vehicle_type = vehicle_type
self.vehicle_id = vehicle_id
self.local_pose = None
self.current_yaw = 0
self.current_state = None
self.target_motion = PositionTarget()
self.arm_state = Fals... |
def load_net_config(path):
with open(path, 'r') as f:
net_config = ''
while True:
line = f.readline().strip()
if ('net_type' in line):
net_type = line.split(': ')[(- 1)]
break
else:
net_config += line
return (net... |
class TestExog(unittest.TestCase):
def test_exog_ensemble(self):
self._test_exog_ensemble(automl=False)
def test_exog_automl_ensemble(self):
self._test_exog_ensemble(automl=True)
def _test_exog_ensemble(self, automl: bool):
print(('-' * 80))
logger.info((f'''TestExog.test_exo... |
def test(cfg):
du.init_distributed_training(cfg)
np.random.seed(cfg.RNG_SEED)
torch.manual_seed(cfg.RNG_SEED)
logging.setup_logging(cfg.OUTPUT_DIR)
logger.info('Test with config:')
logger.info(cfg)
model = build_model(cfg)
if (du.is_master_proc() and cfg.LOG_MODEL_INFO):
misc.log... |
def overview(target, data):
target.write('<a href="./')
dirName = os.getcwd()
dirNameList = list(dirName.split('/'))
dirNameIndex = dirNameList.index('Vitis_Accel_Examples')
diff = ((len(dirNameList) - dirNameIndex) - 1)
while (diff > 0):
target.write('../')
diff -= 1
for loc... |
def cli_optimize_on_call(sdfg: 'SDFG'):
from dace.transformation.optimizer import SDFGOptimizer
opt = SDFGOptimizer(sdfg)
return opt.optimize() |
class SpectrumTemplates(metaclass=ABCMeta):
def __init__(self):
raise NotImplementedError
def absolute_magnitudes(self, coefficients, filters, stellar_mass=None):
mass_modulus = (((- 2.5) * np.log10(stellar_mass)) if (stellar_mass is not None) else 0)
M = mag_ab(self.wavelength, self.tem... |
def load_wav_to_torch(full_path, sr=None):
(data, sr) = librosa.load(full_path, sr=sr)
data = np.clip(data, (- 1), 1)
data = (data * 32768.0)
return (torch.FloatTensor(data.astype(np.float32)), sr) |
def test_var_args_aot():
with pytest.raises(SyntaxError):
def arg_aot(*args: dace.float64[20]):
return (args[0] + args[1])
arg_aot.compile() |
def test_floor2vector():
x_vector = np.array([[1.1, 2, 3], [4.2, (- 3), 1]])
x_v = [0, 1, 1.5, 3]
(x_near, index) = cubic_utils.floor2vector(x_vector, x_v)
np.testing.assert_array_almost_equal(x_near, [1, 1.5, 1.5, 3, 1.5, 1])
np.testing.assert_array_almost_equal(index, [1, 2, 2, (- 1), 2, 1]) |
.parametrize('with_timestamp', [False, True])
def test_d3rlpy_logger(with_timestamp: bool) -> None:
logger = D3RLPyLogger(StubLoggerAdapterFactory(), 'test', with_timestamp)
adapter = logger.adapter
assert isinstance(adapter, StubLoggerAdapter)
if with_timestamp:
assert (adapter.experiment_name ... |
class LossNet(nn.Module):
def __init__(self, feature_sizes=[32, 16, 8, 4], num_channels=[64, 128, 256, 512], interm_dim=128):
super(LossNet, self).__init__()
self.GAP1 = nn.AvgPool2d(feature_sizes[0])
self.GAP2 = nn.AvgPool2d(feature_sizes[1])
self.GAP3 = nn.AvgPool2d(feature_sizes[2... |
def get_dataloaders(args, epic_ds=None, featuresloader=None):
dss = get_datasets(args, epic_ds=epic_ds, featuresloader=featuresloader)
dl_args = {'batch_size': args.batch_size, 'pin_memory': True, 'num_workers': args.num_workers, 'drop_last': False}
if (args.mode in ['train', 'training']):
dls = {'t... |
class JointTotalVariation(BaseSimilarityMeasure):
def __init__(self, mesh, wire_map, eps=1e-08, **kwargs):
super().__init__(mesh, wire_map=wire_map, **kwargs)
self.set_weights(volume=self.regularization_mesh.vol)
self.eps = eps
self._G = self.regularization_mesh.cell_gradient
def... |
def random_shuffle_forever(batch_size, data, *other_data):
data_list = ([data] + list(other_data))
indices = np.arange(len(data))
while True:
batch_indices = np.random.choice(indices, batch_size, replace=False)
batch = [x[batch_indices] for x in data_list]
(yield (batch[0] if (len(ba... |
def register_Ns3CallbackImpl__Void_Double_Double_Ns3Mac48Address_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, double, double, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::e... |
def register_types_ns3_dsr(module):
root_module = module.get_root()
module.add_enum('LinkStates', ['PROBABLE', 'QUESTIONABLE'])
module.add_enum('DsrMessageType', ['DSR_CONTROL_PACKET', 'DSR_DATA_PACKET'])
module.add_enum('ErrorType', ['NODE_UNREACHABLE', 'FLOW_STATE_NOT_SUPPORTED', 'OPTION_NOT_SUPPORTED... |
class Rouge(object):
def __init__(self):
self.beta = 1.2
def calc_score(self, candidate, refs):
assert (len(candidate) == 1)
assert (len(refs) > 0)
prec = []
rec = []
token_c = candidate[0].split(' ')
for reference in refs:
token_r = reference.... |
def checking_feature_entry():
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
features = torch.load('feature_cache/grail_mini_bert_32')
encoded_lens = sanity_check_feature(tokenizer, features)
frac = (lambda t: (sum([(x <= t) for x in encoded_len... |
def line_graph_forbidden_subgraphs():
from sage.graphs.graph import Graph
from sage.graphs.generators.basic import ClawGraph
graphs = [ClawGraph()]
graphs.append(Graph({0: [1, 2, 3], 1: [2, 3], 4: [2], 5: [3]}))
graphs.append(Graph({0: [1, 2, 3, 4], 1: [2, 3, 4], 3: [4], 2: [5]}))
graphs.append(... |
def ua_check_converted_mot():
phase = config['phase']
dataset_name = config['dataset_name']
if ((phase == 'train') and (dataset_name == 'UA-DETRAC')):
ua_root = config['dataset_path']
if (not os.path.exists(os.path.join(config['dataset_path'], 'DETRAC-Train-Annotations-MOT'))):
w... |
.parametrize('value, result', [(['foo', 'bar'], False), ({'foo', 'bar'}, False), ({'foo': 'bar'}, True), (('foo', 'bar'), False)])
def test_is_dict(value, result):
assert (is_dict(type(value)) == result) |
class FreeModuleCoBasis(Basis_abstract):
def __init__(self, basis, symbol, latex_symbol=None, indices=None, latex_indices=None):
self._basis = basis
Basis_abstract.__init__(self, basis._fmodule, symbol, latex_symbol, indices, latex_indices)
vl = list()
fmodule = self._fmodule
... |
def compute_f1_score(gt, pred):
gt_class = gt.cpu().detach().numpy()
pred_np = pred.cpu().detach().numpy()
pred_class = np.argmax(pred_np, axis=1)
F1 = f1_score(gt_class, pred_class, average='macro')
return F1 |
def mkdir_ifnotexists(directory):
if (not os.path.exists(directory)):
os.mkdir(directory) |
def build_param(ctx, py_arg):
if (getattr(py_arg, 'annotation', None) is not None):
raise ValueError("Compiled functions don't support annotations")
name = (py_arg.id if PY2 else py_arg.arg)
r = ctx.make_range(py_arg.lineno, py_arg.col_offset, (py_arg.col_offset + len(name)))
return Param(Tensor... |
def deprecate_method(method, old_name, removal_version=None, future_warn=False, error=False):
new_name = method.__qualname__
split_name = new_name.split('.')
if (len(split_name) > 1):
old_name = f'{split_name[0]}.{old_name}'
message = f'{old_name} has been deprecated, please use {new_name}.'
... |
def BaulieuIII_calc(TP, FP, FN, TN):
try:
n = (((TP + FP) + FN) + TN)
part1 = ((n * n) - (4 * ((TP * TN) - (FP * FN))))
return (part1 / ((2 * n) * n))
except Exception:
return 'None' |
def check_disjoint(a, b):
s = fd_solver()
s.add(a)
s.add(b)
return (unsat == s.check()) |
def print_network(net):
num_params = 0
for param in net.parameters():
num_params += param.numel()
print('Network', net)
print(('Total number of parameters: %d' % num_params)) |
def SQLiteFileLock(*args, **kwds):
from . import sqlitelockfile
return _fl_helper(sqlitelockfile.SQLiteLockFile, 'lockfile.sqlitelockfile', *args, **kwds) |
def training_stopping_msg(best_val):
print('\nStopping training, validation accuracy not improving after {:.2f}\n'.format(best_val), flush=True) |
def img_random_flip(image, choice):
image = cv2.flip(image, 1)
steering = choice[0]
throttle = choice[1]
steering = (- steering)
new_choice = [steering, throttle]
return (image, new_choice) |
class RandomFlip(object):
def __call__(self, rgb_img, label_img):
if (random.random() < 0.5):
rgb_img = rgb_img.transpose(Image.FLIP_LEFT_RIGHT)
label_img = label_img.transpose(Image.FLIP_LEFT_RIGHT)
return (rgb_img, label_img) |
class ChunkCacheBuilder():
def __init__(self, broker_ref, cache_dir: str, source: ShardedDataset[T], processor: BatchProcessor[T], rows_per_chunk: int):
logging.basicConfig(level=logging.INFO)
self.broker_ref = broker_ref
self.shard_status: Dict[(str, _ShardStatus)] = dict()
self._cu... |
_task('audio_pretraining')
class AudioPretrainingTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('data', help='path to data directory')
parser.add_argument('--sample-rate', default=16000, type=int, help='target sample rate. audio files will be up/down sampled to this rate')
... |
class FeatureFusionBlock_custom(nn.Module):
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True):
super(FeatureFusionBlock_custom, self).__init__()
self.deconv = deconv
self.align_corners = align_corners
self.groups = 1
self.expan... |
class MetaNetDefTest(unittest.TestCase):
def test_minimal(self):
metanet_pb2.NetsMap(key='test_key', value=caffe2_pb2.NetDef())
def test_adding_net(self):
meta_net_def = metanet_pb2.MetaNetDef()
net_def = caffe2_pb2.NetDef()
meta_net_def.nets.add(key='test_key', value=net_def)
... |
class ExplainStateEvolution(MessagePassing):
def __init__(self, model, keys=[], print_incoming=True, print_outcoming=True):
model.init_second_moments()
super().__init__(model, message_keys=['a'])
self.keys = keys
self.print_incoming = print_incoming
self.print_outcoming = pri... |
class DepthCompletion():
def __init__(self):
self.main_img_path = os.path.expanduser('dataset\\kitti_validation_cropped\\image')
self.input_depth_dir = os.path.expanduser('dataset\\kitti_validation_cropped\\velodyne_raw')
self.img_size = (450, 130)
def save_for_evaluation(self, sufficien... |
def mlp(input, out_dim, name, is_train, reuse, norm=None, activation=None, dtype=tf.float32, bias=True):
with tf.variable_scope(name, reuse=reuse):
(_, n) = input.get_shape()
w = tf.get_variable('w', [n, out_dim], dtype, tf.random_normal_initializer(0.0, 0.02))
out = tf.matmul(input, w)
... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('including_pad', [True, False])
.parametrize('ignore_border', [True, False])
.parametrize('channel_last', [False, True])
.parametrize('inshape, kernel, stride, pad', [((4, 6), (2, 2), (2, 1), (1, 0)), ((2, 4, 6), (2, 2), (2, 1), (1, 0)), ((2,... |
class PreActBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, drop_rate=0.2):
super(PreActBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = conv3x3(in_planes, planes, stride)
self.bn2 = nn.BatchNorm2d(planes)
self.conv... |
class Issue111Test(ReBenchTestCase):
def setUp(self):
super(Issue111Test, self).setUp()
self._set_path(__file__)
def test_invocation_and_mean_with_warmup_2(self):
ds = DataStore(self.ui)
cnf = Configurator(load_config((self._path + '/issue_111.conf')), ds, self.ui, exp_name='test... |
def extract_mosei(args, dim):
assert os.path.exists(args.flac_path), f'{args.flac_path} not exists'
todo = list(Path(args.flac_path).glob('*.flac'))
print(len(todo), 'audio files found in MOSEI')
assert (args.feature_type in ['mel', 'linear', 'fbank']), 'Feature type unsupported'
if (not os.path.exi... |
_numpy_output()
def test_flip_3d_axis02(A: dace.int32[(10, 5, 7)]):
return np.flip(A, axis=(0, 2)) |
def imread(img_path):
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img |
def __scale_width(img, target_size, crop_size, method=Image.BICUBIC):
(ow, oh) = img.size
if ((ow == target_size) and (oh >= crop_size)):
return img
w = target_size
h = int(max(((target_size * oh) / ow), crop_size))
return img.resize((w, h), method) |
def resnet101(num_classes, loss='softmax', pretrained=True, **kwargs):
model = ResNet(num_classes=num_classes, loss=loss, block=Bottleneck, layers=[3, 4, 23, 3], last_stride=2, fc_dims=None, dropout_p=None, **kwargs)
if pretrained:
init_pretrained_weights(model, model_urls['resnet101'])
return model |
class DeepV3Plus(nn.Module):
def __init__(self, num_classes, trunk='resnet-50', criterion=None, criterion_aux=None, cont_proj_head=0, wild_cont_dict_size=0, variant='D16', skip='m1', skip_num=48, args=None):
super(DeepV3Plus, self).__init__()
self.args = args
self.criterion = criterion
... |
class Trainer():
def __init__(self):
self.dataloader = None
self.model = None
self.color_loss = None
self.exposure_loss = None
self.illumination_smoothing_loss = None
self.spatial_consistency_loss = None
self.optimizer = None
def build_dataloader(self, ima... |
class ODEfunc(nn.Module):
def __init__(self, diffeq):
super(ODEfunc, self).__init__()
self.diffeq = diffeq
self.divergence_fn = divergence_approx
self.register_buffer('_num_evals', torch.tensor(0.0))
def before_odeint(self, e=None):
self._e = e
self._num_evals.fil... |
def _to2d(coors):
if (coors.shape[1] == 1):
coors = nm.c_[(coors, nm.zeros_like(coors))]
return coors |
class FlaxGPTJModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def download_extract(url, root, filename, md5):
download_url(url, root, filename, md5)
with tarfile.open(os.path.join(root, filename), 'r') as tar:
tar.extractall(path=root) |
('pyscipopt')
class TestSCIPBackend(GenericBackendTests):
def backend(self) -> GenericBackend:
return MixedIntegerLinearProgram(solver='SCIP').get_backend() |
_utils.test(arch=[ti.cpu, ti.cuda])
def test_function_without_return():
x = ti.field(ti.i32, shape=())
_func
def foo(val: ti.i32):
x[None] += val
def run():
foo(40)
foo(2)
x[None] = 0
run()
assert (x[None] == 42) |
def main(args):
logging.basicConfig(filename='struc2vec.log', filemode='w', level=logging.DEBUG, format='%(asctime)s %(message)s')
G = read_graph(args.edgelist_file)
build_struc_layers(G, args.OPT1, args.OPT2, args.OPT3, args.until_layer, args.workers)
fin = open(args.nodelabels_file, 'r')
if args.d... |
class Data():
def __init__(self, args):
kwargs = {'num_workers': args.n_threads, 'pin_memory': True}
if args.cpu:
kwargs['pin_memory'] = False
module = import_module(('data.' + args.data_train.lower()))
(self.loader_train, self.loader_test) = module.get_loader(args, kwarg... |
class Git(VersionControl):
name = 'git'
dirname = '.git'
repo_name = 'clone'
schemes = ('git', 'git+ 'git+ 'git+ssh', 'git+git', 'git+file')
unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')
default_arg_rev = 'HEAD'
def get_base_rev_args(rev):
return [rev]
def is_immutable_rev_checkou... |
class KerasDDPGAgent(KerasAgent):
def __init__(self, observation_space, action_space, filename='KerasDDPGAgent.h5f'):
nb_actions = action_space.shape[0]
actor = Sequential()
actor.add(Flatten(input_shape=((1,) + observation_space.shape)))
actor.add(Dense(32))
actor.add(Activa... |
def distance(str1, str2):
m = np.zeros([(len(str2) + 1), (len(str1) + 1)], dtype=int)
for x in range(1, (len(str2) + 1)):
m[(x, 0)] = (m[((x - 1), 0)] + 1)
for y in range(1, (len(str1) + 1)):
m[(0, y)] = (m[(0, (y - 1))] + 1)
for x in range(1, (len(str2) + 1)):
for y in range(1, ... |
_method
def random_diagonalizable_matrix(parent, eigenvalues=None, dimensions=None):
from sage.misc.prandom import randint
size = parent.nrows()
if (parent.nrows() != parent.ncols()):
raise TypeError('a diagonalizable matrix must be square.')
if ((eigenvalues is not None) and (dimensions is None... |
def max_val_accuracy(stats):
val_acc = stats['val_acc']
max_val_acc_idx = val_acc.index(max(val_acc))
max_val_acc = max(val_acc)
train_acc = stats['train_acc'][max_val_acc_idx]
val_loss = stats['val_loss'][max_val_acc_idx]
train_loss = stats['train_loss'][max_val_acc_idx]
return {'epoch': ma... |
def clean_up_gcda() -> None:
gcda_files = get_gcda_files()
for item in gcda_files:
remove_file(item) |
class ScalarMix(torch.nn.Module):
def __init__(self, mix_dim: int):
super().__init__()
self.scalars = torch.nn.Parameter(torch.zeros(mix_dim))
def __repr__(self):
return f'{self.__class__.__name__}(mix_dim={self.scalars.size(0)})'
def forward(self, tensors: Union[(torch.FloatTensor, ... |
.parametrize('bisecting_strategy', ['biggest_inertia', 'largest_cluster'])
.parametrize('init', ['k-means++', 'random'])
def test_three_clusters(bisecting_strategy, init):
X = np.array([[1, 1], [10, 1], [3, 1], [10, 0], [2, 1], [10, 2], [10, 8], [10, 9], [10, 10]])
bisect_means = BisectingKMeans(n_clusters=3, r... |
class Renderbuffer(object):
def __init__(self, internalformat, W, H):
self.__id = np.empty(1, dtype=np.uint32)
glCreateRenderbuffers(len(self.__id), self.__id)
glNamedRenderbufferStorage(self.__id[0], internalformat, W, H)
def delete(self):
glDeleteRenderbuffers(1, self.__id)
... |
def test_multi_stage():
batch_size = 32
linear = unittest.mock.Mock(wraps=torch.nn.Linear(8, 8))
inp = torch.autograd.Variable(torch.rand(batch_size, 8))
batcher = torch_batcher.TorchBatcher()
async def process(item, iters):
for iter in range(iters):
item = (await batcher(linear,... |
def compress_to_zip(dir_to_compress: os.PathLike, delete: bool=False):
shutil.make_archive(dir_to_compress, 'zip', root_dir=os.path.dirname(dir_to_compress), base_dir=os.path.basename(dir_to_compress))
if delete:
shutil.rmtree(dir_to_compress) |
def extract_warnings(artifact_dir, targets):
selected_warnings = set()
paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if (p.endswith('.zip') or from_gh)]
for p in paths:
selected_warnings.update(extract_warnings_from_single_artifact(p, targets))
return selected_warnings |
def make_plots(all_logdirs, legend=None, xaxis=None, values=None, count=False, font_scale=1.5, smooth=1, select=None, exclude=None, estimator='mean'):
data = get_all_datasets(all_logdirs, legend, select, exclude)
values = (values if isinstance(values, list) else [values])
condition = ('Condition2' if count ... |
class ResidualBlock(nn.Module):
def __init__(self, kernel_size=3, n_channels=64):
super(ResidualBlock, self).__init__()
self.conv_block1 = ConvolutionalBlock(in_channels=n_channels, out_channels=n_channels, kernel_size=kernel_size, batch_norm=True, activation='PReLu')
self.conv_block2 = Conv... |
class LogParser():
def __init__(self, config: object):
name = config.parsing_algorithm.lower()
config_class = factory.get_config_class('parsing', name)
algorithm_class = factory.get_algorithm_class('parsing', name)
self.parser = algorithm_class((config.parsing_algo_params if config.p... |
class ExtendedAffineWeylGroup_Class(UniqueRepresentation, Parent):
def __init__(self, cartan_type, general_linear, **print_options):
if (not cartan_type.is_affine()):
raise ValueError(('%s is not affine' % cartan_type))
self._cartan_type = cartan_type
self._prefixt = 't'
... |
class ScipyOptimizer():
def __init__(self, parameters, method, maxiter, callback=(lambda *args: None), **kwargs):
self.kwargs = kwargs
self.parameters = list(parameters)
self.method = method
self.maxiter = maxiter
self.callback = callback
self.param_groups = []
de... |
.parametrize('inspecs', pairwise_inspecs_params())
.parametrize('op', ['add2', 'sub2', 'mul2', 'div2', 'pow2', 'maximum2', 'minimum2'])
def test_pairwise_arithmetic(inspecs, op, nnabla_opts):
func = getattr(F, op)
fb = FunctionBenchmark(func, inspecs, [], {}, nnabla_opts.ext, nnabla_opts.ext_kwargs)
fb.benc... |
def finiteCheck(parameters):
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter((lambda p: (p.grad is not None)), parameters))
for p in parameters:
infGrads = isinf(p.grad.data)
p.grad.data[infGrads] = 0
nanGrads = isnan(p.grad.data)
... |
class ChannelLastModifier(FunctionModifier):
def __init__(self, inputs, inputs_cl=None):
super(ChannelLastModifier, self).__init__()
self._inputs = inputs
self._inputs_cl = inputs_cl
self._prepare_inputs(inputs, inputs_cl)
def _prepare_inputs(self, inputs, inputs_cl=None):
... |
def similarity_constrained_penalized_logp_atomrings(smiles, name, threshold, fp_type='ECFP4'):
benchmark_name = f'{name} {threshold:.1f} Similarity Constrained Penalized logP'
objective = RdkitScoringFunction(descriptor=(lambda mol: _penalized_logp_atomrings(mol)))
offset = (- objective.score(smiles))
c... |
def byetenet_residual_block(input_, dilation, layer_no, residual_channels, filter_width, causal=True, train=True):
block_type = ('decoder' if causal else 'encoder')
block_name = 'bytenet_{}_layer_{}_{}'.format(block_type, layer_no, dilation)
with tf.variable_scope(block_name):
input_ln = layer_norma... |
def infer_dataset_impl(path):
if IndexedRawTextDataset.exists(path):
return 'raw'
elif IndexedDataset.exists(path):
with open(index_file_path(path), 'rb') as f:
magic = f.read(8)
if (magic == IndexedDataset._HDR_MAGIC):
return 'cached'
elif (ma... |
class Partition4(nn.Module):
LAYER_SCOPES = ['Net/Linear[h2_layer]', 'Net/BatchNorm1d[bn3]', 'Net/Linear[output_layer]']
TENSORS = []
def __init__(self, layers, tensors, device='cuda:4'):
super().__init__()
for (idx, layer_scope) in enumerate(self.LAYER_SCOPES):
self.add_module(f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.