code stringlengths 101 5.91M |
|---|
def c(dfs, numL, numR):
r = Rule.fromDFS(dfs)
assert (r.numLeftComponents == numL)
assert (r.numRightComponents == numR)
commonChecks(r) |
def bottle3(f, x_tuple):
x_sizes = tuple(map((lambda x: x.size()), x_tuple))
y = f(*map((lambda x: x[0].view(((x[1][0] * x[1][1]) * x[1][2]), *x[1][3:])), zip(x_tuple, x_sizes)))
y_size = y.size()
return y.view(x_sizes[0][0], x_sizes[0][1], x_sizes[0][2], *y_size[1:]) |
class BridgeTowerForImageAndTextRetrieval(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def polarity(importtext):
text = word_tokenize(importtext)
tokens = nltk.pos_tag(text)
polarity = TextBlob(importtext).sentiment[0]
sentiment = TextBlob(importtext).sentiment[1]
polaritylist = list()
for i in range(0, len(tokens), 3):
if (i <= (len(tokens) - 3)):
words = ((((... |
class PointnetSAModule(PointnetSAModuleMSG):
def __init__(self, *, mlp: List[int], npoint: int=None, radius: float=None, nsample: int=None, bn: bool=True, use_xyz: bool=True, pool_method='max_pool'):
super().__init__(mlps=[mlp], npoint=npoint, radii=[radius], nsamples=[nsample], bn=bn, use_xyz=use_xyz, pool... |
def train(train_dataloader, ae, optimizer, optimizer_step, cuda_details: gnn_utils.CudaDetails, tb_logger, lambda_value, property_pred_factor):
loss_meter = gnn_utils.AverageMeter()
time_meter = gnn_utils.AverageMeter()
time_on_calc = gnn_utils.AverageMeter()
prediction_mse_meter = gnn_utils.AverageMete... |
_model_architecture('s2ut_conformer', 's2ut_conformer')
def s2ut_conformer_architecture_base(args):
args.attn_type = getattr(args, 'attn_type', None)
args.pos_enc_type = getattr(args, 'pos_enc_type', 'abs')
args.input_feat_per_channel = getattr(args, 'input_feat_per_channel', 80)
args.input_channels = g... |
class LEVIRCDPlus(torch.utils.data.Dataset):
splits = ['train', 'test']
def __init__(self, root: str='.data/levircd_plus', split: str='train', transform: Compose=Compose([ToTensor()])):
assert (split in self.splits)
self.root = root
self.transform = transform
self.files = self.lo... |
def create_FDS_train_subset(args):
print('Creating FDS statistics updating subset...')
frame = pd.read_csv(os.path.join(args.data_dir, 'nyu2_train.csv'), header=None)
select_id = np.load(os.path.join(args.data_dir, 'FDS_train_subset_id.npy'))
frame.iloc[select_id].to_csv(os.path.join(args.data_dir, 'nyu... |
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--input_model', type=str, required=False, default='zfnet512-12.onnx')
parser.add_argument('--output_model', type=str, required=True)
return parser.parse_args() |
class TestHPO(unittest.TestCase):
search_space = {'learning_rate': SearchSpace((0.0001, 0.001)), 'num_train_epochs': SearchSpace(bound=(20, 100), interval=1), 'weight_decay': SearchSpace((0.0001, 0.001)), 'cooldown_epochs': SearchSpace(bound=(0, 10), interval=1), 'sparsity_warm_epochs': SearchSpace(bound=(0, 5), in... |
def make_agent(id, **kwargs):
if isinstance(id, str):
wargs = dict(**_agent_registry[id])
del wargs['agent']
wargs.update(kwargs)
instance = _agent_registry[id]['agent'](name=id, **wargs)
return instance
else:
return id(**kwargs) |
def get_extensions():
this_dir = os.path.dirname(os.path.abspath(__file__))
extensions_dir = this_dir
main_file = glob.glob(os.path.join(extensions_dir, '*.cpp'))
source_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', '*.cpp'))
source_cuda = glob.glob(os.path.join(extensions_dir, 'cuda', '*.cu')... |
class HfApi():
def __init__(self, endpoint=None):
self.endpoint = (endpoint if (endpoint is not None) else ENDPOINT)
def login(self, username: str, password: str) -> str:
path = '{}/api/login'.format(self.endpoint)
r = requests.post(path, json={'username': username, 'password': password}... |
def load_dataset(n_jobs, use_gpu, pin_memory, ascending, corpus, audio, text):
print('Prepare dataloader for training/validation')
(audio_transform, feat_dim) = create_transform(audio.copy())
tokenizer = load_text_encoder(**text)
(tr_set, dv_set, tr_loader_bs, dv_loader_bs, mode, data_msg) = create_data... |
class ModelCriterionConfig(FairseqDataclass):
loss_weights: Dict[(str, float)] = field(default_factory=dict, metadata={'help': 'weights for the loss terms'})
log_keys: List[str] = field(default_factory=list, metadata={'help': 'additional output keys to log'}) |
def track_parallel_progress(func, tasks, nproc, initializer=None, initargs=None, bar_width=50, chunksize=1, skip_first=False, keep_order=True):
if isinstance(tasks, tuple):
assert (len(tasks) == 2)
assert isinstance(tasks[0], collections_abc.Iterable)
assert isinstance(tasks[1], int)
... |
class ContinuousInverseModel(nn.Module):
def __init__(self, state_size, action_size, log_std_low=(- 10.0), log_std_high=2.0, hidden_size=256, dist_impl='pyd'):
super().__init__()
assert (dist_impl in ['pyd', 'beta'])
self.fc1 = nn.Linear((state_size * 2), hidden_size)
self.fc2 = nn.L... |
def test_glorot_normal_receptive_field():
from lasagne.init import GlorotNormal
sample = GlorotNormal().sample((50, 50, 2))
assert ((- 0.01) < sample.mean() < 0.01)
assert (0.09 < sample.std() < 0.11) |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, plan... |
def loss_G_fn(P, D, options, images, gen_images):
d_gen = D(P.augment_fn(gen_images))
if (options['loss'] == 'nonsat'):
g_loss = F.softplus((- d_gen)).mean()
elif (options['loss'] == 'lsgan'):
g_loss = (0.5 * ((d_gen - 1.0) ** 2).mean())
else:
g_loss = (- d_gen.mean())
return... |
def initialize_double_double_artificial_homotopy(target, start, homogeneous=False, vrblvl=0):
if (vrblvl > 0):
print('in initialize_double_double_artificial_homotopy', end='')
print(', homogeneous :', homogeneous)
print('the target system :')
for pol in target:
print(pol)... |
class MAP():
def __init__(self, length=20):
self.length = length
def init(self, train):
return
def reset(self):
self.test = 0
self.pos = 0
def skip(self, for_item=0, session=(- 1)):
pass
def add_multiple(self, result, next_items, for_item=0, session=0, positio... |
class CollectLayerHistogram(unittest.TestCase):
def setUp(self):
model = BuildFakeModel(width_mult=1)
(layer_tensor, include_layer) = (OrderedDict(), OrderedDict())
i = 0
for (key, value) in model.state_dict().items():
if (not value.ndim):
value = np.expan... |
def load_tensorrt_plugin():
global plugin_is_loaded
lib_path = get_tensorrt_op_path()
if ((not plugin_is_loaded) and os.path.exists(lib_path)):
ctypes.CDLL(lib_path)
plugin_is_loaded = True |
class KPFCNN(nn.Module):
def __init__(self, config):
super(KPFCNN, self).__init__()
self.encoder = KPCNN(config)
self.config = config
self.blocks = nn.ModuleDict()
start_i = 0
for (block_i, block) in enumerate(config.architecture):
if ('upsample' in block)... |
def InceptionV3(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, **kwargs):
global backend, layers, models, keras_utils
(backend, layers, models, keras_utils) = get_submodules_from_kwargs(kwargs)
if (not ((weights in {'imagenet', None}) or os.path.exists... |
(version='2.0')
class Optimizers(object):
def __init__(self, framework):
assert (framework in ('tensorflow', 'pytorch', 'pytorch_fx')), 'framework support tensorflow pytorch'
self.optimizers = framework_optimizers[framework]().optimizers
def __getitem__(self, optimizer_type):
assert (opt... |
class Permute(torch.nn.Module):
def __init__(self, dims):
super().__init__()
self.dims = dims
def forward(self, input: Tensor) -> Tensor:
return input.permute(self.dims).contiguous() |
def test_modelcheckpoint_get_state():
fpath = 'tests/test_model_functioning/modelcheckpoint/'
model_checkpoint = ModelCheckpoint(filepath='/'.join([fpath, 'weights_out']), monitor='val_loss')
trainer = Trainer(model, objective='binary', callbacks=[model_checkpoint], verbose=0)
trainer.fit(X_wide=X_wide,... |
def train(model, loader, optimizer, device, weights):
model.train()
total_loss = total_examples = 0
total_correct = total_examples = 0
for data in loader:
data = data.to(device)
if (data.train_mask.sum() == 0):
continue
optimizer.zero_grad()
out = model(data.x... |
def tune_model(model_type, X_tune, y_tune, X_val, y_val, tree_type=None, scoring='nll', bagging_frac=1.0, gridsearch=True, cond_mean_type='base', n_stopping_rounds=25, in_dir=None, logger=None, verbose=0, n_jobs=1):
start = time.time()
model = get_model(model_type=model_type, tree_type=tree_type, scoring=scorin... |
class AutoEncoder(nn.Module):
def __init__(self):
super(AutoEncoder, self).__init__()
self.autoencoder = nn.Sequential(nn.Conv2d(4, 8, kernel_size=3, stride=1, padding=1), nn.LeakyReLU(inplace=True), nn.AvgPool2d(kernel_size=2, stride=2), nn.Conv2d(8, 12, kernel_size=3, stride=1, padding=1), nn.Leak... |
class SpeedController(PID):
def __init__(self, params: Optional[PIDParam]=None):
params = (SpeedControllerParam() if (params is None) else params)
super(SpeedController, self).__init__(params)
def from_vehicle_params(cls, model_param: ModelParameters) -> 'SpeedController':
params = Speed... |
def load_predictions(pred_path, gt_path, w2i_path):
raw_preds = load_json(pred_path)
gt_data = load_json(gt_path)
word2idx = load_json(w2i_path)
idx2word = {i: w for (w, i) in word2idx.items()}
qid2ans = {int(e['qid']): int(e['answer_idx']) for e in gt_data}
qid2bbox = {int(e['qid']): e['bbox'] ... |
def tryLoad(name, default=None):
try:
import user_config
except:
return None
if hasattr(user_config, name):
return getattr(user_config, name)
return default |
class MaskedSeparableConv2D(_MaskedConv):
def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format='channels_last', dilation_rate=(1, 1), depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='global_uniform', pointwise_initializer='global_uniform', depthwise_regular... |
def default_install_dir(target_abi):
install_dir = '/tmp/mace_run'
if ((target_abi == 'armeabi-v7a') or (target_abi == 'arm64-v8a')):
install_dir = '/data/local/tmp/mace_run'
return install_dir |
class PruningCallbacks(BaseCallbacks):
def __init__(self, conf=None, model=None):
super(PruningCallbacks, self).__init__(conf=conf, model=model)
self.pruners_info = process_config(self.conf)
self.pruners = []
self._generate_pruners()
self.generate_hooks()
def on_train_end... |
def witness_set_of_hypersurface(nvar, hpol, precision='d'):
if (precision == 'd'):
from phcpy.phcpy2c3 import py2c_standard_witset_of_hypersurface
from phcpy.interface import load_standard_system
from phcpy.interface import load_standard_solutions
py2c_standard_witset_of_hypersurface... |
class MeshRenderer(nn.Module):
def __init__(self, rasterize_fov, znear=0.1, zfar=10, rasterize_size=224):
super(MeshRenderer, self).__init__()
x = (np.tan(np.deg2rad((rasterize_fov * 0.5))) * znear)
self.ndc_proj = torch.tensor(ndc_projection(x=x, n=znear, f=zfar)).matmul(torch.diag(torch.te... |
def test_func(x):
print('Running test_func')
p = mp.current_process()
y = ((x * x) if (p.runner is None) else x)
print(y) |
def blh2xyz(latitude, longitude, height):
latitude = math.radians(latitude)
longitude = math.radians(longitude)
e = math.sqrt((1 - ((B ** 2) / (A ** 2))))
N = (A / math.sqrt((1 - ((e ** 2) * (math.sin(latitude) ** 2)))))
X = (((N + height) * math.cos(latitude)) * math.cos(longitude))
Y = (((N + ... |
def interpolate_img(img, coords, order=3, mode='nearest', cval=0.0):
return map_coordinates(img, coords, order=order, mode=mode, cval=cval) |
class ResNet(nn.Module):
__factory = {18: torchvision.models.resnet18, 34: torchvision.models.resnet34, 50: torchvision.models.resnet50, 101: torchvision.models.resnet101, 152: torchvision.models.resnet152}
def __init__(self, depth, pretrained=True, cut_at_pooling=False, num_features=0, norm=False, dropout=0, n... |
def load_results(sent_lst, tokenizer):
full_result_dict = {}
failed_instances = []
found_idx = []
sent_lst_lst = list(sent_lst.items())
for (idx, (key, val)) in enumerate(sent_lst_lst):
if (idx in full_result_dict.keys()):
continue
word_lst1 = [x.text for x in tokenizer(v... |
def mood(sentence, **kwargs):
if isinstance(sentence, str):
try:
from pattern.en import parse, Sentence
sentence = Sentence(parse(sentence))
except ImportError:
pass
if imperative(sentence, **kwargs):
return IMPERATIVE
if conditional(sentence, **kw... |
class Attribute(JsonSerializer):
def __init__(self, name: str, attribute_type: str, value: Any):
super().__init__()
self.name = name
self.attribute_type = attribute_type
self.value = value |
class Generic_MIL_Dataset(Generic_WSI_Classification_Dataset):
def __init__(self, data_dir, **kwargs):
super().__init__(**kwargs)
self.data_dir = data_dir
self.use_h5 = False
def load_from_h5(self, toggle):
self.use_h5 = toggle
def __getitem__(self, idx):
import h5py
... |
class PowerTransformerComponent(Rescaling, AutotabularPreprocessingAlgorithm):
def __init__(self, random_state: Optional[np.random.RandomState]=None):
from sklearn.preprocessing import PowerTransformer
self.preprocessor = PowerTransformer(copy=False)
def get_properties(dataset_properties: Option... |
class Timer():
def __init__(self, keys):
self.keys = keys
self.n = {}
self.running_time = {}
self.total_time = {}
self.reset()
def start(self, key):
self.running_time[key] = time.time()
return self
def stop(self, key):
self.total_time[key] = (t... |
def _loads(s, *, fix_imports=True, encoding='ASCII', errors='strict', buffers=None):
if isinstance(s, str):
raise TypeError("Can't load pickle from unicode string")
file = io.BytesIO(s)
return _Unpickler(file, fix_imports=fix_imports, buffers=buffers, encoding=encoding, errors=errors).load() |
def main():
parser = argparse.ArgumentParser(description='Diffuser Pipeline for processing images with prompts.')
parser.add_argument('--prompt_path', type=str, default='dataset/animal.json', help='Path to the JSON file containing prompts.')
parser.add_argument('--save_path', type=str, default='train_set/an... |
class Task(NamedTuple):
video_name: str
video_path: str
out_path: str
min_frame: int
max_frame: int
target_fps: float
target_num_frames: int
width: int
height: int
max_height: int |
def evaluate(args):
with open(args.data, 'rb') as f:
test_dataset: SNLIDataset = pickle.load(f)
word_vocab = test_dataset.word_vocab
label_vocab = test_dataset.label_vocab
model = SNLIModel(num_classes=len(label_vocab), num_words=len(word_vocab), word_dim=args.word_dim, hidden_dim=args.hidden_di... |
_model('s2t_transformer_w2v2')
class S2TTransformerModelW2V2(FairseqEncoderDecoderModel):
def __init__(self, encoder, decoder):
super().__init__(encoder, decoder)
def add_args(parser):
parser.add_argument('--conv-kernel-sizes', type=str, metavar='N', help='kernel sizes of Conv1d subsampling laye... |
class SegNet(nn.Module):
def __init__(self, input_nbr=3, label_nbr=22):
super(SegNet, self).__init__()
batchNorm_momentum = 0.1
self.conv11 = nn.Conv2d(input_nbr, 64, kernel_size=3, padding=1)
self.bn11 = nn.BatchNorm2d(64, momentum=batchNorm_momentum)
self.conv12 = nn.Conv2d... |
class DataCfg(TypedDict):
type: str
mode: str
size: Sequence[int]
supp_idxs: Optional[Sequence[int]]
use_depth: Optional[bool]
use_hints: Optional[bool]
use_benchmark: Optional[bool]
use_strong_aug: Optional[bool]
as_torch: Optional[bool]
use_aug: Optional[bool]
log_time: Opt... |
def load_local_or_remote_file(filepath, file_type=None):
local_path = local_path_from_s3_or_local_path(filepath)
if (file_type is None):
extension = local_path.split('.')[(- 1)]
if (extension == 'npy'):
file_type = NUMPY
else:
file_type = PICKLE
else:
... |
class FuncNonContiguousArgs():
def forward(self, input_ids, some_other_args, token_type_ids, attention_mask):
return None |
def set_severity(args):
if (args.dataset != 'kitti'):
args.severity = args.robustness_severities[args.severity_idx]
return True
if (args.task == 'initial'):
args.severity = ''
return True
if (args.severity_idx < len(globals.KITTI_SEVERITIES[args.task])):
args.severity... |
def inverse_dict(d):
assert (len(d.keys()) == len(set(d.keys())))
return {v: k for (k, v) in d.items()} |
def get_model_list():
_start_prompt = ' Transformers currently provides the following architectures'
_end_prompt = '1. Want to contribute a new model?'
with open(os.path.join(REPO_PATH, 'README.md'), 'r', encoding='utf-8', newline='\n') as f:
lines = f.readlines()
start_index = 0
while (not ... |
class EagerModeCtx():
def __init__(self, eagerly: bool) -> None:
assert isinstance(eagerly, bool), f'argument eagerly should not be {eagerly.__class__}. It must be a boolean.'
self.eagerly = eagerly
def __enter__(self) -> None:
self.old_mode = tf.config.functions_run_eagerly()
tf... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data_name', default='gsm8k', type=str)
parser.add_argument('--model_name_or_path', default='gpt-4', type=str)
parser.add_argument('--prompt_type', default='pal', type=str)
parser.add_argument('--split', default='test', type=... |
class AlexDagRnn(nn.Module):
def __init__(self, embedding_size, hidden_size):
super(AlexDagRnn, self).__init__()
self.embedding_size = embedding_size
self.hidden_size = hidden_size
(sym_dict, _) = ut.get_sym_dict()
self.max_tok = (len(sym_dict) + 1)
embedding = nn.Emb... |
def get_tag_device(args: object) -> str:
tag = ''
if torch.cuda.is_available():
txt = subprocess.run(['nvidia-smi', '--list-gpus'], stdout=subprocess.PIPE).stdout.decode('utf-8').split('\n')
try:
cudaids = args.cudaid.split(',')
tag = 'CUDA devices: \n'
for ci... |
_model
def ese_vovnet19b_dw(pretrained=False, **kwargs):
return _create_vovnet('ese_vovnet19b_dw', pretrained=pretrained, **kwargs) |
def get_user_config(usr_config_path, default_config=None):
if (default_config is None):
config = get_default_config()
else:
config = default_config
usr_config = get_config_from_file(usr_config_path)
config.merge_from_other_cfg(usr_config)
config = get_conditional_config(config)
r... |
def calibrate(prompt_model: PromptForClassification, dataloader: PromptDataLoader) -> torch.Tensor:
all_logits = []
prompt_model.eval()
for batch in tqdm(dataloader, desc='ContextCali'):
batch = batch.to(prompt_model.device)
logits = prompt_model.forward_without_verbalize(batch)
all_... |
def create_lmsm_network(outfname_train, outfname_deploy, source_train, source_test, softmax_weight, use_OLE, batch_size_train, lambda_, num_classes=10):
template_train = open('model/cifar_network.prototxt', 'r').read()
template_deploy = open('model/cifar_network.prototxt', 'r').read()
if use_OLE:
te... |
def pca_sub_df(df, task, ref_depth):
data_dict = pkl.load(open(scores_path, 'rb'))
accs = [get_acc(data_dict, probe_task, seed, layer=ref_depth, dims=0, run='average') for seed in REF_SEEDS]
acc_dict = dict(zip(REF_SEEDS, accs))
best_seed = max(acc_dict, key=acc_dict.get)
sub_df = df[(((df.layer1 ==... |
def register_images(output_map, grapher, prefix='train'):
if ((args.distributed_rank == 0) and (grapher is not None)):
for (k, v) in output_map.items():
if isinstance(v, dict):
register_images(output_map[k], grapher, prefix=prefix)
if (('img' in k) or ('imgs' in k)):
... |
class BidirectionalLSTM(nn.Module):
def __init__(self, nIn, nHidden, nOut, dropout=0.2):
super(BidirectionalLSTM, self).__init__()
self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True, batch_first=True)
self.embedding = nn.Linear((nHidden * 2), nOut)
self.dropout = nn.Dropout(p=dropou... |
_module()
class ResNeXt2(ResNet2):
arch_settings = {50: (Bottleneck, (3, 4, 6, 3)), 101: (Bottleneck, (3, 4, 23, 3)), 152: (Bottleneck, (3, 8, 36, 3))}
def __init__(self, groups=1, base_width=4, patch_path=None, **kwargs):
self.groups = groups
self.base_width = base_width
super(ResNeXt2,... |
def search_similar(s1, dlist=DATASET_IDS, MAX_SIMILARS=10):
similars = {s2: similarity(s1, s2) for s2 in dlist if similarity(s1, s2)}
top_match = Counter(similars).most_common((MAX_SIMILARS + 1))
return top_match |
def _ada_boost_hp_space(name_func, base_estimator=None, n_estimators=None, learning_rate=None, random_state=None):
hp_space = dict(base_estimator=base_estimator, n_estimators=(_boosting_n_estimators(name_func('n_estimators')) if (n_estimators is None) else n_estimators), learning_rate=(_ada_boost_learning_rate(name... |
def pageinate(page, maxPage, n):
pages = [page]
min = (page - 1)
max = (page + 1)
while (len(pages) < n):
if (((((2 * page) - min) <= max) or (max > maxPage)) and (min > 0)):
pages.append(min)
min -= 1
elif (max <= maxPage):
pages.append(max)
... |
def get_device():
device = ('cuda' if torch.cuda.is_available() else 'cpu')
if (torch.backends.mps.is_available() and torch.backends.mps.is_built()):
device = 'mps'
if (device == 'mps'):
print("WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible tor... |
def ignore_buffers_decorator(func):
def wrapper_ignore_buffers_decorator(self, raw_state):
raw_state = raw_state[(- 1)]
if (len(raw_state['parsed_mkt_data']) == 0):
pass
else:
raw_state['parsed_mkt_data'] = raw_state['parsed_mkt_data'][(- 1)]
if raw_state[... |
class Layer(object):
def __init__(self):
raise NotImplementedError((str(type(self)) + ' does not implement this method'))
def get_output_shape(self):
raise NotImplementedError((str(type(self)) + ' does not implement this method'))
def output(self):
raise NotImplementedError((str(type... |
def get_vehicle_corners_from_dict(state_dict):
x = state_dict['center-x']
y = state_dict['center-y']
psi = state_dict['heading']
body_shape = state_dict['corners']
center = np.array([x, y])
R = np.array([[np.cos(psi), (- np.sin(psi))], [np.sin(psi), np.cos(psi)]])
corners = (R body_shape.T)... |
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--display_freq', type=int, default=100, help='frequency of showing training results on screen')
self.parser.add_argument('--print_freq', type=int, default=100, help='frequency of sho... |
def main():
cuda = torch.cuda.is_available()
device = torch.device(('cuda' if cuda else 'cpu'))
print('Used device:', device)
encoder = CNN_4Layer(in_channels=3)
encoder = encoder.to(device)
save_path = 'prototransfer/checkpoints/random_init_conv4'
print('Save path is:', save_path)
def s... |
def ReadFile(tthread, batchInterval):
(w, h) = (6, 6)
y = [[0 for x in range(w)] for y in range(h)]
y_sum = [0 for x in range(w)]
inputEvents = (tthread * batchInterval)
gs_path = (FILE_FOLER + '/GS/threads = {}/totalEvents = {}'.format(tthread, inputEvents))
lines = open(gs_path).readlines()
... |
class WideResNet(nn.Module):
def __init__(self, depth, num_classes, widen_factor=1, bn_aff=True, shortcut=True, dropRate=0.0):
super(WideResNet, self).__init__()
nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)]
assert (((depth - 4) % 6) == 0)
n = ((dept... |
def test():
global best_acc
net.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for (batch_idx, (inputs, targets)) in enumerate(testloader):
(inputs, targets) = (inputs.to(device), targets.to(device))
outputs = net(inputs)
loss = crite... |
class OnnxrtModel(Model):
def __init__(self, path: str) -> None:
super().__init__(path)
self._nc_model_instance: Optional[ONNXModel] = None
def domain(self) -> Domain:
try:
input_node_names = {node.name for node in self.nc_model_instance.graph().input}
node_names ... |
def merge_dict(user, default):
if (isinstance(user, dict) and isinstance(default, dict)):
for (k, v) in default.items():
if (k not in user):
user[k] = v
else:
user[k] = merge_dict(user[k], v)
return user |
class TestDummy(unittest.TestCase):
def test_encode(self):
commands = [['python', 'encode.py', '--users', '--items'], ['python', 'lr.py', 'data/dummy/X-ui.npz'], ['python', 'lr.py', '--folds', 'strong', 'data/dummy/X-ui.npz'], ['python', 'fm.py', 'data/dummy/X-ui.npz'], ['python', 'fm.py', '--folds', 'weak'... |
_args('v', 'is', 'is', 'is', 'is')
def im2col(g, input, kernel_size, dilation, padding, stride):
input_h = size(g, input, g.op('Constant', value_t=torch.tensor(2)))
input_w = size(g, input, g.op('Constant', value_t=torch.tensor(3)))
(stride_h, stride_w) = (stride[0], stride[1])
(padding_h, padding_w) = ... |
def plot(json_fname, results_fname, store_plots='', plots_to_latex=''):
name = '.'.join(json_fname.split('.')[:(- 1)])
data = json.loads(open(json_fname, 'r', encoding='utf-8').read())
fi = open(results_fname, 'r', encoding='utf-8')
truely_detected_and_truely_corrected = [[], []]
truely_detected_and... |
def process_single_fragment(fragment_id, color_files, depth_files, n_files, n_fragments, config):
if config['path_intrinsic']:
intrinsic = o3d.io.read_pinhole_camera_intrinsic(config['path_intrinsic'])
else:
intrinsic = o3d.camera.PinholeCameraIntrinsic(o3d.camera.PinholeCameraIntrinsicParameter... |
class AdvWeightPerturb(object):
def __init__(self, model, proxy, proxy_optim, gamma):
super(AdvWeightPerturb, self).__init__()
self.model = model
self.proxy = proxy
self.proxy_optim = proxy_optim
self.gamma = gamma
def calc_awp(self, inputs_adv, targets):
self.pro... |
class ParetoSetModel(torch.nn.Module):
def __init__(self, n_dim, n_obj):
super(ParetoSetModel, self).__init__()
self.n_dim = n_dim
self.n_obj = n_obj
self.fc1 = nn.Linear(self.n_obj, 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, self.n_dim)
def for... |
class Warmup(Scheduler):
def __init__(self, delta: float) -> None:
from bigdl.dllib.optim.optimizer import Warmup as BWarmup
self.scheduler = BWarmup(delta)
def get_scheduler(self) -> 'optimizer.Warmup':
return self.scheduler |
def line_bounding_2D_activation(x_minus, x_plus, y_minus, y_plus, tanh=True):
(kl, bl, ku, bu) = getConvenientGeneralActivationBound(y_minus, y_plus, 'sigmoid')
if tanh:
X_l = torch.tanh(x_minus)
X_u = torch.tanh(x_plus)
else:
X_l = x_minus
X_u = x_plus
I_l = (X_l >= 0).f... |
def test_text_envs():
env = gym.make('FrozenLake-v0')
video = VideoRecorder(env)
try:
env.reset()
video.capture_frame()
video.close()
finally:
os.remove(video.path) |
def data(ndata=100, baseline=1, freq=10, sigma=1.0, **kwargs):
t = (baseline * np.sort(np.random.rand(ndata)))
y = transit_model(t, freq, **kwargs)
dy = (sigma * np.ones_like(t))
y += (dy * np.random.randn(len(t)))
return (t, y, dy) |
def save_tokenizer(tokenizer, path):
with open(path, 'wb') as f:
pickle.dump(tokenizer, f)
print('tokenizer saved in {}'.format(path)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.