repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
xgboost | xgboost-master/demo/CLI/regression/mapfeat.py | #!/usr/bin/env python3
fo = open('machine.txt', 'w')
cnt = 6
fmap = {}
for l in open('machine.data'):
arr = l.split(',')
fo.write(arr[8])
for i in range(0, 6):
fo.write(' %d:%s' % (i, arr[i + 2]))
if arr[0] not in fmap:
fmap[arr[0]] = cnt
cnt += 1
fo.write(' %d:1' % fmap[a... | 726 | 20.382353 | 76 | py |
xgboost | xgboost-master/demo/CLI/regression/mknfold.py | #!/usr/bin/env python3
import random
import sys
if len(sys.argv) < 2:
print('Usage:<filename> <k> [nfold = 5]')
exit(0)
random.seed(10)
k = int(sys.argv[2])
if len(sys.argv) > 3:
nfold = int(sys.argv[3])
else:
nfold = 5
fi = open(sys.argv[1], 'r')
ftr = open(sys.argv[1] + '.train', 'w')
fte = open(... | 487 | 15.266667 | 45 | py |
xgboost | xgboost-master/demo/guide-python/predict_first_ntree.py | """
Demo for prediction using number of trees
=========================================
"""
import os
import numpy as np
from sklearn.datasets import load_svmlight_file
import xgboost as xgb
CURRENT_DIR = os.path.dirname(__file__)
train = os.path.join(CURRENT_DIR, "../data/agaricus.txt.train")
test = os.path.join(CU... | 1,942 | 30.852459 | 87 | py |
xgboost | xgboost-master/demo/guide-python/external_memory.py | """
Experimental support for external memory
========================================
This is similar to the one in `quantile_data_iterator.py`, but for external memory
instead of Quantile DMatrix. The feature is not ready for production use yet.
.. versionadded:: 1.5.0
See :doc:`the tutorial </tutorials/exter... | 3,179 | 30.8 | 89 | py |
xgboost | xgboost-master/demo/guide-python/quantile_data_iterator.py | """
Demo for using data iterator with Quantile DMatrix
==================================================
.. versionadded:: 1.2.0
The demo that defines a customized iterator for passing batches of data into
:py:class:`xgboost.QuantileDMatrix` and use this ``QuantileDMatrix`` for
training. The feature is used pri... | 3,624 | 28.713115 | 86 | py |
xgboost | xgboost-master/demo/guide-python/callbacks.py | '''
Demo for using and defining callback functions
==============================================
.. versionadded:: 1.3.0
'''
import argparse
import os
import tempfile
import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_... | 4,631 | 33.311111 | 92 | py |
xgboost | xgboost-master/demo/guide-python/generalized_linear_model.py | """
Demo for GLM
============
"""
import os
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
##
CURRENT_DIR = os.path.dirname(__file__)
dtrain = xgb.DMatrix(
os.path.join(CURRENT_DIR, "../da... | 1,425 | 26.423077 | 80 | py |
xgboost | xgboost-master/demo/guide-python/learning_to_rank.py | """
Getting started with learning to rank
=====================================
.. versionadded:: 2.0.0
This is a demonstration of using XGBoost for learning to rank tasks using the
MSLR_10k_letor dataset. For more infomation about the dataset, please visit its
`description page <https://www.microsoft.com/en-us/res... | 6,345 | 28.516279 | 87 | py |
xgboost | xgboost-master/demo/guide-python/continuation.py | """
Demo for training continuation
==============================
"""
import os
import pickle
import tempfile
from sklearn.datasets import load_breast_cancer
import xgboost
def training_continuation(tmpdir: str, use_pickle: bool) -> None:
"""Basic training continuation."""
# Train 128 iterations in 1 sessi... | 3,807 | 33.306306 | 88 | py |
xgboost | xgboost-master/demo/guide-python/custom_rmsle.py | """
Demo for defining a custom regression objective and metric
==========================================================
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... | 6,450 | 31.094527 | 86 | py |
xgboost | xgboost-master/demo/guide-python/cat_in_the_dat.py | """
Train XGBoost with cat_in_the_dat dataset
=========================================
A simple demo for categorical data support using dataset from Kaggle categorical data
tutorial.
The excellent tutorial is at:
https://www.kaggle.com/shahules/an-overview-of-encoding-techniques
And the data can be found at:
https:... | 3,744 | 28.722222 | 86 | py |
xgboost | xgboost-master/demo/guide-python/sklearn_examples.py | '''
Collection of examples for using sklearn interface
==================================================
For an introduction to XGBoost's scikit-learn estimator interface, see
:doc:`/python/sklearn_estimator`.
Created on 1 Apr 2015
@author: Jamie Hall
'''
import pickle
import numpy as np
from sklearn.datasets impo... | 2,644 | 32.910256 | 79 | py |
xgboost | xgboost-master/demo/guide-python/update_process.py | """
Demo for using `process_type` with `prune` and `refresh`
========================================================
Modifying existing trees is not a well established use for XGBoost, so feel free to
experiment.
"""
import numpy as np
from sklearn.datasets import fetch_california_housing
import xgboost as xgb
d... | 3,247 | 32.833333 | 89 | py |
xgboost | xgboost-master/demo/guide-python/feature_weights.py | """
Demo for using feature weight to change column sampling
=======================================================
.. versionadded:: 1.3.0
"""
import argparse
import numpy as np
from matplotlib import pyplot as plt
import xgboost
def main(args: argparse.Namespace) -> None:
rng = np.random.RandomState(199... | 1,383 | 22.066667 | 85 | py |
xgboost | xgboost-master/demo/guide-python/gamma_regression.py | """
Demo for gamma regression
=========================
"""
import numpy as np
import xgboost as xgb
# 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 xgboo... | 1,098 | 35.633333 | 99 | py |
xgboost | xgboost-master/demo/guide-python/categorical.py | """
Getting started with categorical data
=====================================
Experimental support for categorical data.
In before, users need to run an encoder themselves before passing the data into XGBoost,
which creates a sparse matrix and potentially increase memory usage. This demo
showcases the experimental... | 2,833 | 31.204545 | 88 | py |
xgboost | xgboost-master/demo/guide-python/boost_from_prediction.py | """
Demo for boosting from prediction
=================================
"""
import os
import xgboost as xgb
CURRENT_DIR = os.path.dirname(__file__)
dtrain = xgb.DMatrix(
os.path.join(CURRENT_DIR, "../data/agaricus.txt.train?format=libsvm")
)
dtest = xgb.DMatrix(
os.path.join(CURRENT_DIR, "../data/agaricus.txt... | 1,174 | 31.638889 | 73 | py |
xgboost | xgboost-master/demo/guide-python/evals_result.py | """
This script demonstrate how to access the eval metrics
======================================================
"""
import os
import xgboost as xgb
CURRENT_DIR = os.path.dirname(__file__)
dtrain = xgb.DMatrix(
os.path.join(CURRENT_DIR, "../data/agaricus.txt.train?format=libsvm")
)
dtest = xgb.DMatrix(
os.pa... | 1,120 | 24.477273 | 79 | py |
xgboost | xgboost-master/demo/guide-python/sklearn_parallel.py | """
Demo for using xgboost with sklearn
===================================
"""
import multiprocessing
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import GridSearchCV
import xgboost as xgb
if __name__ == "__main__":
print("Parallel Parameter optimization")
X, y = fetch_... | 689 | 24.555556 | 67 | py |
xgboost | xgboost-master/demo/guide-python/predict_leaf_indices.py | """
Demo for obtaining leaf index
=============================
"""
import os
import xgboost as xgb
# load data in do training
CURRENT_DIR = os.path.dirname(__file__)
dtrain = xgb.DMatrix(
os.path.join(CURRENT_DIR, "../data/agaricus.txt.train?format=libsvm")
)
dtest = xgb.DMatrix(
os.path.join(CURRENT_DIR, ".... | 850 | 25.59375 | 73 | py |
xgboost | xgboost-master/demo/guide-python/spark_estimator_examples.py | """
Collection of examples for using xgboost.spark estimator interface
==================================================================
@author: Weichen Xu
"""
import sklearn.datasets
from pyspark.ml.evaluation import MulticlassClassificationEvaluator, RegressionEvaluator
from pyspark.ml.linalg import Vectors
from p... | 3,454 | 34.255102 | 90 | py |
xgboost | xgboost-master/demo/guide-python/individual_trees.py | """
Demo for prediction using individual trees and model slices
===========================================================
"""
import os
import numpy as np
from scipy.special import logit
from sklearn.datasets import load_svmlight_file
import xgboost as xgb
CURRENT_DIR = os.path.dirname(__file__)
train = os.path.jo... | 3,371 | 32.72 | 83 | py |
xgboost | xgboost-master/demo/guide-python/basic_walkthrough.py | """
Getting started with XGBoost
============================
This is a simple example of using the native XGBoost interface, there are other
interfaces in the Python package like scikit-learn interface and Dask interface.
See :doc:`/python/python_intro` and :doc:`/tutorials/index` for other references.
"""
import ... | 2,257 | 29.106667 | 88 | py |
xgboost | xgboost-master/demo/guide-python/sklearn_evals_result.py | """
Demo for accessing the xgboost eval metrics by using sklearn interface
======================================================================
"""
import numpy as np
from sklearn.datasets import make_hastie_10_2
import xgboost as xgb
X, y = make_hastie_10_2(n_samples=2000, random_state=42)
# Map labels from {-1,... | 1,278 | 26.804348 | 70 | py |
xgboost | xgboost-master/demo/guide-python/quantile_regression.py | """
Quantile Regression
===================
.. versionadded:: 2.0.0
The script is inspired by this awesome example in sklearn:
https://scikit-learn.org/stable/auto_examples/ensemble/plot_gradient_boosting_quantile.html
"""
import argparse
from typing import Dict
import numpy as np
from sklearn.model_selection i... | 3,920 | 30.368 | 91 | py |
xgboost | xgboost-master/demo/guide-python/cross_validation.py | """
Demo for using cross validation
===============================
"""
import os
import numpy as np
import xgboost as xgb
# load data in do training
CURRENT_DIR = os.path.dirname(__file__)
dtrain = xgb.DMatrix(
os.path.join(CURRENT_DIR, "../data/agaricus.txt.train?format=libsvm")
)
param = {"max_depth": 2, "eta... | 2,481 | 25.978261 | 85 | py |
xgboost | xgboost-master/demo/guide-python/multioutput_regression.py | """
A demo for multi-output regression
==================================
The demo is adopted from scikit-learn:
https://scikit-learn.org/stable/auto_examples/ensemble/plot_random_forest_regression_multioutput.html#sphx-glr-auto-examples-ensemble-plot-random-forest-regression-multioutput-py
See :doc:`/tutorials/mult... | 4,360 | 30.832117 | 178 | py |
xgboost | xgboost-master/demo/guide-python/custom_softmax.py | '''
Demo for creating customized multi-class objective function
===========================================================
This demo is only applicable after (excluding) XGBoost 1.0.0, as before this version
XGBoost returns transformed prediction for multi-class objective function. More details
in comments.
See :do... | 6,043 | 31.494624 | 89 | py |
xgboost | xgboost-master/demo/rank/rank.py | #!/usr/bin/python
from sklearn.datasets import load_svmlight_file
import xgboost as xgb
from xgboost import DMatrix
# 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,288 | 29.690476 | 63 | py |
xgboost | xgboost-master/demo/rank/trans_data.py | import sys
def save_data(group_data,output_feature,output_group):
if len(group_data) == 0:
return
output_group.write(str(len(group_data))+"\n")
for data in group_data:
# only include nonzero features
feats = [ p for p in data[2:] if float(p.split(':')[1]) != 0.0 ]
output_f... | 1,177 | 27.047619 | 110 | py |
xgboost | xgboost-master/demo/rank/rank_sklearn.py | #!/usr/bin/python
from sklearn.datasets import load_svmlight_file
import xgboost as xgb
# This script demonstrate how to do ranking with XGBRanker
x_train, y_train = load_svmlight_file("mq2008.train")
x_valid, y_valid = load_svmlight_file("mq2008.vali")
x_test, y_test = load_svmlight_file("mq2008.test")
group_train... | 1,131 | 30.444444 | 66 | py |
xgboost | xgboost-master/demo/kaggle-higgs/higgs-pred.py | #!/usr/bin/python
# make prediction
import numpy as np
import xgboost as xgb
# path to where the data lies
dpath = 'data'
modelfile = 'higgs.model'
outfile = 'higgs.pred.csv'
# make top 15% as positive
threshold_ratio = 0.15
# load in training data, directly use numpy
dtest = np.loadtxt( dpath+'/test.csv', delimite... | 1,164 | 22.77551 | 66 | py |
xgboost | xgboost-master/demo/kaggle-higgs/speedtest.py | #!/usr/bin/python
# this is the example script to use xgboost to train
import time
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
import xgboost as xgb
test_size = 550000
# path to where the data lies
dpath = 'data'
# load in training data, directly use numpy
dtrain = np.loadtxt( dpath+... | 2,051 | 30.090909 | 111 | py |
xgboost | xgboost-master/demo/kaggle-higgs/higgs-cv.py | #!/usr/bin/python
import numpy as np
import xgboost as xgb
### load data in do training
train = np.loadtxt('./data/training.csv', delimiter=',', skiprows=1, converters={32: lambda x:int(x=='s'.encode('utf-8')) } )
label = train[:,32]
data = train[:,1:31]
weight = train[:,31]
dtrain = xgb.DMatrix( data, label=label... | 1,436 | 35.846154 | 125 | py |
xgboost | xgboost-master/demo/kaggle-higgs/higgs-numpy.py | #!/usr/bin/python
# this is the example script to use xgboost to train
import numpy as np
import xgboost as xgb
test_size = 550000
# path to where the data lies
dpath = 'data'
# load in training data, directly use numpy
dtrain = np.loadtxt( dpath+'/training.csv', delimiter=',', skiprows=1, converters={32: lambda x:... | 1,714 | 30.759259 | 127 | py |
xgboost | xgboost-master/demo/json-model/json_parser.py | """Demonstration for parsing JSON/UBJSON tree model file generated by XGBoost.
"""
import argparse
import json
from dataclasses import dataclass
from enum import IntEnum, unique
from typing import Any, Dict, List, Sequence, Union
import numpy as np
try:
import ubjson
except ImportError:
ubjson = None
Param... | 9,711 | 33.810036 | 87 | py |
xgboost | xgboost-master/demo/rmm_plugin/rmm_mgpu_with_dask.py | import dask
from dask.distributed import Client
from dask_cuda import LocalCUDACluster
from sklearn.datasets import make_classification
import xgboost as xgb
def main(client):
# Optionally force XGBoost to use RMM for all GPU memory allocation, see ./README.md
# xgb.set_config(use_rmm=True)
X, y = make_... | 1,334 | 36.083333 | 90 | py |
xgboost | xgboost-master/demo/rmm_plugin/rmm_singlegpu.py | import rmm
from sklearn.datasets import make_classification
import xgboost as xgb
# Initialize RMM pool allocator
rmm.reinitialize(pool_allocator=True)
# Optionally force XGBoost to use RMM for all GPU memory allocation, see ./README.md
# xgb.set_config(use_rmm=True)
X, y = make_classification(n_samples=10000, n_inf... | 651 | 27.347826 | 84 | py |
xgboost | xgboost-master/dev/query_contributors.py | """Query list of all contributors and reviewers in a release"""
import json
import re
import sys
import requests
from sh.contrib import git
if len(sys.argv) != 5:
print(f'Usage: {sys.argv[0]} [starting commit/tag] [ending commit/tag] [GitHub username] ' +
'[GitHub password]')
sys.exit(1)
from_com... | 2,905 | 37.236842 | 104 | py |
xgboost | xgboost-master/dev/release-artifacts.py | """Simple script for managing Python, R, and source release packages.
tqdm, sh are required to run this script.
"""
import argparse
import os
import shutil
import subprocess
import tarfile
import tempfile
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from urllib.request import url... | 10,231 | 28.744186 | 91 | py |
xgboost | xgboost-master/dev/prepare_jvm_release.py | import argparse
import errno
import glob
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
from contextlib import contextmanager
from urllib.request import urlretrieve
def normpath(path):
"""Normalize UNIX path to a native path."""
normalized = os.pa... | 7,263 | 40.508571 | 99 | py |
xgboost | xgboost-master/python-package/hatch_build.py | """
Custom hook to customize the behavior of Hatchling.
Here, we customize the tag of the generated wheels.
"""
import sysconfig
from typing import Any, Dict
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
def get_tag() -> str:
"""Get appropriate wheel tag according to system"""
tag_... | 681 | 28.652174 | 79 | py |
xgboost | xgboost-master/python-package/xgboost/rabit.py | """Compatibility shim for xgboost.rabit; to be removed in 2.0"""
import logging
import warnings
from enum import IntEnum, unique
from typing import Any, Callable, List, Optional, TypeVar
import numpy as np
from . import collective
LOGGER = logging.getLogger("[xgboost.rabit]")
def _deprecation_warning() -> str:
... | 4,310 | 24.358824 | 90 | py |
xgboost | xgboost-master/python-package/xgboost/libpath.py | # coding: utf-8
"""Find the path to xgboost dynamic library files."""
import os
import platform
import sys
from typing import List
class XGBoostLibraryNotFound(Exception):
"""Error thrown by when xgboost is not found"""
def find_lib_path() -> List[str]:
"""Find the path to xgboost dynamic library files.
... | 2,791 | 37.246575 | 85 | py |
xgboost | xgboost-master/python-package/xgboost/tracker.py | # pylint: disable=too-many-instance-attributes, too-many-arguments, too-many-branches
"""
This script is a variant of dmlc-core/dmlc_tracker/tracker.py,
which is a specialized version for xgboost tasks.
"""
import argparse
import logging
import socket
import struct
import sys
from threading import Thread
from typing im... | 16,918 | 32.109589 | 88 | py |
xgboost | xgboost-master/python-package/xgboost/core.py | # pylint: disable=too-many-arguments, too-many-branches, invalid-name
# pylint: disable=too-many-lines, too-many-locals
"""Core XGBoost Library."""
import copy
import ctypes
import importlib.util
import json
import os
import re
import sys
import warnings
from abc import ABC, abstractmethod
from collections.abc import M... | 104,045 | 33.728304 | 97 | py |
xgboost | xgboost-master/python-package/xgboost/plotting.py | # pylint: disable=too-many-locals, too-many-arguments, invalid-name,
# pylint: disable=too-many-branches
"""Plotting Library."""
import json
from io import BytesIO
from typing import Any, Optional, Union
import numpy as np
from ._typing import PathLike
from .core import Booster
from .sklearn import XGBModel
Axes = A... | 8,852 | 28.908784 | 88 | py |
xgboost | xgboost-master/python-package/xgboost/collective.py | """XGBoost collective communication related API."""
import ctypes
import json
import logging
import pickle
from enum import IntEnum, unique
from typing import Any, Dict, List
import numpy as np
from ._typing import _T
from .core import _LIB, _check_call, c_str, from_pystr_to_cstr, py_str
LOGGER = logging.getLogger("... | 7,841 | 28.81749 | 100 | py |
xgboost | xgboost-master/python-package/xgboost/training.py | # pylint: disable=too-many-locals, too-many-arguments, invalid-name
# pylint: disable=too-many-branches, too-many-statements
"""Training Library containing training routines."""
import copy
import os
import warnings
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union, cast
import numpy as np... | 21,948 | 35.520799 | 97 | py |
xgboost | xgboost-master/python-package/xgboost/data.py | # pylint: disable=too-many-arguments, too-many-branches, too-many-lines
# pylint: disable=too-many-return-statements, import-error
"""Data dispatching for DMatrix."""
import ctypes
import json
import os
import warnings
from typing import Any, Callable, Iterator, List, Optional, Sequence, Tuple, Union, cast
import nump... | 43,680 | 31.452452 | 88 | py |
xgboost | xgboost-master/python-package/xgboost/config.py | # pylint: disable=missing-function-docstring
"""Global configuration for XGBoost"""
import ctypes
import json
from contextlib import contextmanager
from functools import wraps
from typing import Any, Callable, Dict, Iterator, Optional, cast
from ._typing import _F
from .core import _LIB, _check_call, c_str, py_str
d... | 5,045 | 25.983957 | 90 | py |
xgboost | xgboost-master/python-package/xgboost/federated.py | """XGBoost Federated Learning related API."""
from .core import _LIB, XGBoostError, _check_call, build_info, c_str
def run_federated_server(
port: int,
world_size: int,
server_key_path: str = "",
server_cert_path: str = "",
client_cert_path: str = "",
) -> None:
"""Run the Federated Learning ... | 1,447 | 30.478261 | 79 | py |
xgboost | xgboost-master/python-package/xgboost/__init__.py | """XGBoost: eXtreme Gradient Boosting library.
Contributors: https://github.com/dmlc/xgboost/blob/master/CONTRIBUTORS.md
"""
from . import tracker # noqa
from . import collective, dask, rabit
from .core import (
Booster,
DataIter,
DeviceQuantileDMatrix,
DMatrix,
QuantileDMatrix,
_py_version,
... | 1,280 | 17.838235 | 73 | py |
xgboost | xgboost-master/python-package/xgboost/_typing.py | # pylint: disable=protected-access
"""Shared typing definition."""
import ctypes
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Sequence,
Type,
TypeVar,
Union,
)
# os.PathLike/string/numpy.array/scipy.sparse/pd.DataFrame/dt.Frame/
# cudf.DataFrame/cupy.arra... | 2,377 | 22.087379 | 90 | py |
xgboost | xgboost-master/python-package/xgboost/compat.py | # pylint: disable= invalid-name, unused-import
"""For compatibility and optional dependencies."""
import importlib.util
import logging
import sys
import types
from typing import Any, Dict, List, Optional, Sequence, cast
import numpy as np
from ._typing import _T
assert sys.version_info[0] == 3, "Python 2 is no long... | 6,485 | 32.261538 | 89 | py |
xgboost | xgboost-master/python-package/xgboost/callback.py | """Callback library containing training routines. See :doc:`Callback Functions
</python/callbacks>` for a quick introduction.
"""
import collections
import os
import pickle
from abc import ABC
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Unio... | 19,301 | 32.164948 | 89 | py |
xgboost | xgboost-master/python-package/xgboost/dask.py | # pylint: disable=too-many-arguments, too-many-locals
# pylint: disable=missing-class-docstring, invalid-name
# pylint: disable=too-many-lines
# pylint: disable=too-few-public-methods
# pylint: disable=import-error
"""
Dask extensions for distributed training
----------------------------------------
See :doc:`Distribu... | 80,968 | 34.373089 | 94 | py |
xgboost | xgboost-master/python-package/xgboost/sklearn.py | # pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme, too-many-lines
"""Scikit-Learn Wrapper interface for XGBoost."""
import copy
import json
import os
import warnings
from concurrent.futures import ThreadPoolExecutor
from typing import (
Any,
Callable,
Dict,
List,
Optional,
... | 80,941 | 37.397533 | 90 | py |
xgboost | xgboost-master/python-package/xgboost/testing/data.py | # pylint: disable=invalid-name
"""Utilities for data generation."""
import os
import zipfile
from dataclasses import dataclass
from typing import Any, Generator, List, NamedTuple, Optional, Tuple, Union
from urllib import request
import numpy as np
import pytest
from numpy import typing as npt
from numpy.random import... | 17,993 | 28.693069 | 90 | py |
xgboost | xgboost-master/python-package/xgboost/testing/updater.py | """Tests for updaters."""
import json
from functools import partial, update_wrapper
from typing import Any, Dict
import numpy as np
import xgboost as xgb
import xgboost.testing as tm
def get_basescore(model: xgb.XGBModel) -> float:
"""Get base score from an XGBoost sklearn estimator."""
base_score = float(
... | 8,994 | 33.72973 | 88 | py |
xgboost | xgboost-master/python-package/xgboost/testing/shared.py | """Testing code shared by other tests."""
# pylint: disable=invalid-name
import collections
import importlib.util
import json
import os
import tempfile
from typing import Any, Callable, Dict, Type
import numpy as np
import xgboost as xgb
from xgboost._typing import ArrayLike
def validate_leaf_output(leaf: np.ndarra... | 3,113 | 31.4375 | 80 | py |
xgboost | xgboost-master/python-package/xgboost/testing/metrics.py | """Tests for evaluation metrics."""
from typing import Dict, List
import numpy as np
import pytest
import xgboost as xgb
from xgboost.compat import concat
from xgboost.core import _parse_eval_str
def check_precision_score(tree_method: str) -> None:
"""Test for precision with ranking and classification."""
d... | 2,468 | 29.8625 | 87 | py |
xgboost | xgboost-master/python-package/xgboost/testing/__init__.py | """Utilities for defining Python tests. The module is private and subject to frequent
change without notice.
"""
# pylint: disable=invalid-name,missing-function-docstring,import-error
import gc
import importlib.util
import multiprocessing
import os
import platform
import socket
import sys
from concurrent.futures impor... | 26,177 | 27.735456 | 101 | py |
xgboost | xgboost-master/python-package/xgboost/testing/ranking.py | # pylint: disable=too-many-locals
"""Tests for learning to rank."""
from types import ModuleType
from typing import Any
import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
def run_ranking_qid_df(impl: ModuleType, tree_method: str) -> None:
"""Test ranking with qid packed int... | 2,513 | 31.230769 | 87 | py |
xgboost | xgboost-master/python-package/xgboost/testing/params.py | """Strategies for updater tests."""
from typing import cast
import pytest
strategies = pytest.importorskip("hypothesis.strategies")
exact_parameter_strategy = strategies.fixed_dictionaries(
{
"nthread": strategies.integers(1, 4),
"max_depth": strategies.integers(1, 11),
"min_child_weigh... | 3,227 | 37.428571 | 86 | py |
xgboost | xgboost-master/python-package/xgboost/testing/dask.py | """Tests for dask shared by different test modules."""
import numpy as np
import pandas as pd
from dask import array as da
from dask import dataframe as dd
from distributed import Client
import xgboost as xgb
from xgboost.testing.updater import get_basescore
def check_init_estimation_clf(tree_method: str, client: Cl... | 2,607 | 33.315789 | 84 | py |
xgboost | xgboost-master/python-package/xgboost/spark/core.py | """XGBoost pyspark integration submodule for core code."""
import base64
# pylint: disable=fixme, too-many-ancestors, protected-access, no-member, invalid-name
# pylint: disable=too-few-public-methods, too-many-lines, too-many-branches
import json
import logging
import os
from collections import namedtuple
from typing... | 59,223 | 37.733813 | 99 | py |
xgboost | xgboost-master/python-package/xgboost/spark/utils.py | """Xgboost pyspark integration submodule for helper functions."""
# pylint: disable=fixme
import inspect
import logging
import os
import sys
import uuid
from threading import Thread
from typing import Any, Callable, Dict, Optional, Set, Type
import pyspark
from pyspark import BarrierTaskContext, SparkContext, SparkFi... | 6,352 | 31.747423 | 87 | py |
xgboost | xgboost-master/python-package/xgboost/spark/data.py | # pylint: disable=protected-access
"""Utilities for processing spark partitions."""
from collections import defaultdict, namedtuple
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
from xgboost import Da... | 12,431 | 33.247934 | 92 | py |
xgboost | xgboost-master/python-package/xgboost/spark/__init__.py | """PySpark XGBoost integration interface"""
try:
import pyspark
except ImportError as e:
raise ImportError("pyspark package needs to be installed to use this module") from e
from .estimator import (
SparkXGBClassifier,
SparkXGBClassifierModel,
SparkXGBRanker,
SparkXGBRankerModel,
SparkXGBR... | 536 | 20.48 | 88 | py |
xgboost | xgboost-master/python-package/xgboost/spark/params.py | """Xgboost pyspark integration submodule for params."""
from typing import Dict
# pylint: disable=too-few-public-methods
from pyspark.ml.param import TypeConverters
from pyspark.ml.param.shared import Param, Params
class HasArbitraryParamsDict(Params):
"""
This is a Params based class that is extended by _Sp... | 3,221 | 29.396226 | 96 | py |
xgboost | xgboost-master/python-package/xgboost/spark/estimator.py | """Xgboost pyspark integration submodule for estimator API."""
# pylint: disable=too-many-ancestors
# pylint: disable=fixme, too-many-ancestors, protected-access, no-member, invalid-name
# pylint: disable=unused-argument, too-many-locals
import warnings
from typing import Any, List, Optional, Type, Union
import numpy... | 23,434 | 37.544408 | 100 | py |
xgboost | xgboost-master/python-package/packager/build_config.py | """Build configuration"""
import dataclasses
from typing import Any, Dict, List, Optional
@dataclasses.dataclass
class BuildConfiguration: # pylint: disable=R0902
"""Configurations use when building libxgboost"""
# Whether to hide C++ symbols in libxgboost.so
hide_cxx_symbols: bool = True
# Whether ... | 1,840 | 34.403846 | 78 | py |
xgboost | xgboost-master/python-package/packager/sdist.py | """
Functions for building sdist
"""
import logging
import pathlib
from .util import copy_with_logging, copytree_with_logging
def copy_cpp_src_tree(
cpp_src_dir: pathlib.Path, target_dir: pathlib.Path, logger: logging.Logger
) -> None:
"""Copy C++ source tree into build directory"""
for subdir in [
... | 678 | 23.25 | 87 | py |
xgboost | xgboost-master/python-package/packager/pep517.py | """
Custom build backend for XGBoost Python package.
Builds source distribution and binary wheels, following PEP 517 / PEP 660.
Reuses components of Hatchling (https://github.com/pypa/hatch/tree/master/backend) for the sake
of brevity.
"""
import dataclasses
import logging
import os
import pathlib
import tempfile
from ... | 5,643 | 34.496855 | 96 | py |
xgboost | xgboost-master/python-package/packager/nativelib.py | """
Functions for building libxgboost
"""
import logging
import os
import pathlib
import shutil
import subprocess
import sys
from platform import system
from typing import Optional
from .build_config import BuildConfiguration
def _lib_name() -> str:
"""Return platform dependent shared object name."""
if syst... | 5,623 | 34.371069 | 91 | py |
xgboost | xgboost-master/python-package/packager/util.py | """
Utility functions for implementing PEP 517 backend
"""
import logging
import pathlib
import shutil
def copytree_with_logging(
src: pathlib.Path, dest: pathlib.Path, logger: logging.Logger
) -> None:
"""Call shutil.copytree() with logging"""
logger.info("Copying %s -> %s", str(src), str(dest))
shut... | 679 | 25.153846 | 71 | py |
xgboost | xgboost-master/python-package/packager/__init__.py | 0 | 0 | 0 | py | |
xgboost | xgboost-master/jvm-packages/create_jni.py | #!/usr/bin/env python
import errno
import argparse
import glob
import os
import platform
import shutil
import subprocess
import sys
from contextlib import contextmanager
# Monkey-patch the API inconsistency between Python2.X and 3.X.
if sys.platform.startswith("linux"):
sys.platform = "linux"
CONFIG = {
"USE... | 5,347 | 31.023952 | 96 | py |
xgboost | xgboost-master/jvm-packages/xgboost4j-tester/generate_pom.py | import sys
pom_template = """
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<g... | 5,462 | 33.575949 | 177 | py |
xgboost | xgboost-master/jvm-packages/xgboost4j-tester/get_iris.py | import numpy as np
import pandas
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
y = y.astype(np.int32)
df = pandas.DataFrame(data=X, columns=['sepal length', 'sepal width', 'petal length', 'petal width'])
class_id_to_name = {0:'Iris-setosa', 1:'Iris-versicolor', 2:'Iris-virginica'}
df['class'... | 434 | 38.545455 | 101 | py |
xgboost | xgboost-master/doc/sphinx_util.py | # -*- coding: utf-8 -*-
"""Helper utility function for customization."""
import os
import subprocess
import sys
READTHEDOCS_BUILD = (os.environ.get('READTHEDOCS', None) is not None)
if not os.path.exists('web-data'):
subprocess.call('rm -rf web-data;' +
'git clone https://github.com/dmlc/web-data'... | 457 | 27.625 | 77 | py |
xgboost | xgboost-master/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... | 9,206 | 31.419014 | 97 | py |
missingpy | missingpy-master/setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="missingpy",
version="0.2.0",
author="Ashim Bhattarai",
description="Missing Data Imputation for Python",
long_description=long_description,
long_description_content_type="text/markdown... | 616 | 28.380952 | 75 | py |
missingpy | missingpy-master/missingpy/pairwise_external.py | # This file is a modification of sklearn.metrics.pairwise
# Modifications by Ashim Bhattarai
"""
New BSD License
Copyright (c) 2007–2018 The scikit-learn developers.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditi... | 13,219 | 40.835443 | 79 | py |
missingpy | missingpy-master/missingpy/missforest.py | """MissForest Imputer for Missing Data"""
# Author: Ashim Bhattarai
# License: GNU General Public License v3 (GPLv3)
import warnings
import numpy as np
from scipy.stats import mode
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted, check_array
from sklearn.... | 24,673 | 43.298025 | 137 | py |
missingpy | missingpy-master/missingpy/knnimpute.py | """KNN Imputer for Missing Data"""
# Author: Ashim Bhattarai
# License: GNU General Public License v3 (GPLv3)
import warnings
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from sklearn.utils.valid... | 13,456 | 39.902736 | 79 | py |
missingpy | missingpy-master/missingpy/utils.py | """Utility Functions"""
# Author: Ashim Bhattarai
# License: BSD 3 clause
import numpy as np
def masked_euclidean_distances(X, Y=None, squared=False,
missing_values="NaN", copy=True):
"""Calculates euclidean distances in the presence of missing values
Computes the euclidean di... | 4,360 | 33.888 | 79 | py |
missingpy | missingpy-master/missingpy/__init__.py | from .knnimpute import KNNImputer
from .missforest import MissForest
__all__ = ['KNNImputer', 'MissForest']
| 109 | 21 | 38 | py |
missingpy | missingpy-master/missingpy/tests/test_knnimpute.py | import numpy as np
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_equal
from missingpy import KNNImputer
from missingpy.pairwise_external import masked_eucl... | 17,527 | 27.924092 | 79 | py |
missingpy | missingpy-master/missingpy/tests/__init__.py | 0 | 0 | 0 | py | |
missingpy | missingpy-master/missingpy/tests/test_missforest.py | import numpy as np
from scipy.stats import mode
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_equal
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from missingpy import MissForest
def ge... | 13,725 | 32.478049 | 79 | py |
basho_bench | basho_bench-master/priv/results-browser.py | #!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import base64
import argparse
import os
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
logging.warning("======= GET STARTED =======")
logging.warning(self.headers)
Simp... | 1,280 | 32.710526 | 124 | py |
deep_direct_stat | deep_direct_stat-master/setup.py | from setuptools import setup, find_packages
setup(
name="datasets",
version=0.1,
description="Scripts to load preprocessed datasets (PASCAL3D+, CAVIAR, TownCentre, IDIAP)",
author="Sergey Prokudin",
author_email="[email protected]",
packages=["datasets"],
)
setup(
name="utils",
... | 731 | 25.142857 | 95 | py |
deep_direct_stat | deep_direct_stat-master/view_estimation/run_evaluation.py | import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.dirname(BASE_DIR))
from global_variables import *
from evaluation_helper import *
cls_names = g_shape_names
# img_name_file_list = [os.path.join(g_real_images_voc12val_det_bbox_folder, name+'.... | 940 | 43.809524 | 131 | py |
deep_direct_stat | deep_direct_stat-master/view_estimation/prepare_training_data.py | #!/usr/bin/python
'''
Prepare Training Data
Running this program will populate following folders:
g_syn_images_lmdb_folder
with img-label files and g_syn_images_lmdb_pathname_prefix+[_label,_image] LMDBs
g_real_images_voc12train_all_gt_bbox_folder
with cropped images and img-label files and g_real_images_... | 2,744 | 42.571429 | 311 | py |
deep_direct_stat | deep_direct_stat-master/view_estimation/prepare_testing_data.py | #!/usr/bin/python
'''
Prepare Testing Data
prepare filelist and LMDB for real images
running this program will populate following folders:
g_real_images_voc12val_det_bbox_folder
g_real_images_voc12val_easy_gt_bbox_folder
'''
import os
import sys
from data_prep_helper import *
BASE_DIR = os.path.dirname(os.path.... | 1,226 | 33.083333 | 205 | py |
deep_direct_stat | deep_direct_stat-master/models/single_density.py | import tensorflow as tf
import keras
import numpy as np
from keras import backend as K
from keras.models import Sequential
from keras.layers import Input, Dense, Dropout, Flatten, Activation, Lambda
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.model... | 10,409 | 35.271777 | 119 | py |
deep_direct_stat | deep_direct_stat-master/models/finite_mixture.py | import tensorflow as tf
import keras
import numpy as np
from keras import backend as K
from keras.models import Sequential
from keras.layers import Input, Dense, Dropout, Flatten, Activation, Lambda
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from keras.model... | 11,224 | 38.111498 | 125 | py |
deep_direct_stat | deep_direct_stat-master/models/infinite_mixture.py | import tensorflow as tf
import keras
import numpy as np
import os
from scipy import stats
from scipy.misc import imresize
from keras import backend as K
from keras.models import Sequential
from keras.layers import Input, Dense, Dropout, Flatten, Activation, Lambda, GlobalAveragePooling2D
from keras.layers import Conv... | 22,658 | 39.753597 | 128 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.