repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/finetune_src/reverie/model_navref.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from transformers import (PretrainedConfig, AutoTokenizer) from utils.misc import length2mask from reverie.vlnbert_navref import NavRefCMT def get_tokenizer(args): if args.tokenizer == 'bert': tokenizer = AutoTokenizer...
5,576
36.938776
98
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/finetune_src/reverie/vlnbert_navref.py
import torch import torch.nn as nn from transformers import BertPreTrainedModel from models.vilmodel_cmt import ( BertLayerNorm, BertEmbeddings, ImageEmbeddings, HistoryEmbeddings, LxmertEncoder, NextActionPrediction, ) class ObjectEmbeddings(nn.Module): """Construct the embeddings from image, spati...
7,456
45.60625
124
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/finetune_src/reverie/main_navref.py
import os import json import time import numpy as np from collections import defaultdict import torch from tensorboardX import SummaryWriter from utils.misc import set_random_seed from utils.logger import write_to_record_file, print_progress, timeSince from utils.distributed import init_distributed, is_default_gpu fr...
11,533
40.192857
148
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/finetune_src/reverie/agent.py
import json import os import sys import numpy as np import random import math import time from collections import defaultdict import torch import torch.nn as nn from torch import optim import torch.nn.functional as F from utils.misc import length2mask from r2r.agent_cmt import Seq2SeqCMTAgent from reverie.model_navr...
20,684
44.065359
140
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/finetune_src/utils/parser.py
import argparse import os import torch def parse_args(): parser = argparse.ArgumentParser(description="") parser.add_argument('--root_dir', type=str, default='/sequoia/data1/shichen/datasets') parser.add_argument( '--dataset', type=str, default='r2r', choices=['r2r', 'r4r', 'r2r_back', '...
7,866
43.954286
113
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/finetune_src/utils/misc.py
import random import numpy as np import torch def set_random_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) random.seed(seed) np.random.seed(seed) def length2mask(length, size=None): batch_size = len(length) size = int(max(length)) if size...
510
27.388889
84
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/finetune_src/utils/distributed.py
""" Distributed tools """ import os from pathlib import Path from pprint import pformat import pickle import torch import torch.distributed as dist def load_init_param(opts): """ Load parameters for the rendezvous distributed procedure """ # sync file if opts.output_dir != "": sync_dir = ...
4,908
28.751515
94
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/preprocess/precompute_img_features_vit.py
#!/usr/bin/env python3 ''' Script to precompute image features using a Pytorch ResNet CNN, using 36 discretized views at each viewpoint in 30 degree increments, and the provided camera WIDTH, HEIGHT and VFOV parameters. ''' import os import sys import MatterSim import argparse import numpy as np import jso...
6,102
32.168478
105
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/main_r2r.py
import os import sys import json import argparse import time from collections import defaultdict from easydict import EasyDict from tqdm import tqdm import torch import torch.nn.functional as F import torch.distributed as dist from transformers import AutoTokenizer, PretrainedConfig from transformers import AutoModel...
20,591
37.779661
129
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/main_r2r_image.py
import os import sys import json import argparse from collections import abc import time from collections import defaultdict from easydict import EasyDict from tqdm import tqdm import torch import torch.nn.functional as F from transformers import AutoTokenizer, PretrainedConfig from utils.logger import LOGGER, TB_LOGGE...
21,279
35.313993
88
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/optim/rangerlars.py
import torch, math from torch.optim.optimizer import Optimizer import itertools as it from .lookahead import * from .ralamb import * # RAdam + LARS + LookAHead # Lookahead implementation from https://github.com/lonePatient/lookahead_pytorch/blob/master/optimizer.py # RAdam + LARS implementation from https://gist.git...
519
33.666667
105
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/optim/radam.py
# from https://github.com/LiyuanLucasLiu/RAdam/blob/master/radam.py import math import torch from torch.optim.optimizer import Optimizer, required class RAdam(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): defaults = dict(lr=lr, betas=betas, eps=eps, weight...
8,100
37.57619
185
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/optim/misc.py
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. Misc lr helper """ from torch.optim import Adam, Adamax from .adamw import AdamW from .rangerlars import RangerLars def build_optimizer(model, opts): param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias',...
1,138
28.973684
65
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/optim/adamw.py
""" AdamW optimizer (weight decay fix) copied from hugginface (https://github.com/huggingface/transformers). """ import math from typing import Callable, Iterable, Tuple import torch from torch.optim import Optimizer class AdamW(Optimizer): """ Implements Adam algorithm with weight decay fix as introduced i...
4,887
42.256637
116
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/optim/ralamb.py
import torch, math from torch.optim.optimizer import Optimizer # RAdam + LARS class Ralamb(Optimizer): def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay) self.buffer = [[None, None, None] for in...
4,050
39.51
181
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/optim/lookahead.py
# Lookahead implementation from https://github.com/rwightman/pytorch-image-models/blob/master/timm/optim/lookahead.py """ Lookahead Optimizer Wrapper. Implementation modified from: https://github.com/alphadl/lookahead.pytorch Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610...
4,076
40.602041
117
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/utils/misc.py
import random import numpy as np from typing import Tuple, Union, Dict, Any import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from .distributed import init_distributed from .logger import LOGGER def set_random_seed(seed): random.seed(seed) np.random.s...
2,165
27.5
89
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/utils/save.py
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. saving utilities """ import json import os import torch def save_training_meta(args): os.makedirs(os.path.join(args.output_dir, 'logs'), exist_ok=True) os.makedirs(os.path.join(args.output_dir, 'ckpts'), exist_ok=True) with open(os...
1,606
33.191489
90
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/utils/distributed.py
""" Distributed tools """ import os from pathlib import Path from pprint import pformat import pickle import torch import torch.distributed as dist def load_init_param(opts): """ Load parameters for the rendezvous distributed procedure """ # sync file if opts.output_dir != "": sync_dir = ...
4,851
29.136646
94
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/data/r2r_tasks.py
import random import math import numpy as np import torch from torch.utils.data import Dataset from torch.nn.utils.rnn import pad_sequence from .common import pad_tensors, gen_seq_masks ############### Masked Language Modeling ############### def random_word(tokens, vocab_range, mask): """ Masking some rando...
24,879
40.605351
112
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/data/image_loader.py
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. A prefetch loader to speedup data loading Modified from Nvidia Deep Learning Examples (https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch). """ import random from typing import List, Dict, Tuple, Union, Iterator import torch from ...
5,236
29.447674
86
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/data/common.py
import numpy as np import torch def pad_tensors(tensors, lens=None, pad=0): """B x [T, ...]""" if lens is None: lens = [t.size(0) for t in tensors] max_len = max(lens) bs = len(tensors) hid = list(tensors[0].size()[1:]) size = [bs, max_len] + hid dtype = tensors[0].dtype outpu...
810
26.033333
73
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/data/image_tasks.py
import random import numpy as np import torch from torch.nn.utils.rnn import pad_sequence from .data import pad_tensors, gen_seq_masks from .mlm import random_word, MlmDataset from .mrc import _get_img_mask, MrcDataset from .sap import SapDataset from .sar import SarDataset from .sprel import SprelDataset from .itm i...
18,514
35.375246
88
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/data/image_data.py
""" R2R-style dataset: load images """ import os import json import jsonlines import numpy as np import h5py import math import lmdb import networkx as nx from PIL import Image import torch from timm.data.transforms_factory import create_transform from .data import angle_feature, softmax, MultiStepNavData HEIGHT = ...
9,046
32.63197
88
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/data/loader.py
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. A prefetch loader to speedup data loading Modified from Nvidia Deep Learning Examples (https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch). """ import random from typing import List, Dict, Tuple, Union, Iterator import torch from...
5,220
30.642424
103
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/model/vilmodel.py
import json import logging import math import os import sys from io import open from typing import Callable, List, Tuple import numpy as np import copy import torch from torch import nn from torch import Tensor, dtype from transformers import BertPreTrainedModel from transformers.modeling_utils import get_parameter_d...
32,060
43.161157
137
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/model/vision_transformer.py
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 The official jax code is released and available at https://github.com/google-research/vision_transformer ...
33,731
45.785021
140
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/model/image_vilmodel.py
import json import logging import math import os import sys from io import open from typing import Callable, List, Tuple import numpy as np import copy import torch from torch import nn from torch import Tensor, device, dtype from transformers import BertPreTrainedModel from .vision_transformer import vit_base_patch...
9,606
44.747619
137
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/model/image_pretrain.py
from collections import defaultdict import torch import torch.nn as nn import torch.nn.functional as F from transformers import BertPreTrainedModel from .vilmodel import BertLayerNorm, BertOnlyMLMHead from .pretrain import (NextActionPrediction, NextActionRegression, SpatialRelRegression, Reg...
10,924
51.272727
128
py
Diagnose_VLN
Diagnose_VLN-master/rxr/model/VLN-HAMT/pretrain_src/model/pretrain_cmt.py
from collections import defaultdict import torch import torch.nn as nn import torch.nn.functional as F from transformers import BertPreTrainedModel from .vilmodel import BertLayerNorm, BertOnlyMLMHead from .vilmodel import NavPreTrainedModel class NextActionPrediction(nn.Module): def __init__(self, hidden_size...
12,828
47.779468
129
py
GNG-ODE
GNG-ODE-main/src/models/gng_ode.py
import math from rdflib import Graph import torch as th import torch.nn as nn import torch.nn.functional as F import dgl import dgl.ops as F import dgl.function as fn from dgl.nn.pytorch import GraphConv, GATConv from torchdiffeq import odeint from torch.autograd import Variable class GraphGRUODE(nn.Module): ...
12,193
38.71987
152
py
GNG-ODE
GNG-ODE-main/src/scripts/main_ode.py
import argparse import sys import torch import random import numpy as np import os def seed_torch(seed=42): seed = int(seed) random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed)...
4,932
28.538922
157
py
GNG-ODE
GNG-ODE-main/src/utils/train.py
import time import numpy as np import torch as th from sklearn.metrics import accuracy_score from torch import nn, optim from tqdm import tqdm # ignore weight decay for parameters in bias, batch norm and activation def fix_weight_decay(model): decay = [] no_decay = [] for name, param in model.named_param...
4,717
34.208955
156
py
GNG-ODE
GNG-ODE-main/src/utils/data/collate.py
from collections import Counter import numpy as np import torch as th import torch.nn.functional as F import dgl import pickle def label_last(g, last_nid): is_last = th.zeros(g.num_nodes(), dtype=th.int32) is_last[last_nid] = 1 g.ndata['last'] = is_last return g def label_last_ccs(g, last_nid): f...
4,868
31.898649
150
py
GBST
GBST-master/gbst_src/rabit/python/rabit.py
""" Reliable Allreduce and Broadcast Library. Author: Tianqi Chen """ # pylint: disable=unused-argument,invalid-name,global-statement,dangerous-default-value, import pickle import ctypes import os import platform import sys import warnings import numpy as np # version information about the doc __version__ = '1.0' _L...
10,642
28.158904
89
py
GBST
GBST-master/gbst_src/rabit/doc/conf.py
# -*- coding: utf-8 -*- # # documentation build configuration file, created by # sphinx-quickstart on Thu Jul 23 19:40:08 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All confi...
6,362
33.394595
88
py
GBST
GBST-master/gbst_src/tests/ci_build/insert_vcomp140.py
import sys import re import zipfile import glob if len(sys.argv) != 2: print('Usage: {} [wheel]'.format(sys.argv[0])) sys.exit(1) vcomp140_path = 'C:\\Windows\\System32\\vcomp140.dll' for wheel_path in sorted(glob.glob(sys.argv[1])): m = re.search(r'xgboost-(.*)-py2.py3', wheel_path) assert m ver...
479
24.263158
91
py
GBST
GBST-master/gbst_src/tests/ci_build/tidy.py
#!/usr/bin/env python import subprocess import yaml import json from multiprocessing import Pool, cpu_count import shutil import os import sys import re import argparse def call(args): '''Subprocess run wrapper.''' completed = subprocess.run(args, stdout=subprocess.PIPE, ...
9,066
34.280156
76
py
GBST
GBST-master/gbst_src/tests/python/test_dmatrix.py
# -*- coding: utf-8 -*- import numpy as np import xgboost as xgb import unittest import scipy.sparse from scipy.sparse import rand rng = np.random.RandomState(1) dpath = 'demo/data/' rng = np.random.RandomState(1994) class TestDMatrix(unittest.TestCase): def test_dmatrix_numpy_init(self): data = np.rand...
6,189
34.988372
80
py
GBST
GBST-master/gbst_src/tests/python/test_interaction_constraints.py
# -*- coding: utf-8 -*- import numpy as np import xgboost import unittest import testing as tm import pytest dpath = 'demo/data/' rng = np.random.RandomState(1994) class TestInteractionConstraints(unittest.TestCase): def run_interaction_constraints(self, tree_method): x1 = np.random.normal(loc=1.0, scale...
3,396
35.526882
78
py
GBST
GBST-master/gbst_src/tests/python/test_plotting.py
# -*- coding: utf-8 -*- import numpy as np import xgboost as xgb import testing as tm import unittest import pytest try: import matplotlib matplotlib.use('Agg') from matplotlib.axes import Axes from graphviz import Source except ImportError: pass pytestmark = pytest.mark.skipif(**tm.no_matplotli...
2,422
30.467532
72
py
GBST
GBST-master/gbst_src/tests/python/test_tracker.py
import time from xgboost import RabitTracker import xgboost as xgb def test_rabit_tracker(): tracker = RabitTracker(hostIP='127.0.0.1', nslave=1) tracker.start(1) rabit_env = [ str.encode('DMLC_TRACKER_URI=127.0.0.1'), str.encode('DMLC_TRACKER_PORT=9091'), str.encode('DMLC_TASK_ID...
460
24.611111
56
py
GBST
GBST-master/gbst_src/tests/python/test_ranking.py
import numpy as np from scipy.sparse import csr_matrix import xgboost import os import unittest import itertools import shutil import urllib.request import zipfile def test_ranking_with_unweighted_data(): Xrow = np.array([1, 2, 6, 8, 11, 14, 16, 17]) Xcol = np.array([0, 0, 1, 1, 2, 2, 3, 3]) X = csr_m...
7,180
38.674033
117
py
GBST
GBST-master/gbst_src/tests/python/test_with_sklearn.py
import numpy as np import xgboost as xgb import testing as tm import tempfile import os import shutil import pytest rng = np.random.RandomState(1994) pytestmark = pytest.mark.skipif(**tm.no_sklearn()) class TemporaryDirectory(object): """Context manager for tempfile.mkdtemp()""" def __enter__(self): ...
25,149
35.031519
81
py
GBST
GBST-master/gbst_src/tests/python/test_basic.py
# -*- coding: utf-8 -*- import sys from contextlib import contextmanager try: # python 2 from StringIO import StringIO except ImportError: # python 3 from io import StringIO import numpy as np import xgboost as xgb import unittest import json from pathlib import Path dpath = 'demo/data/' rng = np.rando...
11,472
34.853125
113
py
GBST
GBST-master/gbst_src/tests/python/test_dt.py
# -*- coding: utf-8 -*- import unittest import pytest import testing as tm import xgboost as xgb try: import datatable as dt import pandas as pd except ImportError: pass pytestmark = pytest.mark.skipif( tm.no_dt()['condition'] or tm.no_pandas()['condition'], reason=tm.no_dt()['reason'] + ' or ' +...
1,592
29.634615
68
py
GBST
GBST-master/gbst_src/tests/python/test_pickling.py
import pickle import numpy as np import xgboost as xgb import os import unittest kRows = 100 kCols = 10 def generate_data(): X = np.random.randn(kRows, kCols) y = np.random.randn(kRows) return X, y class TestPickling(unittest.TestCase): def run_model_pickling(self, xgb_params): X, y = gene...
1,349
21.5
58
py
GBST
GBST-master/gbst_src/tests/python/test_with_pandas.py
# -*- coding: utf-8 -*- import numpy as np import xgboost as xgb import testing as tm import unittest import pytest try: import pandas as pd except ImportError: pass pytestmark = pytest.mark.skipif(**tm.no_pandas()) dpath = 'demo/data/' rng = np.random.RandomState(1994) class TestPandas(unittest.TestCase...
7,788
38.338384
77
py
GBST
GBST-master/gbst_src/tests/python/testing.py
# coding: utf-8 from xgboost.compat import SKLEARN_INSTALLED, PANDAS_INSTALLED, DT_INSTALLED from xgboost.compat import CUDF_INSTALLED, DASK_INSTALLED def no_sklearn(): return {'condition': not SKLEARN_INSTALLED, 'reason': 'Scikit-Learn is not installed'} def no_dask(): return {'condition': not ...
1,492
24.741379
76
py
GBST
GBST-master/gbst_src/tests/python/test_with_dask.py
import testing as tm import pytest import xgboost as xgb import sys import numpy as np if sys.platform.startswith("win"): pytest.skip("Skipping dask tests on Windows", allow_module_level=True) pytestmark = pytest.mark.skipif(**tm.no_dask()) try: from distributed.utils_test import client, loop, cluster_fixtur...
3,449
26.6
74
py
GBST
GBST-master/gbst_src/tests/python/test_openmp.py
# -*- coding: utf-8 -*- import xgboost as xgb import unittest import numpy as np class TestOMP(unittest.TestCase): def test_omp(self): dpath = 'demo/data/' dtrain = xgb.DMatrix(dpath + 'agaricus.txt.train') dtest = xgb.DMatrix(dpath + 'agaricus.txt.test') param = {'booster': 'gbtr...
2,357
30.44
85
py
GBST
GBST-master/gbst_src/tests/python/test_eval_metrics.py
import xgboost as xgb import testing as tm import numpy as np import unittest import pytest rng = np.random.RandomState(1337) class TestEvalMetrics(unittest.TestCase): xgb_params_01 = { 'verbosity': 0, 'nthread': 1, 'eval_metric': 'error' } xgb_params_02 = { 'verbosity': ...
4,075
37.093458
78
py
GBST
GBST-master/gbst_src/tests/python/test_training_continuation.py
import xgboost as xgb import testing as tm import numpy as np import unittest import pytest rng = np.random.RandomState(1337) class TestTrainingContinuation(unittest.TestCase): num_parallel_tree = 3 def generate_parameters(self, use_json): xgb_params_01_binary = { 'nthread': 1, }...
6,555
38.02381
76
py
GBST
GBST-master/gbst_src/tests/python/test_linear.py
from __future__ import print_function import numpy as np import testing as tm import unittest import pytest import xgboost as xgb try: from sklearn.linear_model import ElasticNet from sklearn.preprocessing import scale from regression_test_utilities import run_suite, parameter_combinations except ImportE...
3,397
36.755556
79
py
GBST
GBST-master/gbst_src/tests/python/test_shap.py
# -*- coding: utf-8 -*- import numpy as np import xgboost as xgb import unittest import itertools import re import scipy import scipy.special dpath = 'demo/data/' rng = np.random.RandomState(1994) class TestSHAP(unittest.TestCase): def test_feature_importances(self): data = np.random.randn(100, 5) ...
10,198
38.839844
104
py
GBST
GBST-master/gbst_src/tests/python/test_tree_regularization.py
import numpy as np import unittest import xgboost as xgb from numpy.testing import assert_approx_equal train_data = xgb.DMatrix(np.array([[1]]), label=np.array([1])) class TestTreeRegularization(unittest.TestCase): def test_alpha(self): params = { 'tree_method': 'exact', 'verbosity': 0, ...
1,843
27.8125
78
py
GBST
GBST-master/gbst_src/tests/python/test_basic_models.py
import numpy as np import xgboost as xgb import unittest import os import json dpath = 'demo/data/' dtrain = xgb.DMatrix(dpath + 'agaricus.txt.train') dtest = xgb.DMatrix(dpath + 'agaricus.txt.test') rng = np.random.RandomState(1994) class TestModels(unittest.TestCase): def test_glm(self): param = {'ver...
9,141
39.631111
107
py
GBST
GBST-master/gbst_src/tests/python/test_monotone_constraints.py
import numpy as np import xgboost as xgb import unittest import testing as tm import pytest dpath = 'demo/data/' def is_increasing(y): return np.count_nonzero(np.diff(y) < 0.0) == 0 def is_decreasing(y): return np.count_nonzero(np.diff(y) > 0.0) == 0 def is_correctly_constrained(learner): n = 100 ...
4,196
33.121951
79
py
GBST
GBST-master/gbst_src/tests/python/test_early_stopping.py
import xgboost as xgb import testing as tm import numpy as np import unittest import pytest rng = np.random.RandomState(1994) class TestEarlyStopping(unittest.TestCase): @pytest.mark.skipif(**tm.no_sklearn()) def test_early_stopping_nonparallel(self): from sklearn.datasets import load_digits ...
4,319
38.633028
90
py
GBST
GBST-master/gbst_src/tests/python/test_updaters.py
import testing as tm import unittest import pytest import xgboost as xgb import numpy as np try: from regression_test_utilities import run_suite, parameter_combinations, \ assert_results_non_increasing except ImportError: None class TestUpdaters(unittest.TestCase): @pytest.mark.skipif(**tm.no_skl...
3,102
39.298701
78
py
GBST
GBST-master/gbst_src/tests/python/test_parse_tree.py
import xgboost as xgb import unittest import numpy as np import pytest import testing as tm pytestmark = pytest.mark.skipif(**tm.no_pandas()) dpath = 'demo/data/' rng = np.random.RandomState(1994) class TestTreesToDataFrame(unittest.TestCase): def build_model(self, max_depth, num_round): dtrain = xgb...
1,834
34.288462
76
py
GBST
GBST-master/gbst_src/tests/python/regression_test_utilities.py
from __future__ import print_function import glob import itertools as it import numpy as np import os import sys import xgboost as xgb try: from sklearn import datasets from sklearn.preprocessing import scale except ImportError: None class Dataset: def __init__(self, name, get_dataset, objective, me...
5,046
29.587879
104
py
GBST
GBST-master/gbst_src/tests/python-gpu/load_pickle.py
'''Loading a pickled model generated by test_pickling.py, only used by `test_gpu_with_dask.py`''' import unittest import os import xgboost as xgb import json from test_gpu_pickling import build_dataset, model_path, load_pickle class TestLoadPickle(unittest.TestCase): def test_load_pkl(self): '''Test whet...
1,413
34.35
75
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_monotonic_constraints.py
from __future__ import print_function import numpy as np from sklearn.datasets import make_regression import unittest import pytest import xgboost as xgb rng = np.random.RandomState(1994) def non_decreasing(L): return all((x - y) < 0.001 for x, y in zip(L, L[1:])) def non_increasing(L): return all((y - ...
1,172
23.957447
78
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_gpu_updaters.py
import numpy as np import sys import unittest import pytest import xgboost sys.path.append("tests/python") from regression_test_utilities import run_suite, parameter_combinations, \ assert_results_non_increasing def assert_gpu_results(cpu_results, gpu_results): for cpu_res, gpu_res in zip(cpu_results, gpu_re...
3,390
35.858696
99
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_large_sizes.py
from __future__ import print_function import sys import time import pytest sys.path.append("../../tests/python") import xgboost as xgb import numpy as np import unittest def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) sys.stderr.flush() print(*args, file=sys.stdout, **kwargs) sy...
2,863
31.91954
81
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_gpu_with_sklearn.py
import xgboost as xgb import pytest import sys import numpy as np sys.path.append("tests/python") import testing as tm pytestmark = pytest.mark.skipif(**tm.no_sklearn()) rng = np.random.RandomState(1994) def test_gpu_binary_classification(): from sklearn.datasets import load_digits from sklearn.model_selec...
999
30.25
79
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_gpu_training_continuation.py
import unittest import numpy as np import xgboost as xgb import json rng = np.random.RandomState(1994) class TestGPUTrainingContinuation(unittest.TestCase): def run_training_continuation(self, use_json): kRows = 64 kCols = 32 X = np.random.randn(kRows, kCols) y = np.random.randn(k...
2,179
36.586207
78
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_gpu_pickling.py
'''Test model IO with pickle.''' import pickle import unittest import numpy as np import subprocess import os import json import xgboost as xgb from xgboost import XGBClassifier model_path = './model.pkl' def build_dataset(): N = 10 x = np.linspace(0, N*N, N*N) x = x.reshape((N, N)) y = np.linspace(0...
3,826
27.774436
78
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_gpu_ranking.py
import numpy as np from scipy.sparse import csr_matrix import xgboost import os import math import unittest import itertools import shutil import urllib.request import zipfile class TestRanking(unittest.TestCase): @classmethod def setUpClass(cls): """ Download and setup the test fixtures ...
5,913
40.069444
98
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_gpu_prediction.py
from __future__ import print_function import numpy as np import unittest import xgboost as xgb import pytest rng = np.random.RandomState(1994) @pytest.mark.gpu class TestGPUPredict(unittest.TestCase): def test_predict(self): iterations = 10 np.random.seed(1) test_num_rows = [10, 1000, 50...
4,499
39.178571
79
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_from_columnar.py
import numpy as np import xgboost as xgb import sys import pytest sys.path.append("tests/python") import testing as tm def dmatrix_from_cudf(input_type, missing=np.NAN): '''Test constructing DMatrix from cudf''' import cudf import pandas as pd kRows = 80 kCols = 3 na = np.random.randn(kRows,...
2,688
29.213483
75
py
GBST
GBST-master/gbst_src/tests/python-gpu/test_gpu_with_dask.py
import sys import pytest import numpy as np import unittest if sys.platform.startswith("win"): pytest.skip("Skipping dask tests on Windows", allow_module_level=True) try: import dask.dataframe as dd from xgboost import dask as dxgb from dask_cuda import LocalCUDACluster from dask.distributed impor...
3,550
36.776596
74
py
GBST
GBST-master/gbst_src/tests/distributed/test_basic.py
#!/usr/bin/python import xgboost as xgb # Always call this before using distributed module xgb.rabit.init() # Load file, file will be automatically sharded in distributed mode. dtrain = xgb.DMatrix('../../demo/data/agaricus.txt.train') dtest = xgb.DMatrix('../../demo/data/agaricus.txt.test') # Specify parameters via...
1,074
34.833333
84
py
GBST
GBST-master/gbst_src/tests/distributed/distributed_gpu.py
"""Distributed GPU tests.""" import sys import time import xgboost as xgb import os def run_test(name, params_fun): """Runs a distributed GPU test.""" # Always call this before using distributed module xgb.rabit.init() rank = xgb.rabit.get_rank() world = xgb.rabit.get_world_size() # Load file...
2,703
29.044444
88
py
GBST
GBST-master/gbst_src/tests/distributed/test_issue3402.py
#!/usr/bin/python import xgboost as xgb import numpy as np xgb.rabit.init() X = [ [15.00,28.90,29.00,3143.70,0.00,0.10,69.90,90.00,13726.07,0.00,2299.70,0.00,0.05, 4327.03,0.00,24.00,0.18,3.00,0.41,3.77,0.00,0.00,4.00,0.00,150.92,0.00,2.00,0.00, 0.01,138.00,1.00,0.02,69.90,0.00,0.83,5.00,0.01,0.12,47.30,0.00,...
5,298
65.2375
91
py
GBST
GBST-master/gbst_src/tests/benchmark/benchmark_linear.py
#pylint: skip-file import sys, argparse import xgboost as xgb import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split import time import ast rng = np.random.RandomState(1994) def run_benchmark(args): try: dtest = xgb.DMatrix('dtest.dm') ...
2,921
40.742857
143
py
GBST
GBST-master/gbst_src/tests/benchmark/benchmark_tree.py
"""Run benchmark on the tree booster.""" import argparse import ast import time import numpy as np import xgboost as xgb RNG = np.random.RandomState(1994) def run_benchmark(args): """Runs the benchmark.""" try: dtest = xgb.DMatrix('dtest.dm') dtrain = xgb.DMatrix('dtrain.dm') if no...
3,021
33.735632
100
py
GBST
GBST-master/gbst_src/demo/multiclass_classification/train.py
#!/usr/bin/python from __future__ import division import numpy as np import xgboost as xgb # label need to be 0 to num_class -1 data = np.loadtxt('./dermatology.data', delimiter=',', converters={33: lambda x:int(x == '?'), 34: lambda x:int(x) - 1}) sz = data.shape train = data[:int(sz[0] * 0.7), :] test = d...
1,572
29.25
73
py
GBST
GBST-master/gbst_src/demo/gpu_acceleration/memory.py
import xgboost as xgb import numpy as np import time import pickle import GPUtil n = 10000 m = 1000 X = np.random.random((n, m)) y = np.random.random(n) param = {'objective': 'binary:logistic', 'tree_method': 'gpu_hist' } iterations = 5 dtrain = xgb.DMatrix(X, label=y) # High memory usage # active ...
1,186
21.826923
97
py
GBST
GBST-master/gbst_src/demo/gpu_acceleration/cover_type.py
import xgboost as xgb import numpy as np from sklearn.datasets import fetch_covtype from sklearn.model_selection import train_test_split import time # Fetch dataset using sklearn cov = fetch_covtype() X = cov.data y = cov.target # Create 0.75/0.25 train/test split X_train, X_test, y_train, y_test = train_test_split(X...
1,350
31.95122
90
py
GBST
GBST-master/gbst_src/demo/dask/sklearn_cpu_training.py
'''Dask interface demo: Use scikit-learn regressor interface with CPU histogram tree method.''' from dask.distributed import Client from dask.distributed import LocalCluster from dask import array as da import xgboost def main(client): # generate some random data for demonstration n = 100 m = 10000 p...
1,182
28.575
74
py
GBST
GBST-master/gbst_src/demo/dask/sklearn_gpu_training.py
'''Dask interface demo: Use scikit-learn regressor interface with GPU histogram tree method.''' from dask.distributed import Client # It's recommended to use dask_cuda for GPU assignment from dask_cuda import LocalCUDACluster from dask import array as da import xgboost def main(client): # generate some random d...
1,302
29.302326
73
py
GBST
GBST-master/gbst_src/demo/dask/gpu_training.py
from dask_cuda import LocalCUDACluster from dask.distributed import Client from dask import array as da import xgboost as xgb from xgboost.dask import DaskDMatrix def main(client): # generate some random data for demonstration m = 100000 n = 100 X = da.random.random(size=(m, n), chunks=100) y = da...
1,699
35.170213
79
py
GBST
GBST-master/gbst_src/demo/dask/cpu_training.py
import xgboost as xgb from xgboost.dask import DaskDMatrix from dask.distributed import Client from dask.distributed import LocalCluster from dask import array as da def main(client): # generate some random data for demonstration m = 100000 n = 100 X = da.random.random(size=(m, n), chunks=100) y =...
1,462
33.023256
73
py
GBST
GBST-master/gbst_src/demo/guide-python/predict_first_ntree.py
#!/usr/bin/python import numpy as np import xgboost as xgb ### load data in do training dtrain = xgb.DMatrix('../data/agaricus.txt.train') dtest = xgb.DMatrix('../data/agaricus.txt.test') param = {'max_depth':2, 'eta':1, 'silent':1, 'objective':'binary:logistic'} watchlist = [(dtest, 'eval'), (dtrain, 'train')] num_ro...
776
36
83
py
GBST
GBST-master/gbst_src/demo/guide-python/external_memory.py
#!/usr/bin/python import numpy as np import scipy.sparse import xgboost as xgb ### simple example for using external memory version # this is the only difference, add a # followed by a cache prefix name # several cache file with the prefix will be generated # currently only support convert from libsvm file dtrain = x...
886
33.115385
107
py
GBST
GBST-master/gbst_src/demo/guide-python/generalized_linear_model.py
#!/usr/bin/python import xgboost as xgb ## # this script demonstrate how to fit generalized linear model in xgboost # basically, we are using linear model, instead of tree for our boosters ## dtrain = xgb.DMatrix('../data/agaricus.txt.train') dtest = xgb.DMatrix('../data/agaricus.txt.test') # change booster to gbline...
1,231
38.741935
111
py
GBST
GBST-master/gbst_src/demo/guide-python/custom_rmsle.py
'''Demo for defining customized metric and objective. Notice that for simplicity reason weight is not used in following example. In this script, we implement the Squared Log Error (SLE) objective and RMSLE metric as customized functions, then compare it with native implementation in XGBoost. See doc/tutorials/custom_...
5,845
31.477778
89
py
GBST
GBST-master/gbst_src/demo/guide-python/sklearn_examples.py
#!/usr/bin/python ''' Created on 1 Apr 2015 @author: Jamie Hall ''' import pickle import xgboost as xgb import numpy as np from sklearn.model_selection import KFold, train_test_split, GridSearchCV from sklearn.metrics import confusion_matrix, mean_squared_error from sklearn.datasets import load_iris, load_digits, loa...
2,431
30.584416
73
py
GBST
GBST-master/gbst_src/demo/guide-python/custom_objective.py
#!/usr/bin/python import numpy as np import xgboost as xgb ### # advanced: customized loss function # print('start running example to used customized objective function') dtrain = xgb.DMatrix('../data/agaricus.txt.train') dtest = xgb.DMatrix('../data/agaricus.txt.test') # note: for customized objective function, we l...
1,913
37.28
78
py
GBST
GBST-master/gbst_src/demo/guide-python/gamma_regression.py
#!/usr/bin/python import xgboost as xgb import numpy as np # this script demonstrates how to fit gamma regression model (with log link function) # in xgboost, before running the demo you need to generate the autoclaims dataset # by running gen_autoclaims.R located in xgboost/demo/data. data = np.genfromtxt('../dat...
1,067
40.076923
99
py
GBST
GBST-master/gbst_src/demo/guide-python/boost_from_prediction.py
#!/usr/bin/python import numpy as np import xgboost as xgb dtrain = xgb.DMatrix('../data/agaricus.txt.train') dtest = xgb.DMatrix('../data/agaricus.txt.test') watchlist = [(dtest, 'eval'), (dtrain, 'train')] ### # advanced: start from a initial base prediction # print ('start running example to start from a initial pr...
996
38.88
103
py
GBST
GBST-master/gbst_src/demo/guide-python/evals_result.py
## # This script demonstrate how to access the eval metrics in xgboost ## import xgboost as xgb dtrain = xgb.DMatrix('../data/agaricus.txt.train', silent=True) dtest = xgb.DMatrix('../data/agaricus.txt.test', silent=True) param = [('max_depth', 2), ('objective', 'binary:logistic'), ('eval_metric', 'logloss'), ('eval...
938
29.290323
114
py
GBST
GBST-master/gbst_src/demo/guide-python/sklearn_parallel.py
import os if __name__ == "__main__": # NOTE: on posix systems, this *has* to be here and in the # `__name__ == "__main__"` clause to run XGBoost in parallel processes # using fork, if XGBoost was built with OpenMP support. Otherwise, if you # build XGBoost without OpenMP support, you can use fork, whic...
1,301
35.166667
78
py
GBST
GBST-master/gbst_src/demo/guide-python/predict_leaf_indices.py
#!/usr/bin/python import xgboost as xgb ### load data in do training dtrain = xgb.DMatrix('../data/agaricus.txt.train') dtest = xgb.DMatrix('../data/agaricus.txt.test') param = {'max_depth':2, 'eta':1, 'silent':1, 'objective':'binary:logistic'} watchlist = [(dtest, 'eval'), (dtrain, 'train')] num_round = 3 bst = xgb.t...
637
30.9
75
py
GBST
GBST-master/gbst_src/demo/guide-python/basic_walkthrough.py
#!/usr/bin/python import numpy as np import scipy.sparse import pickle import xgboost as xgb ### simple example # load file from text file, also binary buffer generated by xgboost dtrain = xgb.DMatrix('../data/agaricus.txt.train') dtest = xgb.DMatrix('../data/agaricus.txt.test') # specify parameters via map, definiti...
2,719
32.580247
111
py
GBST
GBST-master/gbst_src/demo/guide-python/sklearn_evals_result.py
## # This script demonstrate how to access the xgboost eval metrics by using sklearn ## import xgboost as xgb import numpy as np from sklearn.datasets import make_hastie_10_2 X, y = make_hastie_10_2(n_samples=2000, random_state=42) # Map labels from {-1, 1} to {0, 1} labels, y = np.unique(y, return_inverse=True) X...
1,218
26.704545
82
py
GBST
GBST-master/gbst_src/demo/guide-python/cross_validation.py
#!/usr/bin/python import numpy as np import xgboost as xgb ### load data in do training dtrain = xgb.DMatrix('../data/agaricus.txt.train') param = {'max_depth':2, 'eta':1, 'silent':1, 'objective':'binary:logistic'} num_round = 2 print('running cross validation') # do cross validation, this will print result out as # ...
2,329
35.984127
75
py
GBST
GBST-master/gbst_src/demo/rank/rank.py
#!/usr/bin/python import xgboost as xgb from xgboost import DMatrix from sklearn.datasets import load_svmlight_file # This script demonstrate how to do ranking with xgboost.train x_train, y_train = load_svmlight_file("mq2008.train") x_valid, y_valid = load_svmlight_file("mq2008.vali") x_test, y_test = load_svmlight_...
1,302
30.02381
65
py