Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def multiply(self, a, b):
if a is None or b is None: return None
m, n, l = len(a), len(b[0]), len(b[0])
if len(b) != n:
raise Exception("A's column number must be equal to B's row number.")
c = [[0 for _ in range(l)] for _ in range(m)]
for i,... | [
"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n "
] |
Please provide a description of the function:def multiply(self, a, b):
if a is None or b is None: return None
m, n = len(a), len(b[0])
if len(b) != n:
raise Exception("A's column number must be equal to B's row number.")
l = len(b[0])
table_a, table_b = {}, {}
for i, row in enumerat... | [
"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n "
] |
Please provide a description of the function:def bitonic_sort(arr, reverse=False):
def compare(arr, reverse):
n = len(arr)//2
for i in range(n):
if reverse != (arr[i] > arr[i+n]):
arr[i], arr[i+n] = arr[i+n], arr[i]
return arr
def bitonic_merge(arr, reve... | [
"\n bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process\n It can sort only array that sizes power of 2\n It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(decreasing)\n \n Worst-case in pa... |
Please provide a description of the function:def scc(graph):
''' Computes the strongly connected components of a graph '''
order = []
vis = {vertex: False for vertex in graph}
graph_transposed = {vertex: [] for vertex in graph}
for (v, neighbours) in graph.iteritems():
for u in neighbours:... | [] |
Please provide a description of the function:def build_graph(formula):
''' Builds the implication graph from the formula '''
graph = {}
for clause in formula:
for (lit, _) in clause:
for neg in [False, True]:
graph[(lit, neg)] = []
for ((a_lit, a_neg), (b_lit, b_neg... | [] |
Please provide a description of the function:def unique_array_sum_combinations(A, B, C, target):
def check_sum(n, *nums):
if sum(x for x in nums) == n:
return (True, nums)
else:
return (False, nums)
pro = itertools.product(A, B, C)
func = partial(check_sum, targ... | [
"\n 1. Sort all the arrays - a,b,c. - This improves average time complexity.\n 2. If c[i] < Sum, then look for Sum - c[i] in array a and b.\n When pair found, insert c[i], a[j] & b[k] into the result list.\n This can be done in O(n).\n 3. Keep on doing the above procedure while going through co... |
Please provide a description of the function:def is_bst(root):
stack = []
pre = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if pre and root.val <= pre.val:
return False
pre = root
... | [
"\n :type root: TreeNode\n :rtype: bool\n "
] |
Please provide a description of the function:def __get_depth(root):
if root is None:
return 0
left = __get_depth(root.left)
right = __get_depth(root.right)
if abs(left-right) > 1 or -1 in [left, right]:
return -1
return 1 + max(left, right) | [
"\n return 0 if unbalanced else depth + 1\n "
] |
Please provide a description of the function:def copy_random_pointer_v1(head):
dic = dict()
m = n = head
while m:
dic[m] = RandomListNode(m.label)
m = m.next
while n:
dic[n].next = dic.get(n.next)
dic[n].random = dic.get(n.random)
n = n.next
return dic.ge... | [
"\n :type head: RandomListNode\n :rtype: RandomListNode\n "
] |
Please provide a description of the function:def copy_random_pointer_v2(head):
copy = defaultdict(lambda: RandomListNode(0))
copy[None] = None
node = head
while node:
copy[node].label = node.label
copy[node].next = copy[node.next]
copy[node].random = copy[node.random]
... | [
"\n :type head: RandomListNode\n :rtype: RandomListNode\n "
] |
Please provide a description of the function:def get_factors(n):
def factor(n, i, combi, res):
while i * i <= n:
if n % i == 0:
res += combi + [i, int(n/i)],
factor(n/i, i, combi+[i], res)
i += 1
return res
return factor(n, ... | [
"[summary]\n \n Arguments:\n n {[int]} -- [to analysed number]\n \n Returns:\n [list of lists] -- [all factors of the number n]\n ",
"[summary]\n helper function\n\n Arguments:\n n {[int]} -- [number]\n i {[int]} -- [to tested divisor]\n ... |
Please provide a description of the function:def get_factors_iterative1(n):
todo, res = [(n, 2, [])], []
while todo:
n, i, combi = todo.pop()
while i * i <= n:
if n % i == 0:
res += combi + [i, n//i],
todo.append((n//i, i, combi+[i])),
... | [
"[summary]\n Computes all factors of n.\n Translated the function get_factors(...) in\n a call-stack modell.\n\n Arguments:\n n {[int]} -- [to analysed number]\n \n Returns:\n [list of lists] -- [all factors]\n "
] |
Please provide a description of the function:def get_factors_iterative2(n):
ans, stack, x = [], [], 2
while True:
if x > n // x:
if not stack:
return ans
ans.append(stack + [n])
x = stack.pop()
n *= x
x += 1
elif n... | [
"[summary]\n analog as above\n\n Arguments:\n n {[int]} -- [description]\n \n Returns:\n [list of lists] -- [all factors of n]\n "
] |
Please provide a description of the function:def longest_increasing_subsequence(sequence):
length = len(sequence)
counts = [1 for _ in range(length)]
for i in range(1, length):
for j in range(0, i):
if sequence[i] > sequence[j]:
counts[i] = max(counts[i], counts[j] +... | [
"\n Dynamic Programming Algorithm for\n counting the length of longest increasing subsequence\n type sequence: List[int]\n "
] |
Please provide a description of the function:def single_number3(nums):
# isolate a^b from pairs using XOR
ab = 0
for n in nums:
ab ^= n
# isolate right most bit from a^b
right_most = ab & (-ab)
# isolate a and b from a^b
a, b = 0, 0
for n in nums:
if n & right_most... | [
"\n :type nums: List[int]\n :rtype: List[int]\n "
] |
Please provide a description of the function:def distance(x,y):
assert len(x) == len(y), "The vector must have same length"
result = ()
sum = 0
for i in range(len(x)):
result += (x[i] -y[i],)
for component in result:
sum += component**2
return math.sqrt(sum) | [
"[summary]\n HELPER-FUNCTION\n calculates the (eulidean) distance between vector x and y.\n\n Arguments:\n x {[tuple]} -- [vector]\n y {[tuple]} -- [vector]\n "
] |
Please provide a description of the function:def nearest_neighbor(x, tSet):
assert isinstance(x, tuple) and isinstance(tSet, dict)
current_key = ()
min_d = float('inf')
for key in tSet:
d = distance(x, key)
if d < min_d:
min_d = d
current_key = key
return... | [
"[summary]\n Implements the nearest neighbor algorithm\n\n Arguments:\n x {[tupel]} -- [vector]\n tSet {[dict]} -- [training set]\n\n Returns:\n [type] -- [result of the AND-function]\n "
] |
Please provide a description of the function:def is_strobogrammatic(num):
comb = "00 11 88 69 96"
i = 0
j = len(num) - 1
while i <= j:
x = comb.find(num[i]+num[j])
if x == -1:
return False
i += 1
j -= 1
return True | [
"\n :type num: str\n :rtype: bool\n "
] |
Please provide a description of the function:def merge_sort(arr):
# Our recursive base case
if len(arr) <= 1:
return arr
mid = len(arr) // 2
# Perform merge_sort recursively on both halves
left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])
# Merge each side together
ret... | [
" Merge Sort\n Complexity: O(n log(n))\n "
] |
Please provide a description of the function:def merge(left, right, merged):
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
# Sort each one and place into the result
if left[left_cursor] <= right[right_cursor]:
merged[left_cursor+r... | [
" Merge helper\n Complexity: O(n)\n "
] |
Please provide a description of the function:def bucket_sort(arr):
''' Bucket Sort
Complexity: O(n^2)
The complexity is dominated by nextSort
'''
# The number of buckets and make buckets
num_buckets = len(arr)
buckets = [[] for bucket in range(num_buckets)]
# Assign values into b... | [] |
Please provide a description of the function:def k_closest(points, k, origin=(0, 0)):
# Time: O(k+(n-k)logk)
# Space: O(k)
heap = [(-distance(p, origin), p) for p in points[:k]]
heapify(heap)
for p in points[k:]:
d = distance(p, origin)
heappushpop(heap, (-d, p)) # heapp... | [
"Initialize max heap with first k points.\n Python does not support a max heap; thus we can use the default min heap where the keys (distance) are negated.\n ",
"\n For every point p in points[k:],\n check if p is smaller than the root of the max heap;\n if it is, add p to heap and remove root. Reh... |
Please provide a description of the function:def reverse_list(head):
if not head or not head.next:
return head
prev = None
while head:
current = head
head = head.next
current.next = prev
prev = current
return prev | [
"\n :type head: ListNode\n :rtype: ListNode\n "
] |
Please provide a description of the function:def reverse_list_recursive(head):
if head is None or head.next is None:
return head
p = head.next
head.next = None
revrest = reverse_list_recursive(p)
p.next = head
return revrest | [
"\n :type head: ListNode\n :rtype: ListNode\n "
] |
Please provide a description of the function:def has_path_sum(root, sum):
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
sum -= root.val
return has_path_sum(root.left, sum) or has_path_sum(root.right, sum) | [
"\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n "
] |
Please provide a description of the function:def int_to_base(n, base):
is_negative = False
if n == 0:
return '0'
elif n < 0:
is_negative = True
n *= -1
digit = string.digits + string.ascii_uppercase
res = ''
while n > 0:
res += digit[n % base]
n //= b... | [
"\n :type n: int\n :type base: int\n :rtype: str\n "
] |
Please provide a description of the function:def base_to_int(s, base):
digit = {}
for i,c in enumerate(string.digits + string.ascii_uppercase):
digit[c] = i
multiplier = 1
res = 0
for c in s[::-1]:
res += digit[c] * multiplier
multiplier *= base
return res | [
"\n Note : You can use int() built-in function instread of this.\n :type s: str\n :type base: int\n :rtype: int\n "
] |
Please provide a description of the function:def is_cyclic(head):
if not head:
return False
runner = head
walker = head
while runner.next and runner.next.next:
runner = runner.next.next
walker = walker.next
if runner == walker:
return True
return Fals... | [
"\n :type head: Node\n :rtype: bool\n "
] |
Please provide a description of the function:def decode_string(s):
stack = []; cur_num = 0; cur_string = ''
for c in s:
if c == '[':
stack.append((cur_string, cur_num))
cur_string = ''
cur_num = 0
elif c == ']':
prev_string, num = stack.pop()
... | [
"\n :type s: str\n :rtype: str\n "
] |
Please provide a description of the function:def palindromic_substrings_iter(s):
if not s:
yield []
return
for i in range(len(s), 0, -1):
sub = s[:i]
if sub == sub[::-1]:
for rest in palindromic_substrings_iter(s[i:]):
yield [sub] + rest | [
"\n A slightly more Pythonic approach with a recursive generator\n "
] |
Please provide a description of the function:def is_isomorphic(s, t):
if len(s) != len(t):
return False
dict = {}
set_value = set()
for i in range(len(s)):
if s[i] not in dict:
if t[i] in set_value:
return False
dict[s[i]] = t[i]
s... | [
"\n :type s: str\n :type t: str\n :rtype: bool\n "
] |
Please provide a description of the function:def calc(n2, n1, operator):
if operator == '-': return n1 - n2
elif operator == '+': return n1 + n2
elif operator == '*': return n1 * n2
elif operator == '/': return n1 / n2
elif operator == '^': return n1 ** n2
return 0 | [
"\r\n Calculate operation result\r\n\r\n n2 Number: Number 2\r\n n1 Number: Number 1\r\n operator Char: Operation to calculate\r\n "
] |
Please provide a description of the function:def apply_operation(op_stack, out_stack):
out_stack.append(calc(out_stack.pop(), out_stack.pop(), op_stack.pop())) | [
"\r\n Apply operation to the first 2 items of the output queue\r\n\r\n op_stack Deque (reference)\r\n out_stack Deque (reference)\r\n "
] |
Please provide a description of the function:def parse(expression):
result = []
current = ""
for i in expression:
if i.isdigit() or i == '.':
current += i
else:
if len(current) > 0:
result.append(current)
current = ""
... | [
"\r\n Return array of parsed tokens in the expression\r\n\r\n expression String: Math expression to parse in infix notation\r\n "
] |
Please provide a description of the function:def evaluate(expression):
op_stack = deque() # operator stack
out_stack = deque() # output stack (values)
tokens = parse(expression) # calls the function only once!
for token in tokens:
if numeric_value.match(token):
out_stack... | [
"\r\n Calculate result of expression\r\n\r\n expression String: The expression\r\n type Type (optional): Number type [int, float]\r\n "
] |
Please provide a description of the function:def main():
print("\t\tCalculator\n\n")
while True:
user_input = input("expression or exit: ")
if user_input == "exit":
break
try:
print("The result is {0}".format(evaluate(user_input)))
except Exc... | [
"\r\n simple user-interface\r\n "
] |
Please provide a description of the function:def closest_value(root, target):
a = root.val
kid = root.left if target < a else root.right
if not kid:
return a
b = closest_value(kid, target)
return min((a,b), key=lambda x: abs(target-x)) | [
"\n :type root: TreeNode\n :type target: float\n :rtype: int\n "
] |
Please provide a description of the function:def get_primes(n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
# If x is even, exclude x from list (-1):
sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2)
sieve = [True for _ in range(sieve_size)] # Sieve
primes = [] ... | [
"Return list of all primes less than n,\n Using sieve of Eratosthenes.\n "
] |
Please provide a description of the function:def permute(elements):
if len(elements) <= 1:
return [elements]
else:
tmp = []
for perm in permute(elements[1:]):
for i in range(len(elements)):
tmp.append(perm[:i] + elements[0:1] + perm[i:])
return tm... | [
"\n returns a list with the permuations.\n "
] |
Please provide a description of the function:def permute_iter(elements):
if len(elements) <= 1:
yield elements
else:
for perm in permute_iter(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:] | [
"\n iterator: returns a perumation by each call.\n "
] |
Please provide a description of the function:def extended_gcd(a, b):
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = a, b
while r != 0:
quotient = old_r / r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient... | [
"Extended GCD algorithm.\n Return s, t, g\n such that a * s + b * t = GCD(a, b)\n and s and t are co-prime.\n "
] |
Please provide a description of the function:def bin_tree_to_list(root):
if not root:
return root
root = bin_tree_to_list_util(root)
while root.left:
root = root.left
return root | [
"\n type root: root class\n "
] |
Please provide a description of the function:def add_operators(num, target):
def dfs(res, path, num, target, pos, prev, multed):
if pos == len(num):
if target == prev:
res.append(path)
return
for i in range(pos, len(num)):
if i != pos and num... | [
"\n :type num: str\n :type target: int\n :rtype: List[str]\n "
] |
Please provide a description of the function:def _init_rabit():
if _LIB is not None:
_LIB.RabitGetRank.restype = ctypes.c_int
_LIB.RabitGetWorldSize.restype = ctypes.c_int
_LIB.RabitIsDistributed.restype = ctypes.c_int
_LIB.RabitVersionNumber.restype = ctypes.c_int | [
"internal library initializer."
] |
Please provide a description of the function:def init(args=None):
if args is None:
args = []
arr = (ctypes.c_char_p * len(args))()
arr[:] = args
_LIB.RabitInit(len(arr), arr) | [
"Initialize the rabit library with arguments"
] |
Please provide a description of the function:def tracker_print(msg):
if not isinstance(msg, STRING_TYPES):
msg = str(msg)
is_dist = _LIB.RabitIsDistributed()
if is_dist != 0:
_LIB.RabitTrackerPrint(c_str(msg))
else:
sys.stdout.write(msg)
sys.stdout.flush() | [
"Print message to the tracker.\n\n This function can be used to communicate the information of\n the progress to the tracker\n\n Parameters\n ----------\n msg : str\n The message to be printed to tracker.\n "
] |
Please provide a description of the function:def get_processor_name():
mxlen = 256
length = ctypes.c_ulong()
buf = ctypes.create_string_buffer(mxlen)
_LIB.RabitGetProcessorName(buf, ctypes.byref(length), mxlen)
return buf.value | [
"Get the processor name.\n\n Returns\n -------\n name : str\n the name of processor(host)\n "
] |
Please provide a description of the function:def broadcast(data, root):
rank = get_rank()
length = ctypes.c_ulong()
if root == rank:
assert data is not None, 'need to pass in data when broadcasting'
s = pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL)
length.value = len(s)
... | [
"Broadcast object from one node to all other nodes.\n\n Parameters\n ----------\n data : any type that can be pickled\n Input data, if current rank does not equal root, this can be None\n root : int\n Rank of the node to broadcast data from.\n\n Returns\n -------\n object : int\n ... |
Please provide a description of the function:def normpath(path):
normalized = os.path.join(*path.split("/"))
if os.path.isabs(path):
return os.path.abspath("/") + normalized
else:
return normalized | [
"Normalize UNIX path to a native path."
] |
Please provide a description of the function:def _train_internal(params, dtrain,
num_boost_round=10, evals=(),
obj=None, feval=None,
xgb_model=None, callbacks=None):
callbacks = [] if callbacks is None else callbacks
evals = list(evals)
if isi... | [
"internal training function"
] |
Please provide a description of the function:def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None,
maximize=False, early_stopping_rounds=None, evals_result=None,
verbose_eval=True, xgb_model=None, callbacks=None, learning_rates=None):
# pylint: disable=too-many-statements... | [
"Train a booster with given parameters.\n\n Parameters\n ----------\n params : dict\n Booster params.\n dtrain : DMatrix\n Data to be trained.\n num_boost_round: int\n Number of boosting iterations.\n evals: list of pairs (DMatrix, string)\n List of items to be evaluate... |
Please provide a description of the function:def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None, stratified=False,
folds=None, shuffle=True):
evals = list(evals)
np.random.seed(seed)
if stratified is False and folds is None:
# Do standard k-fold cross validation
... | [
"\n Make an n-fold list of CVPack from random indices.\n "
] |
Please provide a description of the function:def aggcv(rlist):
# pylint: disable=invalid-name
cvmap = {}
idx = rlist[0].split()[0]
for line in rlist:
arr = line.split()
assert idx == arr[0]
for it in arr[1:]:
if not isinstance(it, STRING_TYPES):
i... | [
"\n Aggregate cross-validation results.\n\n If verbose_eval is true, progress is displayed in every call. If\n verbose_eval is an integer, progress will only be displayed every\n `verbose_eval` trees, tracked via trial.\n "
] |
Please provide a description of the function:def cv(params, dtrain, num_boost_round=10, nfold=3, stratified=False, folds=None,
metrics=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None,
fpreproc=None, as_pandas=True, verbose_eval=None, show_stdv=True,
seed=0, callbacks=None, shuf... | [
"Cross-validation with given parameters.\n\n Parameters\n ----------\n params : dict\n Booster params.\n dtrain : DMatrix\n Data to be trained.\n num_boost_round : int\n Number of boosting iterations.\n nfold : int\n Number of folds in CV.\n stratified : bool\n ... |
Please provide a description of the function:def update(self, iteration, fobj):
self.bst.update(self.dtrain, iteration, fobj) | [
"\"Update the boosters for one iteration"
] |
Please provide a description of the function:def eval(self, iteration, feval):
return self.bst.eval_set(self.watchlist, iteration, feval) | [
"\"Evaluate the CVPack for one iteration."
] |
Please provide a description of the function:def _get_callback_context(env):
if env.model is not None and env.cvfolds is None:
context = 'train'
elif env.model is None and env.cvfolds is not None:
context = 'cv'
return context | [
"return whether the current callback context is cv or train"
] |
Please provide a description of the function:def _fmt_metric(value, show_stdv=True):
if len(value) == 2:
return '%s:%g' % (value[0], value[1])
if len(value) == 3:
if show_stdv:
return '%s:%g+%g' % (value[0], value[1], value[2])
return '%s:%g' % (value[0], value[1])
r... | [
"format metric string"
] |
Please provide a description of the function:def print_evaluation(period=1, show_stdv=True):
def callback(env):
if env.rank != 0 or (not env.evaluation_result_list) or period is False or period == 0:
return
i = env.iteration
if i % period == 0 or i + 1 == env.begin_... | [
"Create a callback that print evaluation result.\n\n We print the evaluation results every **period** iterations\n and on the first and the last iterations.\n\n Parameters\n ----------\n period : int\n The period to log the evaluation results\n\n show_stdv : bool, optional\n Whether... |
Please provide a description of the function:def record_evaluation(eval_result):
if not isinstance(eval_result, dict):
raise TypeError('eval_result has to be a dictionary')
eval_result.clear()
def init(env):
for k, _ in env.evaluation_result_list:
pos = k.index('-'... | [
"Create a call back that records the evaluation history into **eval_result**.\n\n Parameters\n ----------\n eval_result : dict\n A dictionary to store the evaluation results.\n\n Returns\n -------\n callback : function\n The requested callback function.\n ",
"internal function",
... |
Please provide a description of the function:def reset_learning_rate(learning_rates):
def get_learning_rate(i, n, learning_rates):
if isinstance(learning_rates, list):
if len(learning_rates) != n:
raise ValueError("Length of list 'learning_rates' has to equal 'num_b... | [
"Reset learning rate after iteration 1\n\n NOTE: the initial learning rate will still take in-effect on first iteration.\n\n Parameters\n ----------\n learning_rates: list or function\n List of learning rate for each boosting round\n or a customized function that calculates eta in terms of... |
Please provide a description of the function:def early_stop(stopping_rounds, maximize=False, verbose=True):
state = {}
def init(env):
bst = env.model
if not env.evaluation_result_list:
raise ValueError('For early stopping you need at least one set in evals.')
... | [
"Create a callback that activates early stoppping.\n\n Validation error needs to decrease at least\n every **stopping_rounds** round(s) to continue training.\n Requires at least one item in **evals**.\n If there's more than one, will use the last.\n Returns the model from the last iteration (not the ... |
Please provide a description of the function:def run_doxygen(folder):
try:
retcode = subprocess.call("cd %s; make doxygen" % folder, shell=True)
if retcode < 0:
sys.stderr.write("doxygen terminated by signal %s" % (-retcode))
except OSError as e:
sys.stderr.write("doxygen execution failed: %s" ... | [
"Run the doxygen make command in the designated folder."
] |
Please provide a description of the function:def _objective_decorator(func):
def inner(preds, dmatrix):
labels = dmatrix.get_label()
return func(labels, preds)
return inner | [
"Decorate an objective function\n\n Converts an objective function using the typical sklearn metrics\n signature so that it is usable with ``xgboost.training.train``\n\n Parameters\n ----------\n func: callable\n Expects a callable with signature ``func(y_true, y_pred)``:\n\n y_true: ar... |
Please provide a description of the function:def set_params(self, **params):
if not params:
# Simple optimization to gain speed (inspect is slow)
return self
for key, value in params.items():
if hasattr(self, key):
setattr(self, key, value)
... | [
"Set the parameters of this estimator.\n Modification of the sklearn method to allow unknown kwargs. This allows using\n the full range of xgboost parameters that are not defined as member variables\n in sklearn grid search.\n Returns\n -------\n self\n "
] |
Please provide a description of the function:def get_params(self, deep=False):
params = super(XGBModel, self).get_params(deep=deep)
if isinstance(self.kwargs, dict): # if kwargs is a dict, update params accordingly
params.update(self.kwargs)
if params['missing'] is np.nan:
... | [
"Get parameters."
] |
Please provide a description of the function:def get_xgb_params(self):
xgb_params = self.get_params()
random_state = xgb_params.pop('random_state')
if 'seed' in xgb_params and xgb_params['seed'] is not None:
warnings.warn('The seed parameter is deprecated as of version .6.'
... | [
"Get xgboost type parameters."
] |
Please provide a description of the function:def load_model(self, fname):
if self._Booster is None:
self._Booster = Booster({'nthread': self.n_jobs})
self._Booster.load_model(fname) | [
"\n Load the model from a file.\n\n The model is loaded from an XGBoost internal binary format which is\n universal among the various XGBoost interfaces. Auxiliary attributes of\n the Python Booster object (such as feature names) will not be loaded.\n Label encodings (text labels ... |
Please provide a description of the function:def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
early_stopping_rounds=None, verbose=True, xgb_model=None,
sample_weight_eval_set=None, callbacks=None):
# pylint: disable=missing-docstring,invalid-name,attribute-defined... | [
"\n Fit the gradient boosting model\n\n Parameters\n ----------\n X : array_like\n Feature matrix\n y : array_like\n Labels\n sample_weight : array_like\n instance weights\n eval_set : list, optional\n A list of (X, y) tupl... |
Please provide a description of the function:def predict(self, data, output_margin=False, ntree_limit=None, validate_features=True):
# pylint: disable=missing-docstring,invalid-name
test_dmatrix = DMatrix(data, missing=self.missing, nthread=self.n_jobs)
# get ntree_limit to use - if non... | [
"\n Predict with `data`.\n\n .. note:: This function is not thread safe.\n\n For each booster object, predict can only be called from one thread.\n If you want to run prediction using multiple thread, call ``xgb.copy()`` to make copies\n of model object and then call ``predi... |
Please provide a description of the function:def apply(self, X, ntree_limit=0):
test_dmatrix = DMatrix(X, missing=self.missing, nthread=self.n_jobs)
return self.get_booster().predict(test_dmatrix,
pred_leaf=True,
... | [
"Return the predicted leaf every tree for each sample.\n\n Parameters\n ----------\n X : array_like, shape=[n_samples, n_features]\n Input features matrix.\n\n ntree_limit : int\n Limit number of trees in the prediction; defaults to 0 (use all trees).\n\n Ret... |
Please provide a description of the function:def feature_importances_(self):
if getattr(self, 'booster', None) is not None and self.booster != 'gbtree':
raise AttributeError('Feature importance is not defined for Booster type {}'
.format(self.booster))
... | [
"\n Feature importances property\n\n .. note:: Feature importance is defined only for tree boosters\n\n Feature importance is only defined when the decision tree model is chosen as base\n learner (`booster=gbtree`). It is not defined for other base learner types, such\n ... |
Please provide a description of the function:def coef_(self):
if getattr(self, 'booster', None) is not None and self.booster != 'gblinear':
raise AttributeError('Coefficients are not defined for Booster type {}'
.format(self.booster))
b = self.get_bo... | [
"\n Coefficients property\n\n .. note:: Coefficients are defined only for linear learners\n\n Coefficients are only defined when the linear model is chosen as base\n learner (`booster=gblinear`). It is not defined for other base learner types, such\n as tree learners (... |
Please provide a description of the function:def intercept_(self):
if getattr(self, 'booster', None) is not None and self.booster != 'gblinear':
raise AttributeError('Intercept (bias) is not defined for Booster type {}'
.format(self.booster))
b = sel... | [
"\n Intercept (bias) property\n\n .. note:: Intercept is defined only for linear learners\n\n Intercept (bias) is only defined when the linear model is chosen as base\n learner (`booster=gblinear`). It is not defined for other base learner types, such\n as tree learner... |
Please provide a description of the function:def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
early_stopping_rounds=None, verbose=True, xgb_model=None,
sample_weight_eval_set=None, callbacks=None):
# pylint: disable = attribute-defined-outside-init,arguments-diffe... | [
"\n Fit gradient boosting classifier\n\n Parameters\n ----------\n X : array_like\n Feature matrix\n y : array_like\n Labels\n sample_weight : array_like\n Weight for each instance\n eval_set : list, optional\n A list of (X... |
Please provide a description of the function:def predict(self, data, output_margin=False, ntree_limit=None, validate_features=True):
test_dmatrix = DMatrix(data, missing=self.missing, nthread=self.n_jobs)
if ntree_limit is None:
ntree_limit = getattr(self, "best_ntree_limit", 0)
... | [
"\n Predict with `data`.\n\n .. note:: This function is not thread safe.\n\n For each booster object, predict can only be called from one thread.\n If you want to run prediction using multiple thread, call ``xgb.copy()`` to make copies\n of model object and then call ``predi... |
Please provide a description of the function:def predict_proba(self, data, ntree_limit=None, validate_features=True):
test_dmatrix = DMatrix(data, missing=self.missing, nthread=self.n_jobs)
if ntree_limit is None:
ntree_limit = getattr(self, "best_ntree_limit", 0)
class_prob... | [
"\n Predict the probability of each `data` example being of a given class.\n\n .. note:: This function is not thread safe\n\n For each booster object, predict can only be called from one thread.\n If you want to run prediction using multiple thread, call ``xgb.copy()`` to make co... |
Please provide a description of the function:def fit(self, X, y, group, sample_weight=None, eval_set=None, sample_weight_eval_set=None,
eval_group=None, eval_metric=None, early_stopping_rounds=None,
verbose=False, xgb_model=None, callbacks=None):
# pylint: disable = attribute-defined-out... | [
"\n Fit the gradient boosting model\n\n Parameters\n ----------\n X : array_like\n Feature matrix\n y : array_like\n Labels\n group : array_like\n group size of training data\n sample_weight : array_like\n group weights\n\n... |
Please provide a description of the function:def from_pystr_to_cstr(data):
if not isinstance(data, list):
raise NotImplementedError
pointers = (ctypes.c_char_p * len(data))()
if PY3:
data = [bytes(d, 'utf-8') for d in data]
else:
data = [d.encode('utf-8') if isinstance(d, u... | [
"Convert a list of Python str to C pointer\n\n Parameters\n ----------\n data : list\n list of str\n "
] |
Please provide a description of the function:def from_cstr_to_pystr(data, length):
if PY3:
res = []
for i in range(length.value):
try:
res.append(str(data[i].decode('ascii')))
except UnicodeDecodeError:
res.append(str(data[i].decode('utf-8... | [
"Revert C pointer to Python str\n\n Parameters\n ----------\n data : ctypes pointer\n pointer to data\n length : ctypes pointer\n pointer to length of data\n "
] |
Please provide a description of the function:def _load_lib():
lib_paths = find_lib_path()
if not lib_paths:
return None
try:
pathBackup = os.environ['PATH'].split(os.pathsep)
except KeyError:
pathBackup = []
lib_success = False
os_error_list = []
for lib_path in ... | [
"Load xgboost Library."
] |
Please provide a description of the function:def ctypes2numpy(cptr, length, dtype):
NUMPY_TO_CTYPES_MAPPING = {
np.float32: ctypes.c_float,
np.uint32: ctypes.c_uint,
}
if dtype not in NUMPY_TO_CTYPES_MAPPING:
raise RuntimeError('Supported types: {}'.format(NUMPY_TO_CTYPES_MAPPIN... | [
"Convert a ctypes pointer array to a numpy array.\n "
] |
Please provide a description of the function:def ctypes2buffer(cptr, length):
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
raise RuntimeError('expected char pointer')
res = bytearray(length)
rptr = (ctypes.c_char * length).from_buffer(res)
if not ctypes.memmove(rptr, cptr, length... | [
"Convert ctypes pointer to buffer type."
] |
Please provide a description of the function:def c_array(ctype, values):
if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):
return (ctype * len(values)).from_buffer_copy(values)
return (ctype * len(values))(*values) | [
"Convert a python string to c array."
] |
Please provide a description of the function:def _maybe_pandas_data(data, feature_names, feature_types):
if not isinstance(data, DataFrame):
return data, feature_names, feature_types
data_dtypes = data.dtypes
if not all(dtype.name in PANDAS_DTYPE_MAPPER for dtype in data_dtypes):
bad_... | [
" Extract internal data from pd.DataFrame for DMatrix data ",
"DataFrame.dtypes for data must be int, float or bool.\n Did not expect the data types in fields "
] |
Please provide a description of the function:def _maybe_dt_data(data, feature_names, feature_types):
if not isinstance(data, DataTable):
return data, feature_names, feature_types
data_types_names = tuple(lt.name for lt in data.ltypes)
bad_fields = [data.names[i]
for i, type_n... | [
"\n Validate feature names and types if data table\n ",
"DataFrame.types for data must be int, float or bool.\n Did not expect the data types in fields "
] |
Please provide a description of the function:def _maybe_dt_array(array):
if not isinstance(array, DataTable) or array is None:
return array
if array.shape[1] > 1:
raise ValueError('DataTable for label or weight cannot have multiple columns')
# below requires new dt version
# extra... | [
" Extract numpy array from single column data table "
] |
Please provide a description of the function:def _init_from_csr(self, csr):
if len(csr.indices) != len(csr.data):
raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data)))
handle = ctypes.c_void_p()
_check_call(_LIB.XGDMatrixCreateFromCSREx(c_arra... | [
"\n Initialize data from a CSR matrix.\n "
] |
Please provide a description of the function:def _init_from_csc(self, csc):
if len(csc.indices) != len(csc.data):
raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data)))
handle = ctypes.c_void_p()
_check_call(_LIB.XGDMatrixCreateFromCSCEx(c_arra... | [
"\n Initialize data from a CSC matrix.\n "
] |
Please provide a description of the function:def _init_from_npy2d(self, mat, missing, nthread):
if len(mat.shape) != 2:
raise ValueError('Input numpy.ndarray must be 2 dimensional')
# flatten the array by rows and ensure it is float32.
# we try to avoid data copies if possib... | [
"\n Initialize data from a 2-D numpy matrix.\n\n If ``mat`` does not have ``order='C'`` (aka row-major) or is not contiguous,\n a temporary copy will be made.\n\n If ``mat`` does not have ``dtype=numpy.float32``, a temporary copy will be made.\n\n So there could be as many as two ... |
Please provide a description of the function:def _init_from_dt(self, data, nthread):
ptrs = (ctypes.c_void_p * data.ncols)()
if hasattr(data, "internal") and hasattr(data.internal, "column"):
# datatable>0.8.0
for icol in range(data.ncols):
col = data.int... | [
"\n Initialize data from a datatable Frame.\n "
] |
Please provide a description of the function:def set_float_info(self, field, data):
if getattr(data, 'base', None) is not None and \
data.base is not None and isinstance(data, np.ndarray) \
and isinstance(data.base, np.ndarray) and (not data.flags.c_contiguous):
self.s... | [
"Set float type property into the DMatrix.\n\n Parameters\n ----------\n field: str\n The field name of the information\n\n data: numpy array\n The array of data to be set\n "
] |
Please provide a description of the function:def set_float_info_npy2d(self, field, data):
if getattr(data, 'base', None) is not None and \
data.base is not None and isinstance(data, np.ndarray) \
and isinstance(data.base, np.ndarray) and (not data.flags.c_contiguous):
... | [
"Set float type property into the DMatrix\n for numpy 2d array input\n\n Parameters\n ----------\n field: str\n The field name of the information\n\n data: numpy array\n The array of data to be set\n "
] |
Please provide a description of the function:def set_uint_info(self, field, data):
if getattr(data, 'base', None) is not None and \
data.base is not None and isinstance(data, np.ndarray) \
and isinstance(data.base, np.ndarray) and (not data.flags.c_contiguous):
warning... | [
"Set uint type property into the DMatrix.\n\n Parameters\n ----------\n field: str\n The field name of the information\n\n data: numpy array\n The array of data to be set\n "
] |
Please provide a description of the function:def save_binary(self, fname, silent=True):
_check_call(_LIB.XGDMatrixSaveBinary(self.handle,
c_str(fname),
ctypes.c_int(silent))) | [
"Save DMatrix to an XGBoost buffer. Saved binary can be later loaded\n by providing the path to :py:func:`xgboost.DMatrix` as input.\n\n Parameters\n ----------\n fname : string\n Name of the output buffer file.\n silent : bool (optional; default: True)\n If... |
Please provide a description of the function:def set_group(self, group):
_check_call(_LIB.XGDMatrixSetGroup(self.handle,
c_array(ctypes.c_uint, group),
c_bst_ulong(len(group)))) | [
"Set group size of DMatrix (used for ranking).\n\n Parameters\n ----------\n group : array like\n Group size of each group\n "
] |
Please provide a description of the function:def feature_names(self):
if self._feature_names is None:
self._feature_names = ['f{0}'.format(i) for i in range(self.num_col())]
return self._feature_names | [
"Get feature names (column labels).\n\n Returns\n -------\n feature_names : list or None\n "
] |
Please provide a description of the function:def feature_names(self, feature_names):
if feature_names is not None:
# validate feature name
try:
if not isinstance(feature_names, str):
feature_names = [n for n in iter(feature_names)]
... | [
"Set feature names (column labels).\n\n Parameters\n ----------\n feature_names : list or None\n Labels for features. None will reset existing feature names\n "
] |
Please provide a description of the function:def feature_types(self, feature_types):
if feature_types is not None:
if self._feature_names is None:
msg = 'Unable to set feature types before setting names'
raise ValueError(msg)
if isinstance(featur... | [
"Set feature types (column types).\n\n This is for displaying the results and unrelated\n to the learning process.\n\n Parameters\n ----------\n feature_types : list or None\n Labels for features. None will reset existing feature names\n "
] |
Please provide a description of the function:def load_rabit_checkpoint(self):
version = ctypes.c_int()
_check_call(_LIB.XGBoosterLoadRabitCheckpoint(
self.handle, ctypes.byref(version)))
return version.value | [
"Initialize the model by load from rabit checkpoint.\n\n Returns\n -------\n version: integer\n The version number of the model.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.