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 |
|---|---|---|---|---|---|---|
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/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/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/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/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/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/__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/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/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/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/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/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/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 |
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 |
deep_direct_stat | deep_direct_stat-master/utils/losses.py | import numpy as np
import tensorflow as tf
from scipy.special import i0 as mod_bessel0
from scipy.special import i1 as mod_bessel1
from keras import backend as K
from scipy.stats import multivariate_normal
def cosine_loss_np(y_target, y_pred):
return 1 - np.sum(np.multiply(y_target, y_pred),axis=1)
def mad_loss... | 14,052 | 33.27561 | 119 | py |
deep_direct_stat | deep_direct_stat-master/utils/custom_keras_callbacks.py | import keras
import numpy as np
import pandas as pd
import warnings
class SideModelCheckpoint(keras.callbacks.Callback):
def __init__(self, model_name, model_to_save, save_path, save_weights_only=False):
self.model_name = model_name
self.model = model_to_save
self.save_path = save_path
... | 6,614 | 43.695946 | 106 | py |
KG-DQN | KG-DQN-master/dqn/dqn.py | import math, random
import textworld
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
from collections import deque
from nltk.tokenize import word_tokenize
#from matplotlib import use
#use('Agg')
import matplotlib.pypl... | 9,801 | 34.132616 | 118 | py |
KG-DQN | KG-DQN-master/kgdqn/gdqn.py | import networkx as nx
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import spacy
import logging
import textworld
import matplotlib.pyplot as plt
from representations import StateNAction
from utils.schedule import *
#from utils.priorit... | 8,916 | 36.624473 | 110 | py |
KG-DQN | KG-DQN-master/kgdqn/layers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
class GraphAttentionLayer(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=Fa... | 6,418 | 35.68 | 215 | py |
KG-DQN | KG-DQN-master/kgdqn/rnn_reader.py | import torch
import torch.nn as nn
from layers import *
class RnnDocReader(nn.Module):
"""Network for the Document Reader module of DrQA."""
RNN_TYPES = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN}
def __init__(self, opt, padding_idx=0, embedding=None):
super(RnnDocReader, self).__init__()
... | 5,938 | 39.958621 | 84 | py |
KG-DQN | KG-DQN-master/kgdqn/models.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import spacy
import numpy as np
from layers import *
from drqa import *
class GAT(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
super(GAT, self).... | 8,466 | 40.915842 | 115 | py |
KG-DQN | KG-DQN-master/kgdqn/drqa.py | import random
import torch
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import logging
from torch.autograd import Variable
from utils.drqa_utils import AverageMeter
from rnn_reader import RnnDocReader
class DocReaderModel(object):
"""High level model that handles intializing the... | 5,300 | 35.061224 | 89 | py |
Slic | Slic-master/utils.py | import torch
from dataset import SolarDataset
from model import SolarClassifier
from torch.utils.data import DataLoader
import numpy as np
from tqdm import tqdm
import sunpy.cm as cm
import matplotlib.pyplot as plt
import torch.nn.functional as F
import os, html
from astropy.io import fits
import sunpy.map as m
from sk... | 7,245 | 41.623529 | 250 | py |
Slic | Slic-master/model.py | import torch
import torch.nn as nn
from torch.nn.init import kaiming_normal_
class SolarClassifier(nn.Module):
def __init__(self):
super().__init__()
self.max_pool = nn.MaxPool2d(kernel_size=2,stride=2)
self.layer1 = nn.Sequential(
nn.Conv2d(1,64,kernel_size=3,padding=1),
... | 2,842 | 32.05814 | 231 | py |
Slic | Slic-master/dataset.py | import numpy as np
from torch.utils.data import Dataset
class SolarDataset(Dataset):
def __init__(self,source="from_file",dat_file=None,data_arr=None,label_arr=None,test=False):
super().__init__()
self.test = test
if not self.test:
if source == "from_file":
if da... | 2,892 | 33.035294 | 141 | py |
Slic | Slic-master/confusion_matrix.py | import numpy as np
import pandas as pd
from dataset import *
from model import solar_classifier
import torch
from torch.utils.data import DataLoader
class ConfusionMatrix():
'''
A class to store the confusion matrix, its features and the associated statistics that go along with it.
Parameters
--------... | 9,563 | 32.093426 | 279 | py |
Slic | Slic-master/train.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import numpy as np
from dataset import SolarDataset
from model import SolarClassifier
import argparse
from tqdm import tqdm
def train(model,device,data_loader,optimiser,epoch,criterion):
model.to(device)
mode... | 4,003 | 51.684211 | 158 | py |
dancin_seq2seq | dancin_seq2seq-master/adversarial.py | """
adversarial.py - Adversarial classes.
Classes:
Autoencoder: a general autoencoder interface.
SpamSeq2SeqAutoencoder: a sequence to sequence autoencoder interface.
"""
from __future__ import division
import gc
import logging
import numpy as np
import os
import scipy
import scipy.stats
import sklearn
impo... | 14,259 | 43.5625 | 168 | py |
dancin_seq2seq | dancin_seq2seq-master/autoencoder.py | """
autoencoder.py - Autoencoder classes.
Classes:
Autoencoder: a general autoencoder interface.
SpamSeq2SeqAutoencoder: a sequence to sequence autoencoder interface.
"""
from __future__ import division
import logging
import numpy as np
import os
import scipy
import scipy.stats
import sklearn
import torch
... | 7,919 | 35.837209 | 115 | py |
Rail-Detection | Rail-Detection-main/train.py | import torch, os, datetime, copy, json, scipy, cv2
import numpy as np
from model.model import parsingNet
from data.dataloader import get_train_loader
from data.dataset import raildb_row_anchor
from utils.evaluation import LaneEval, grid_2_inter
from utils.dist_utils import dist_print, dist_tqdm, is_main_process
from ... | 12,493 | 46.325758 | 158 | py |
Rail-Detection | Rail-Detection-main/segmentation/backbone.py | import torch,pdb
import torchvision
import torch.nn.modules
class vgg16bn(torch.nn.Module):
def __init__(self,pretrained = False):
super(vgg16bn,self).__init__()
model = list(torchvision.models.vgg16_bn(pretrained=pretrained).features.children())
model = model[:33]+model[34:43]
self... | 2,097 | 35.172414 | 92 | py |
Rail-Detection | Rail-Detection-main/segmentation/speed_simple.py | <<<<<<< HEAD
import torch
import time, sys
import numpy as np
from model_seg import parsingNet
torch.backends.cudnn.benchmark = True
net = parsingNet(pretrained = False, backbone='18', cls_dim=(200, 52, 4)).cuda()
net.eval()
x = torch.zeros((1,3,288,800)).cuda() + 1
for i in range(10):
y = net(x)
t_all = []
for ... | 1,764 | 22.851351 | 80 | py |
Rail-Detection | Rail-Detection-main/segmentation/model_seg.py | from turtle import forward
import torch, sys
from backbone import resnet
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class conv_bn_relu(nn.Module):
def __init__(self, in_channels, out_channels, upsample=0):
super(conv_bn_relu,self).__init__()
self.conv = t... | 5,456 | 33.980769 | 126 | py |
Rail-Detection | Rail-Detection-main/segmentation/train.py | <<<<<<< HEAD
from wsgiref import validate
from matplotlib.pyplot import plot
import torch, os, datetime, copy, json, scipy, time, sys, cv2
import numpy as np
from IPython import embed
from model_seg import parsingNet
sys.path.append("..")
from data.dataloader import get_train_loader
from data.constant import raildb_ro... | 24,730 | 48.860887 | 158 | py |
Rail-Detection | Rail-Detection-main/hand-crafted/hand_crafted.py | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 8 21:49:26 2017
@author: zander
"""
import os, random, sys, json
import cv2
import hand_utils
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import time, tqdm
from IPython import embed
import pandas as pd
import torch.multiprocessing
torch.mult... | 3,461 | 34.690722 | 132 | py |
Rail-Detection | Rail-Detection-main/utils/deploy.py | import torch, os, cv2, sys
import scipy.special, tqdm
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
sys.path.append("..")
from model.model import parsingNet
from utils.common import merge_config
from utils.dist_utils import dist_print
from utils.evaluation import grid_2_inter
fr... | 4,050 | 35.827273 | 122 | py |
Rail-Detection | Rail-Detection-main/utils/loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from IPython import embed
class OhemCELoss(nn.Module):
def __init__(self, thresh, n_min, ignore_lb=255, *args, **kwargs):
super(OhemCELoss, self).__init__()
self.thresh = -torch.log(torch.tensor(thresh, dtype=tor... | 2,528 | 34.125 | 86 | py |
Rail-Detection | Rail-Detection-main/utils/dist_utils.py | import torch
import torch.distributed as dist
import pickle
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t... | 4,623 | 25.574713 | 77 | py |
Rail-Detection | Rail-Detection-main/utils/common.py |
import os, argparse
from utils.dist_utils import is_main_process, dist_print, DistSummaryWriter
from utils.config import Config
import torch
import time
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'fa... | 5,025 | 43.477876 | 260 | py |
Rail-Detection | Rail-Detection-main/utils/factory.py |
from utils.loss import SoftmaxFocalLoss, ParsingRelationLoss, ParsingRelationDis
from utils.metrics import MultiLabelAcc, AccTopk, Metric_mIoU
from utils.dist_utils import DistSummaryWriter
import torch
def get_optimizer(net,cfg):
training_params = filter(lambda p: p.requires_grad, net.parameters())
if cfg.o... | 4,637 | 33.61194 | 160 | py |
Rail-Detection | Rail-Detection-main/utils/speed_simple.py | import torch
import time, sys
import numpy as np
sys.path.append("..")
from model.model import parsingNet
# from segmentation.model_seg import parsingNet
torch.backends.cudnn.benchmark = True
net = parsingNet(pretrained = False, backbone='34', cls_dim=(200, 52, 4)).cuda()
net.eval()
x = torch.zeros((1,3,288,800)).cud... | 934 | 23.605263 | 80 | py |
Rail-Detection | Rail-Detection-main/utils/metrics.py | import numpy as np
import torch
import time,pdb
def converter(data):
if isinstance(data,torch.Tensor):
data = data.cpu().data.numpy().flatten()
return data.flatten()
def fast_hist(label_pred, label_true, num_classes):
hist = np.bincount(num_classes * label_true.astype(int) + label_pred, minlen... | 3,271 | 31.39604 | 111 | py |
Rail-Detection | Rail-Detection-main/data/mytransforms.py | import numbers
import random
import numpy as np
from PIL import Image, ImageOps, ImageFilter
#from config import cfg
import torch
import pdb
import cv2
# ===============================img tranforms============================
class Compose2(object):
# compose all transforms for image and label
def __init__(s... | 5,217 | 30.245509 | 129 | py |
Rail-Detection | Rail-Detection-main/data/dataloader.py | import torch, os
import numpy as np
import torchvision.transforms as transforms
import data.mytransforms as mytransforms
from data.dataset import raildb_row_anchor
from data.dataset import RailClsDataset, RailTestDataset
def get_train_loader(batch_size, data_root, griding_num=56, distributed=True, num_rails=4, mode='... | 3,045 | 37.075 | 122 | py |
Rail-Detection | Rail-Detection-main/data/dataset.py | import torch
from PIL import Image
import os
import pdb
import numpy as np
import cv2
import random
import csv
import pandas as pd
import data.mytransforms as mytransforms
# import mytransforms as mytransforms
import torchvision.transforms as transforms
from IPython import embed
import os
os.environ["KMP_DUPLICATE_LI... | 8,571 | 38.141553 | 137 | py |
Rail-Detection | Rail-Detection-main/model/hubconf.py | <<<<<<< HEAD
# Optional list of dependencies required by the package
dependencies = ["torch"]
from torchvision.models.alexnet import alexnet
from torchvision.models.convnext import convnext_tiny, convnext_small, convnext_base, convnext_large
from torchvision.models.densenet import densenet121, densenet169, densenet201... | 4,315 | 28.972222 | 101 | py |
Rail-Detection | Rail-Detection-main/model/model.py | <<<<<<< HEAD
import torch
from model.backbone import resnet, mobilenet, squeezenet, VisionTransformer
import numpy as np
class conv_bn_relu(torch.nn.Module):
def __init__(self,in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1,bias=False):
super(conv_bn_relu,self).__init__()
se... | 7,248 | 33.850962 | 106 | py |
Rail-Detection | Rail-Detection-main/model/backbone.py | <<<<<<< HEAD
import torch, pdb
import torchvision
import torch.nn.modules
from IPython import embed
from model.hubconf import *
# from hubconf import *
class mobilenet(torch.nn.Module):
def __init__(self, backbone, pretrained = False):
super(mobilenet, self).__init__()
features = list(mobilenet_v2(... | 8,429 | 31.929688 | 92 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/setup.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 3,827 | 25.957746 | 86 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/nest/nest_test.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 5,498 | 31.157895 | 79 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/vtrace_test.py | # This file taken from
# https://github.com/deepmind/scalable_agent/blob/
# d24bd74bd53d454b7222b7f0bea57a358e4ca33e/vtrace_test.py
# and modified.
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licen... | 9,701 | 35.611321 | 87 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/polybeast_net_test.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 3,863 | 41.933333 | 88 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/batching_queue_test.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 4,880 | 30.490323 | 85 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/polybeast_loss_functions_test.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 6,870 | 36.752747 | 88 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/inference_speed_profiling.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 3,562 | 25.992424 | 86 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/dynamic_batcher_test.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 7,972 | 28.639405 | 87 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/contiguous_arrays_test.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 2,650 | 31.728395 | 87 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/contiguous_arrays_env.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 1,220 | 31.131579 | 74 | py |
modern-srwm | modern-srwm-main/reinforcement_learning/tests/core_agent_state_env.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 1,230 | 29.02439 | 74 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.