code stringlengths 101 5.91M |
|---|
class SuperResIDWE2K7(SuperResIDWEXKX):
def __init__(self, in_channels=None, out_channels=None, stride=None, bottleneck_channels=None, sub_layers=None, no_create=False, **kwargs):
super(SuperResIDWE2K7, self).__init__(in_channels=in_channels, out_channels=out_channels, stride=stride, bottleneck_channels=bot... |
class Statistics(object):
def __init__(self, loss=0, flow_loss=0, flow_history_loss=0, corefvocab_loss=0, corefattn_loss=0, num_effective_coref=0, n_words=0, n_correct=0):
self.num_effective_coref = num_effective_coref
self.loss = loss
self.flow_loss = flow_loss
self.flow_history_los... |
def get_new_subject_file_split(df: pd.DataFrame, split_method: str, data_testing: dict, random_seed: int, train_frac: float, test_frac: float, path_output: str, balance: str, subject_selection: dict=None) -> (list, list, list):
if (subject_selection is not None):
if (not (len(subject_selection['metadata']) ... |
class PublisherAgent(ph.Agent):
_USER_CLICK_PROBABILITIES = {1: {'sport': 0.0, 'travel': 1.0, 'science': 0.2, 'tech': 0.8}, 2: {'sport': 1.0, 'travel': 0.0, 'science': 0.7, 'tech': 0.1}}
def __init__(self, agent_id: str, exchange_id: str, user_click_proba: dict=None):
super().__init__(agent_id)
... |
_grad()
def moment_update(model, model_ema, m):
for (p1, p2) in zip(model.parameters(), model_ema.parameters()):
p2.data = ((p2.data * m) + (p1.data * (1 - m))) |
(autouse=True, scope='package')
def orca_context_fixture():
conf = {'spark.python.worker.reuse': 'false'}
sc = init_orca_context(cores=8, conf=conf)
def to_array_(v):
return v.toArray().tolist()
def flatten_(v):
result = []
for elem in v:
result.extend(elem.toArray().... |
def main():
args = parse_args()
model = Model()
model.read_model(args.input_model, ext=args.input_format)
print('num_cameras:', len(model.cameras))
print('num_images:', len(model.images))
print('num_points3D:', len(model.points3D))
model.create_window()
model.add_points()
model.add_c... |
def predict_by_best_model(args):
tokenizer = T5Tokenizer.from_pretrained(args['checkpoint'])
data = preprocess_data_t5(args)
testing_set = ood_dataset(data, tokenizer, args)
testing_set_length = len(testing_set)
eval_params = {'batch_size': args['per_device_eval_batch_size'], 'shuffle': True, 'num_w... |
def check_python_script(cmd):
args = split(cmd)
if (args[0] == 'python'):
args = args[1:]
with patch.object(sys, 'argv', args):
run_path(args[0], run_name='__main__') |
class TestStinespring(ChannelTestCase):
def test_init(self):
chan = Stinespring(self.UI)
self.assertAllClose(chan.data, self.UI)
self.assertEqual(chan.dim, (2, 2))
chan = Stinespring(self.depol_stine(0.5))
self.assertAllClose(chan.data, self.depol_stine(0.5))
self.ass... |
def process_hits(response, column_id_pa, column_cit_srprt, column_category_P, column_category_A, column_category_D, column_category_Y, column_category_L, column_category_O, column_category_T, column_category_E, column_category_X):
all_response_patent_applications = response.get('hits').get('hits')
for element i... |
def ComputePriorCounts(args, counts, ref_lexicon, g2p_lexicon, phonetic_decoding_lexicon):
prior_counts = defaultdict(list)
for word in counts:
prior_mean = [args.prior_mean[0], args.prior_mean[1], args.prior_mean[2]]
if (word not in ref_lexicon):
prior_mean[0] = 0
if (word n... |
_module()
class MixVisionTransformer(BaseModule):
def __init__(self, in_channels=3, embed_dims=64, num_stages=4, num_layers=[3, 4, 6, 3], num_heads=[1, 2, 4, 8], patch_sizes=[7, 3, 3, 3], strides=[4, 2, 2, 2], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_ratio=4, qkv_bias=True, drop_rate=0.0, attn_drop_rat... |
def test_one_time_tracing_func():
run_cell('x = 0')
run_cell('y = 1')
run_cell('\n def f(p):\n if p:\n return x\n else:\n return y\n ')
run_cell('z = f(False) + 1\nz = f(True) + 1')
run_cell('y = 2')
run_cell('logging.info(z)')
... |
class BatchFlattenWrapper(VerifiableWrapper):
def __init__(self, module):
if (not isinstance(module, snt.BatchFlatten)):
raise ValueError('Cannot wrap {} with a BatchFlattenWrapper.'.format(module))
super(BatchFlattenWrapper, self).__init__(module) |
def TrainDataLoader(imgDir, nbImg, transform, batchSize):
trainSet = ImageFolder(imgDir, nbImg, transform)
trainLoader = data.DataLoader(dataset=trainSet, batch_size=batchSize, shuffle=True, num_workers=1, drop_last=True)
return trainLoader |
class MegDistributedDataParallel(nn.Module):
def __init__(self, module, dim=0, broadcast_buffers=True, bucket_cap_mb=25):
super(MegDistributedDataParallel, self).__init__()
self.module = module
self.dim = dim
self.broadcast_buffers = broadcast_buffers
self.broadcast_bucket_si... |
def EmbedWord2Vec(walks, dimension):
time_start = time.time()
print('Creating embeddings.')
model = Word2Vec(walks, size=dimension, window=5, min_count=0, sg=1, workers=32, iter=1)
node_ids = model.wv.index2word
node_embeddings = model.wv.vectors
print('Embedding generation runtime: ', (time.tim... |
def _register_on_step_begin(model):
def hook(module, input):
for pruning in module.prunings:
pruning.on_step_begin()
hook_handle = model.register_forward_pre_hook(hook)
return hook_handle |
class DHCF(nn.Module):
def __init__(self, num_users: int, num_items: int, emb_dim: int, num_layers: int=3, drop_rate: float=0.5) -> None:
super().__init__()
(self.num_users, self.num_items) = (num_users, num_items)
self.num_layers = num_layers
self.drop_rate = drop_rate
self.... |
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, dilate, expand_ratio):
super(InvertedResidual, self).__init__()
self.stride = stride
assert (stride in [1, 2])
hidden_dim = round((inp * expand_ratio))
self.use_res_connect = ((self.stride == 1) and (inp ... |
class AverageInKspaceLayer(MergeLayer):
def __init__(self, incomings, data_shape, frame_dist=[1, 3, 5], divide_by_n=False, clipped=False, **kwargs):
if ('name' not in kwargs):
kwargs['name'] = 'kspace_averaging_layer'
super(AverageInKspaceLayer, self).__init__(incomings, **kwargs)
... |
def get_impact_point_direction(state: X, impact_point: Point) -> float:
abs_angle_dof = np.arctan2((impact_point.y - state.y), (impact_point.x - state.x))
car_heading: float = state.psi
return (abs_angle_dof - car_heading) |
def _render_databricks(js):
import inspect
if (_render_databricks.displayHTML is None):
found = False
for frame in inspect.getouterframes(inspect.currentframe()):
global_names = set(frame.frame.f_globals)
target_names = {'displayHTML', 'display', 'spark'}
if t... |
class Logged(Timed):
def __init__(self, **kwargs):
kwargs.setdefault('silent', True)
self.setup_logger(**kwargs)
def timeenv(self, **kwargs):
kw = dict(kwargs)
message = kw.pop('message', None)
timing = kw.pop('timing', True)
timer = kw.setdefault('timer', None)
... |
('cond-affine')
def cond_affine(dataset, model, use_baseline):
assert (not use_baseline), 'Cannot use baseline model for this config'
return {'schema_type': 'cond-affine', 'num_density_layers': 10, 'batch_norm': False, 'st_nets': ([128] * 2), 'p_nets': ([128] * 2), 'q_nets': GridParams(([10] * 2), ([100] * 4))} |
def evaluate_metrics_from_lists(predictions: List[str], ground_truths: List[List[str]], ids: Union[(List[int], None)]=None) -> Tuple[(Dict[(str, float)], Dict[(int, Dict[(str, float)])])]:
assert (len(predictions) == len(ground_truths))
assert all([(len(i) == 5) for i in ground_truths])
if (ids is None):
... |
class ExtensionsWidget():
tag = 'extensions'
description = 'Extensions'
icon = join(dirname(abspath(__file__)), '..', 'gui', 'buttons', 'button_extensions.png')
icon_highlighted = join(dirname(abspath(__file__)), '..', 'gui', 'buttons', 'button_extensions_highlighted.png')
def __init__(self, viz):
... |
class DistModel(BaseModel):
def name(self):
return self.model_name
def initialize(self, model='net-lin', net='alex', vgg_blocks=[1, 2, 3, 4, 5], colorspace='Lab', pnet_rand=False, pnet_tune=False, model_path=None, use_gpu=True, printNet=False, spatial=False, is_train=False, lr=0.0001, beta1=0.5, version... |
def dsrla_mobilenetv2_k24():
print('Constructing dsrla_mobilenetv2_k24......')
model = dsRLA_MobileNetV2(rla_channel=24)
return model |
def mlp_architecture(n_pc_points, bneck_size, bneck_post_mlp=False, check_n_pc_points=True):
if (check_n_pc_points and (n_pc_points != 2048)):
raise ValueError()
encoder = encoder_with_convs_and_symmetry
decoder = decoder_with_fc_only
n_input = [n_pc_points, 3]
encoder_args = {'n_filters': [... |
def now():
from datetime import datetime
return datetime.now().strftime('%Y%m%d%H%M')[:(- 1)] |
def draw_points_on_image(image, points, curr_point=None, highlight_all=True, radius_scale=0.01):
overlay_rgba = Image.new('RGBA', image.size, 0)
overlay_draw = ImageDraw.Draw(overlay_rgba)
for (point_key, point) in points.items():
if (((curr_point is not None) and (curr_point == point_key)) or highl... |
class CbamBlock(nn.Module):
def __init__(self, channels, reduction_ratio=16):
super(CbamBlock, self).__init__()
self.ch_gate = ChannelGate(channels=channels, reduction_ratio=reduction_ratio)
self.sp_gate = SpatialGate()
def forward(self, x):
x = self.ch_gate(x)
x = self.s... |
def main():
args = parse_args()
if (args.mode == 'single'):
train_cmd = ('python lib/train/run_training.py --script %s --config %s --save_dir %s --use_lmdb %d --script_prv %s --config_prv %s --distill %d --script_teacher %s --config_teacher %s --use_wandb %d' % (args.script, args.config, args.save_dir, ... |
class video_show():
def __init__(self):
self.show_output = rospy.get_param('~show_output', True)
self.save_output = rospy.get_param('~save_output', False)
self.output_video_file = rospy.get_param('~output_video_file', 'result.mp4')
self.bridge = CvBridge()
self.image_sub = ro... |
def compare_models(model_1, model_2):
models_differ = 0
for (key_item_1, key_item_2) in zip(model_1.state_dict().items(), model_2.state_dict().items()):
if torch.equal(key_item_1[1], key_item_2[1]):
pass
else:
models_differ += 1
if (key_item_1[0] == key_item_2... |
def cmpGraphs(g1, g2):
assert (g1.numVertices == g2.numVertices)
assert (g1.numEdges == g2.numEdges)
assert (len(list(g1.vertices)) == len(list(g2.vertices)))
assert (len(list(g1.edges)) == len(list(g2.edges)))
for (v1, v2) in zip(g1.vertices, g2.vertices):
assert (v1.id == v2.id)
as... |
class ExperimentPlannerPoolBasedOnSpacing(ExperimentPlanner):
def __init__(self, folder_with_cropped_data, preprocessed_output_folder):
super(ExperimentPlannerPoolBasedOnSpacing, self).__init__(folder_with_cropped_data, preprocessed_output_folder)
self.data_identifier = 'nnUNetData_poolBasedOnSpacin... |
def _match_array_semantics(sym_model):
if (check_mx_version('2.0.0') and mx.util.is_np_array()):
(symnet, args, auxs) = sym_model
symnet = symnet.as_np_ndarray()
for (k, v) in args.items():
args[k] = v.as_np_ndarray()
for (k, v) in auxs.items():
auxs[k] = v.as... |
class VREPGraspVisualization(object):
def __init__(self):
print('VREPGraspVisualization: Object started, attempting to connect to V-REP')
vrep.vrep.simxFinish((- 1))
self.client_id = vrep.vrep.simxStart(FLAGS.vrepConnectionAddress, FLAGS.vrepConnectionPort, FLAGS.vrepWaitUntilConnected, FLAG... |
class DictTensorOutputModel1(nn.Module):
def __init__(self):
super().__init__()
self.layer_1 = nn.Linear((28 * 28), 12)
self.layer_2 = nn.Linear((28 * 28), 12)
self.layer_3 = nn.Linear(24, 1)
def forward(self, x1, x2):
x1 = self.layer_1(x1)
x2 = self.layer_2(x2)
... |
class MBart50TokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
model_input_names = ['input_ids', 'attention_mask']
slow_tokenizer_class = MBart50Tokenize... |
def localize(loc_trainer, classify_evaluator, iter_items, k=5):
(batch_dict, dp_list) = iter_items
(probs, labels, loss) = loc_trainer.model(batch_dict, 'test', loss_fn=None)
classify_evaluator.add_metric_data(probs.cpu().tolist(), labels)
if (probs.shape[(- 1)] < k):
(value, idx_srt) = torch.to... |
def load_optimized_vae_decoder(cache_dir, accelerator='openvino', ipex=True, precision='float32', device='CPU', low_memory=False):
t_start = time.perf_counter()
decoder_path = os.path.join(cache_dir, 'decoder')
(nano_vae_decoder, cache_dir) = try_load_existing_model({}, decoder_path, accelerator=accelerator... |
def get_buffer(config, game) -> (ChessEnv, list):
env = ChessEnv().reset()
white = ChessPlayer(config, dummy=True)
black = ChessPlayer(config, dummy=True)
result = game.headers['Result']
(white_elo, black_elo) = (int(game.headers['WhiteElo']), int(game.headers['BlackElo']))
white_weight = clip_e... |
_cache(None)
def _infer_backed_cached(pool_class):
if (pool_class.__name__ == 'RayExecutor'):
return 'ray'
path = pool_class.__module__.split('.')
if (path[0] == 'concurrent'):
return 'concurrent.futures'
if (path[0] == 'joblib'):
return 'loky'
if (path[0] == 'distributed'):
... |
def test_bytes(doc):
assert (m.bytes_from_char_ssize_t().decode() == 'green')
assert (m.bytes_from_char_size_t().decode() == 'purple')
assert (m.bytes_from_string().decode() == 'foo')
assert (m.bytes_from_str().decode() == 'bar')
assert (doc(m.bytes_from_str) == 'bytes_from_str() -> bytes') |
def load_data(path: PathOrStr, file: PathLikeOrBinaryStream='data_save.pkl', bs: int=64, val_bs: int=None, num_workers: int=defaults.cpus, dl_tfms: Optional[Collection[Callable]]=None, device: torch.device=None, collate_fn: Callable=data_collate, no_check: bool=False, **kwargs) -> DataBunch:
source = ((Path(path) /... |
class CorrelationMetrics():
def __init__(self):
pass
def pearson_cor(self, data1, data2):
(r, p) = stats.pearsonr(data1, data2)
return (r, p)
def spearman_cor(self, data1, data2=None):
(rho, p) = stats.spearmanr(data1, data2)
return (rho, p) |
def test_evolveddiskdf_setup_roAsQuantity_oddunits():
from galpy.df import dehnendf
from galpy.potential import EllipticalDiskPotential, LogarithmicHaloPotential
lp = LogarithmicHaloPotential(normalize=1.0)
ep = EllipticalDiskPotential(twophio=0.05, phib=0.0, p=0.0, tform=(- 150.0), tsteady=125.0)
r... |
def get_parser():
parser = argparse.ArgumentParser(description='merge json files', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--input-jsons', type=str, nargs='+', action='append', default=[], help='Json files for the inputs')
parser.add_argument('--output-jsons', type=str, ... |
class DDPG(object):
def __init__(self, actor, critic, memory, observation_shape, action_shape, param_noise=None, action_noise=None, gamma=0.99, tau=0.001, normalize_returns=False, enable_popart=False, normalize_observations=True, batch_size=128, observation_range=((- 5.0), 5.0), action_range=((- 1.0), 1.0), return_... |
def register_task(name, dataclass=None):
def register_task_cls(cls):
if (name in TASK_REGISTRY):
return TASK_REGISTRY[name]
if (not issubclass(cls, FairseqTask)):
raise ValueError('Task ({}: {}) must extend FairseqTask'.format(name, cls.__name__))
if (cls.__name__ in ... |
class EncodeTest(tf.test.TestCase):
def testBasic(self):
with self.test_session():
item_emb = tf.constant([[0.1, 0.4, (- 0.51), (- 0.9)], [0.2, 0.4, (- 0.2), (- 0.2)], [0.1, 0.7, (- 0.4), (- 0.8)], [0.6, 0.4, (- 0.8), (- 0.3)], [0.9, 0.6, (- 0.2), (- 0.3)]])
codebook = tf.constant([[... |
def oPNBI_torch(pred, true, mask_value=None):
if (mask_value != None):
mask = torch.gt(true, mask_value)
pred = torch.masked_select(pred, mask)
true = torch.masked_select(true, mask)
bias = ((true + pred) / (2 * true))
return bias.mean() |
class NeuralNet(object):
def __init__(self, device, ngpu):
(self.device, self.ngpu) = (device, ngpu)
self.model = SRNET(self.ngpu).to(self.device)
if ((self.device.type == 'cuda') and (self.model.ngpu > 0)):
self.model = nn.DataParallel(self.model, list(range(self.model.ngpu)))
... |
_task('span_bert')
class SpanBertTask(FairseqTask):
def add_args(parser):
parser.add_argument('data', help='path to data directory')
parser.add_argument('--tokens-per-sample', default=512, type=int, help='max number of total tokens over all segments per sample for BERT dataset')
parser.add_a... |
def remove_symbols_and_diacritics(s: str, keep=''):
return ''.join(((c if (c in keep) else (ADDITIONAL_DIACRITICS[c] if (c in ADDITIONAL_DIACRITICS) else ('' if (unicodedata.category(c) == 'Mn') else (' ' if (unicodedata.category(c)[0] in 'MSP') else c)))) for c in unicodedata.normalize('NFKD', s))) |
.skipif((not torch.cuda.is_available()), reason='requires cuda')
.parametrize('cfg_file', ['../configs/kie/sdmgr/sdmgr_unet16_60e_wildreceipt.py'])
def test_single_gpu_test_kie(cfg_file):
curr_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
config_file = os.path.join(curr_dir, cfg_file)
cf... |
class DropoutParameter(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _DROPOUTPARAMETER |
def load_data(root_path, src, tar, batch_size):
kwargs = {'num_workers': 1, 'pin_memory': True}
loader_src = data_loader.load_training(root_path, src, batch_size, kwargs)
loader_tar = data_loader.load_training(root_path, tar, batch_size, kwargs)
loader_tar_test = data_loader.load_testing(root_path, tar,... |
class Linear(gpy.means.Mean):
def __init__(self, input_dim, output_dim) -> None:
super(Linear, self).__init__()
numpy.random.seed(cg.seed)
self.a = nn.Parameter(torch.tensor(numpy.random.randn(output_dim, input_dim, 1), dtype=cg.dtype))
self.b = nn.Parameter(torch.zeros(output_dim, 1... |
def preprocess(x, dset):
if (dset == 'CIFAR10-C'):
return (x / 255.0)
else:
return x |
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
directory = ('runs/%s/' % args.model_type)
if (not os.path.exists(directory)):
os.makedirs(directory)
filename = (directory + filename)
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, (('runs/%s/' %... |
def get_cluster_info(cluster, gold_doc):
text = gold_doc['text']
gold_ner = gold_doc['ner']
(ner, number, person, gender) = (set(), set(), set(), set())
for mention in cluster:
mtext = coreference_rendering.mention_text(text, mention).lower()
(tgender, tnumber, tperson) = coreference.pro... |
class HRSACAgent():
def __init__(self, in_actor, hidden_in_actor, hidden_out_actor, out_actor, in_critic, hidden_in_critic, hidden_out_critic, rnn_num_layers, rnn_hidden_size_actor, rnn_hidden_size_critic, lr_actor=0.01, lr_critic=0.01, weight_decay=1e-05, device='cpu', rnn=True, alpha=0.2, automatic_entropy_tuning... |
def readFragmentScores(name='resources/fpscores'):
import gzip
global _fscores
if (name == 'fpscores'):
name = op.join(op.dirname(__file__), name)
_fscores = cPickle.load(gzip.open(('%s.pkl.gz' % name)))
outDict = {}
for i in _fscores:
for j in range(1, len(i)):
outDi... |
def DoubleConv3x3BnReLU(filters, use_batchnorm, name=None):
(name1, name2) = (None, None)
if (name is not None):
name1 = (name + 'a')
name2 = (name + 'b')
def wrapper(input_tensor):
x = Conv3x3BnReLU(filters, use_batchnorm, name=name1)(input_tensor)
x = Conv3x3BnReLU(filters,... |
def make_array_list_fn_sign_covariant(fn: Callable[([ArrayList], Array)], axis: int=(- 2)) -> Callable[([ArrayList], Array)]:
return apply_sign_symmetry_to_fn(fn, functools.partial(_get_sign_orbit_array_list, axis=axis), functools.partial(_multiply_sign_along_axis, axis=axis), functools.partial(jnp.sum, axis=axis)) |
class PassLogTfIntermediate(NodeTransformerWithPrePost):
__tempId = 0
def __init__(self) -> None:
self.nestedCall = False
def reset(self) -> None:
self.__tempId = 0
def newTempVar(self, lval: str) -> str:
self.__tempId += 1
return 'PassLogTfIntermediateTempVar{}_{}'.forma... |
def _is_valid_sub_path(path, parent_paths):
if (not parent_paths):
return True
for parent_path in parent_paths:
if (path[:len(parent_path)] == parent_path):
return True
return False |
class ReplayBuffer():
def __init__(self, start_index, end_index, batch_size, is_permed, coin_number, sample_bias=1.0):
self.__coin_number = coin_number
self.__experiences = [Experience(i) for i in range(start_index, end_index)]
self.__is_permed = is_permed
self.__batch_size = batch_s... |
def set_num_threads(num_threads=2):
os.environ['MKL_NUM_THREADS'] = ('%s' % num_threads)
os.environ['NUMEXPR_NUM_THREADS'] = ('%s' % num_threads)
os.environ['OMP_NUM_THREADS'] = ('%s' % num_threads)
os.environ['OPENBLAS_NUM_THREADS'] = ('%s' % num_threads)
os.environ['VECLIB_MAXIMUM_THREADS'] = ('%s... |
def _return_handle(x):
handle = x.v_handle
if (not isinstance(handle, ctypes.c_void_p)):
handle = ctypes.c_void_p(handle)
return handle |
class Cutpaste_Dataset(Dataset):
def __init__(self, files: np.ndarray, config: Namespace):
self.files = files
self.center = config.center
self.cutpaste_transform = CutPaste(type=config.cutpaste_type)
self.crop_size = ((32, 32) if config.localization else (config.image_size, config.im... |
def blend_images_np(image, image2, alpha=0.5):
if (image.dtype != np.uint8):
raise ValueError('`image` not of type np.uint8')
if (image2.dtype != np.uint8):
raise ValueError('`image2` not of type np.uint8')
if (image.shape[:2] != image2.shape):
raise ValueError(('The image has spatia... |
def break_up_expressions(pred, label2idx):
if (pred.sum() == 0):
return ([pred.tolist()], [])
if (pred.all() > 0):
full_label = label2idx.idx2label['expressions'][int(pred[0])]
polarity = full_label.split('-')[(- 1)]
return ([([1] * len(pred))], [polarity])
idxs = []
bidx... |
(num_cpus=4)
def get_eval(content: str, max_tokens: int):
while True:
try:
response = openai.ChatCompletion.create(model='gpt-4', messages=[{'role': 'system', 'content': 'You are a helpful and precise assistant for checking the quality of the answer.'}, {'role': 'user', 'content': content}], tem... |
class SAConv2d(ConvAWS2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, use_deform=False):
super().__init__(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)
self.us... |
class ResNet(nn.Module):
def __init__(self, block, layer_channels, channels, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
... |
def _full_conv(input, weights, bias, i, ops, net):
w = tf.Variable(weights, name=('w' + str(i)), dtype='float32')
b = tf.Variable(bias, name=('bias' + str(i)), dtype='float32')
ops.append(w)
ops.append(b)
net[('weights' + str(i))] = w
net[('b' + str(i))] = b
conv = tf.nn.conv2d(input, w, str... |
class ImageSet(JavaValue):
def __init__(self, jvalue, bigdl_type='float'):
self.value = jvalue
self.bigdl_type = bigdl_type
if self.is_local():
self.image_set = LocalImageSet(jvalue=self.value)
else:
self.image_set = DistributedImageSet(jvalue=self.value)
... |
class ViltFeatureExtractionTester(unittest.TestCase):
def __init__(self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=30, size_divisor=2, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]):
self.parent = parent
... |
def resnet34(pretrained=False, **kwargs):
model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet34']), strict=False)
return model |
def run(rank, size, G):
save_path = f'./results_v0/{args.experiment_name}/'
if (rank == 0):
if (not os.path.exists(save_path)):
try:
os.makedirs(save_path)
except OSError:
pass
folder_name = ((save_path + args.name) + '/')
if ((rank... |
def rms(x, name=None):
if (name is None):
name = (x.op.name + '/rms')
with tf.name_scope(None):
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name) |
def _split_on_proportions_and_save(name, proportion_dict, logger, depth_and_tree_tuples):
length_all_data = len(depth_and_tree_tuples)
assert (sum(proportion_dict.values()) == 1.0), 'proportions should sum to one'
used_so_far = 0
out_dict = {}
out_trees_dict = {}
for (subset_name, proportion) in... |
class InceptionA(nn.Module):
def __init__(self, in_channels, pool_features):
super(InceptionA, self).__init__()
self.branch1x1 = BasicConv2d(in_channels, 64, 1)
self.branch5x5_1 = BasicConv2d(in_channels, 48, 1)
self.branch5x5_2 = BasicConv2d(48, 64, 5, padding=2)
self.branch... |
def build_fake_yaml():
fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: x\n outputs: op2_to_store\n device: cpu\n evaluation:\n accuracy:\n metric:\n topk: 1\n tuning:\n strategy:\n ... |
def count_chunks(true_seqs, pred_seqs):
correct_chunks = defaultdict(int)
true_chunks = defaultdict(int)
pred_chunks = defaultdict(int)
correct_counts = defaultdict(int)
true_counts = defaultdict(int)
pred_counts = defaultdict(int)
(prev_true_tag, prev_pred_tag) = ('O', 'O')
correct_chun... |
def get_inceptionv4(model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
net = InceptionV4(**kwargs)
if pretrained:
if ((model_name is None) or (not model_name)):
raise ValueError('Parameter `model_name` should be properly initialized for loading pretrain... |
class P9(GenericPenaltyLagrangian):
def __call__(self, y: Tensor, : Tensor, : Tensor) -> Tensor:
_adjusted = torch.max(, (2 * ))
tilde_x = self..tilde(, _adjusted)
return (self.(((_adjusted * y) + tilde_x)) - self.(tilde_x)) |
def test_nulticlass_task():
from sklearn.datasets import make_classification
(X, y) = make_classification(n_samples=100, n_features=10, n_informative=3, n_classes=3, random_state=2022)
ranked_strengths = measure_interactions(X, y)
assert (45 == len(ranked_strengths)) |
def get_datasets(logdir, condition=None):
global exp_idx
global units
datasets = []
for (root, _, files) in os.walk(logdir):
if ('progress.txt' in files):
exp_name = None
try:
config_path = open(os.path.join(root, 'config.json'))
config = j... |
def ExtractCam(gall_img):
gall_cam = []
for i in range(len(gall_img)):
cam_id = int(gall_img[i][(- 10)])
gall_cam.append(cam_id)
return np.array(gall_cam) |
(scope='function')
def ray_local_session_fixture():
if (not ray.is_initialized()):
ray.init(local_mode=True, ignore_reinit_error=True, log_to_driver=False, include_webui=False)
(yield)
if ray.is_initialized():
ray.shutdown() |
def test_ade_double_double_track():
(c3, c3q, c3qsols) = cyclic3homotopy()
ans = input('Tune the path parameters ? (y/n) ')
if (ans != 'y'):
sols = ade_double_double_track(c3, c3q, c3qsols)
else:
from phcpy.tuning import tune_path_parameters as tune
pars = tune(32)
sols =... |
def rename_cols(df, outcome, *, y_true=None, y_pred=None, uncertainty=None):
if (y_true is None):
y_true = y_true_header(outcome, underscore=(y_true_header(outcome, underscore=True) in df.columns))
if (y_true not in df.columns):
y_true = (str(outcome) + '-y_true')
if (y_pred is None)... |
_module()
class OrgUDADataset(object):
def __init__(self, source, target, cfg):
self.source = source
self.target = target
self.ignore_index = target.ignore_index
self.CLASSES = target.CLASSES
self.PALETTE = target.PALETTE
assert (target.ignore_index == source.ignore_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.