repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
getsentry/raven-python | raven/contrib/tornado/__init__.py | SentryMixin.get_sentry_data_from_request | def get_sentry_data_from_request(self):
"""
Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary.
"""
return {
'request': {
'url': self.request.full_u... | python | def get_sentry_data_from_request(self):
"""
Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary.
"""
return {
'request': {
'url': self.request.full_u... | [
"def",
"get_sentry_data_from_request",
"(",
"self",
")",
":",
"return",
"{",
"'request'",
":",
"{",
"'url'",
":",
"self",
".",
"request",
".",
"full_url",
"(",
")",
",",
"'method'",
":",
"self",
".",
"request",
".",
"method",
",",
"'data'",
":",
"self",
... | Extracts the data required for 'sentry.interfaces.Http' from the
current request being handled by the request handler
:param return: A dictionary. | [
"Extracts",
"the",
"data",
"required",
"for",
"sentry",
".",
"interfaces",
".",
"Http",
"from",
"the",
"current",
"request",
"being",
"handled",
"by",
"the",
"request",
"handler"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L147-L163 | train |
getsentry/raven-python | raven/base.py | Client.get_public_dsn | def get_public_dsn(self, scheme=None):
"""
Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https')
"""
if s... | python | def get_public_dsn(self, scheme=None):
"""
Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https')
"""
if s... | [
"def",
"get_public_dsn",
"(",
"self",
",",
"scheme",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_enabled",
"(",
")",
":",
"url",
"=",
"self",
".",
"remote",
".",
"get_public_dsn",
"(",
")",
"if",
"scheme",
":",
"return",
"'%s:%s'",
"%",
"(",
"schem... | Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https') | [
"Returns",
"a",
"public",
"DSN",
"which",
"is",
"consumable",
"by",
"raven",
"-",
"js"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L330-L345 | train |
getsentry/raven-python | raven/base.py | Client.capture | def capture(self, event_type, data=None, date=None, time_spent=None,
extra=None, stack=None, tags=None, sample_rate=None,
**kwargs):
"""
Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
... | python | def capture(self, event_type, data=None, date=None, time_spent=None,
extra=None, stack=None, tags=None, sample_rate=None,
**kwargs):
"""
Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
... | [
"def",
"capture",
"(",
"self",
",",
"event_type",
",",
"data",
"=",
"None",
",",
"date",
"=",
"None",
",",
"time_spent",
"=",
"None",
",",
"extra",
"=",
"None",
",",
"stack",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"sample_rate",
"=",
"None",
"... | Captures and processes an event and pipes it off to SentryClient.send.
To use structured data (interfaces) with capture:
>>> capture('raven.events.Message', message='foo', data={
>>> 'request': {
>>> 'url': '...',
>>> 'data': {},
>>> 'query_s... | [
"Captures",
"and",
"processes",
"an",
"event",
"and",
"pipes",
"it",
"off",
"to",
"SentryClient",
".",
"send",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L577-L657 | train |
getsentry/raven-python | raven/base.py | Client._log_failed_submission | def _log_failed_submission(self, data):
"""
Log a reasonable representation of an event that should have been sent
to Sentry
"""
message = data.pop('message', '<no message value>')
output = [message]
if 'exception' in data and 'stacktrace' in data['exception']['va... | python | def _log_failed_submission(self, data):
"""
Log a reasonable representation of an event that should have been sent
to Sentry
"""
message = data.pop('message', '<no message value>')
output = [message]
if 'exception' in data and 'stacktrace' in data['exception']['va... | [
"def",
"_log_failed_submission",
"(",
"self",
",",
"data",
")",
":",
"message",
"=",
"data",
".",
"pop",
"(",
"'message'",
",",
"'<no message value>'",
")",
"output",
"=",
"[",
"message",
"]",
"if",
"'exception'",
"in",
"data",
"and",
"'stacktrace'",
"in",
... | Log a reasonable representation of an event that should have been sent
to Sentry | [
"Log",
"a",
"reasonable",
"representation",
"of",
"an",
"event",
"that",
"should",
"have",
"been",
"sent",
"to",
"Sentry"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L696-L712 | train |
getsentry/raven-python | raven/base.py | Client.send_encoded | def send_encoded(self, message, auth_header=None, **kwargs):
"""
Given an already serialized message, signs the message and passes the
payload off to ``send_remote``.
"""
client_string = 'raven-python/%s' % (raven.VERSION,)
if not auth_header:
timestamp = tim... | python | def send_encoded(self, message, auth_header=None, **kwargs):
"""
Given an already serialized message, signs the message and passes the
payload off to ``send_remote``.
"""
client_string = 'raven-python/%s' % (raven.VERSION,)
if not auth_header:
timestamp = tim... | [
"def",
"send_encoded",
"(",
"self",
",",
"message",
",",
"auth_header",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"client_string",
"=",
"'raven-python/%s'",
"%",
"(",
"raven",
".",
"VERSION",
",",
")",
"if",
"not",
"auth_header",
":",
"timestamp",
"=",
... | Given an already serialized message, signs the message and passes the
payload off to ``send_remote``. | [
"Given",
"an",
"already",
"serialized",
"message",
"signs",
"the",
"message",
"and",
"passes",
"the",
"payload",
"off",
"to",
"send_remote",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L752-L781 | train |
getsentry/raven-python | raven/base.py | Client.captureQuery | def captureQuery(self, query, params=(), engine=None, **kwargs):
"""
Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo')
"""
return self.capture(
'raven.events.Query', query=query, params=params, engine=engine,
**kwargs) | python | def captureQuery(self, query, params=(), engine=None, **kwargs):
"""
Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo')
"""
return self.capture(
'raven.events.Query', query=query, params=params, engine=engine,
**kwargs) | [
"def",
"captureQuery",
"(",
"self",
",",
"query",
",",
"params",
"=",
"(",
")",
",",
"engine",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"return",
"self",
".",
"capture",
"(",
"'raven.events.Query'",
",",
"query",
"=",
"query",
",",
"params",
"=",
... | Creates an event for a SQL query.
>>> client.captureQuery('SELECT * FROM foo') | [
"Creates",
"an",
"event",
"for",
"a",
"SQL",
"query",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L892-L900 | train |
getsentry/raven-python | raven/base.py | Client.captureBreadcrumb | def captureBreadcrumb(self, *args, **kwargs):
"""
Records a breadcrumb with the current context. They will be
sent with the next event.
"""
# Note: framework integration should not call this method but
# instead use the raven.breadcrumbs.record_breadcrumb function
... | python | def captureBreadcrumb(self, *args, **kwargs):
"""
Records a breadcrumb with the current context. They will be
sent with the next event.
"""
# Note: framework integration should not call this method but
# instead use the raven.breadcrumbs.record_breadcrumb function
... | [
"def",
"captureBreadcrumb",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"context",
".",
"breadcrumbs",
".",
"record",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | Records a breadcrumb with the current context. They will be
sent with the next event. | [
"Records",
"a",
"breadcrumb",
"with",
"the",
"current",
"context",
".",
"They",
"will",
"be",
"sent",
"with",
"the",
"next",
"event",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L908-L916 | train |
getsentry/raven-python | raven/transport/registry.py | TransportRegistry.register_scheme | def register_scheme(self, scheme, cls):
"""
It is possible to inject new schemes at runtime
"""
if scheme in self._schemes:
raise DuplicateScheme()
urlparse.register_scheme(scheme)
# TODO (vng): verify the interface of the new class
self._schemes[sche... | python | def register_scheme(self, scheme, cls):
"""
It is possible to inject new schemes at runtime
"""
if scheme in self._schemes:
raise DuplicateScheme()
urlparse.register_scheme(scheme)
# TODO (vng): verify the interface of the new class
self._schemes[sche... | [
"def",
"register_scheme",
"(",
"self",
",",
"scheme",
",",
"cls",
")",
":",
"if",
"scheme",
"in",
"self",
".",
"_schemes",
":",
"raise",
"DuplicateScheme",
"(",
")",
"urlparse",
".",
"register_scheme",
"(",
"scheme",
")",
"self",
".",
"_schemes",
"[",
"s... | It is possible to inject new schemes at runtime | [
"It",
"is",
"possible",
"to",
"inject",
"new",
"schemes",
"at",
"runtime"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/registry.py#L40-L49 | train |
getsentry/raven-python | raven/contrib/flask.py | Sentry.get_http_info | def get_http_info(self, request):
"""
Determine how to retrieve actual data by using request.mimetype.
"""
if self.is_json_type(request.mimetype):
retriever = self.get_json_data
else:
retriever = self.get_form_data
return self.get_http_info_with_re... | python | def get_http_info(self, request):
"""
Determine how to retrieve actual data by using request.mimetype.
"""
if self.is_json_type(request.mimetype):
retriever = self.get_json_data
else:
retriever = self.get_form_data
return self.get_http_info_with_re... | [
"def",
"get_http_info",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"is_json_type",
"(",
"request",
".",
"mimetype",
")",
":",
"retriever",
"=",
"self",
".",
"get_json_data",
"else",
":",
"retriever",
"=",
"self",
".",
"get_form_data",
"retur... | Determine how to retrieve actual data by using request.mimetype. | [
"Determine",
"how",
"to",
"retrieve",
"actual",
"data",
"by",
"using",
"request",
".",
"mimetype",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/flask.py#L194-L202 | train |
getsentry/raven-python | raven/conf/__init__.py | setup_logging | def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
"""
Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logg... | python | def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
"""
Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logg... | [
"def",
"setup_logging",
"(",
"handler",
",",
"exclude",
"=",
"EXCLUDE_LOGGER_DEFAULTS",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"handler",
".",
"__class__",
"in",
"map",
"(",
"type",
",",
"logger",
".",
"handlers",
")",
":",
... | Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logging(SentryHandler(client))
Within Django:
>>> from raven.contri... | [
"Configures",
"logging",
"to",
"pipe",
"to",
"Sentry",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/conf/__init__.py#L26-L57 | train |
getsentry/raven-python | raven/utils/stacks.py | to_dict | def to_dict(dictish):
"""
Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary.
"""
if hasattr(dictish, 'iterkeys'):
m = dictish.iterkeys
elif hasattr(dictish, 'keys'):
m = dictish.keys
else:
raise ValueError(dictish)
... | python | def to_dict(dictish):
"""
Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary.
"""
if hasattr(dictish, 'iterkeys'):
m = dictish.iterkeys
elif hasattr(dictish, 'keys'):
m = dictish.keys
else:
raise ValueError(dictish)
... | [
"def",
"to_dict",
"(",
"dictish",
")",
":",
"if",
"hasattr",
"(",
"dictish",
",",
"'iterkeys'",
")",
":",
"m",
"=",
"dictish",
".",
"iterkeys",
"elif",
"hasattr",
"(",
"dictish",
",",
"'keys'",
")",
":",
"m",
"=",
"dictish",
".",
"keys",
"else",
":",... | Given something that closely resembles a dictionary, we attempt
to coerce it into a propery dictionary. | [
"Given",
"something",
"that",
"closely",
"resembles",
"a",
"dictionary",
"we",
"attempt",
"to",
"coerce",
"it",
"into",
"a",
"propery",
"dictionary",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L96-L108 | train |
getsentry/raven-python | raven/utils/stacks.py | slim_frame_data | def slim_frame_data(frames, frame_allowance=25):
"""
Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``.
"""
frames_len = 0
app_frames = []
system_frames = []
for frame in frames:
frames_len += 1
if frame.get('i... | python | def slim_frame_data(frames, frame_allowance=25):
"""
Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``.
"""
frames_len = 0
app_frames = []
system_frames = []
for frame in frames:
frames_len += 1
if frame.get('i... | [
"def",
"slim_frame_data",
"(",
"frames",
",",
"frame_allowance",
"=",
"25",
")",
":",
"frames_len",
"=",
"0",
"app_frames",
"=",
"[",
"]",
"system_frames",
"=",
"[",
"]",
"for",
"frame",
"in",
"frames",
":",
"frames_len",
"+=",
"1",
"if",
"frame",
".",
... | Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``. | [
"Removes",
"various",
"excess",
"metadata",
"from",
"middle",
"frames",
"which",
"go",
"beyond",
"frame_allowance",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L167-L215 | train |
getsentry/raven-python | raven/contrib/webpy/utils.py | get_data_from_request | def get_data_from_request():
"""Returns request data extracted from web.ctx."""
return {
'request': {
'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']),
'query_string': web.ctx.query,
'method': web.ctx.method,
'data': web.data(),... | python | def get_data_from_request():
"""Returns request data extracted from web.ctx."""
return {
'request': {
'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']),
'query_string': web.ctx.query,
'method': web.ctx.method,
'data': web.data(),... | [
"def",
"get_data_from_request",
"(",
")",
":",
"return",
"{",
"'request'",
":",
"{",
"'url'",
":",
"'%s://%s%s'",
"%",
"(",
"web",
".",
"ctx",
"[",
"'protocol'",
"]",
",",
"web",
".",
"ctx",
"[",
"'host'",
"]",
",",
"web",
".",
"ctx",
"[",
"'path'",
... | Returns request data extracted from web.ctx. | [
"Returns",
"request",
"data",
"extracted",
"from",
"web",
".",
"ctx",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/webpy/utils.py#L15-L26 | train |
getsentry/raven-python | raven/contrib/django/resolver.py | get_regex | def get_regex(resolver_or_pattern):
"""Utility method for django's deprecated resolver.regex"""
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | python | def get_regex(resolver_or_pattern):
"""Utility method for django's deprecated resolver.regex"""
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | [
"def",
"get_regex",
"(",
"resolver_or_pattern",
")",
":",
"try",
":",
"regex",
"=",
"resolver_or_pattern",
".",
"regex",
"except",
"AttributeError",
":",
"regex",
"=",
"resolver_or_pattern",
".",
"pattern",
".",
"regex",
"return",
"regex"
] | Utility method for django's deprecated resolver.regex | [
"Utility",
"method",
"for",
"django",
"s",
"deprecated",
"resolver",
".",
"regex"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/resolver.py#L11-L17 | train |
getsentry/raven-python | raven/utils/basic.py | once | def once(func):
"""Runs a thing once and once only."""
lock = threading.Lock()
def new_func(*args, **kwargs):
if new_func.called:
return
with lock:
if new_func.called:
return
rv = func(*args, **kwargs)
new_func.called = True
... | python | def once(func):
"""Runs a thing once and once only."""
lock = threading.Lock()
def new_func(*args, **kwargs):
if new_func.called:
return
with lock:
if new_func.called:
return
rv = func(*args, **kwargs)
new_func.called = True
... | [
"def",
"once",
"(",
"func",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"new_func",
".",
"called",
":",
"return",
"with",
"lock",
":",
"if",
"new_func",
".",
... | Runs a thing once and once only. | [
"Runs",
"a",
"thing",
"once",
"and",
"once",
"only",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/basic.py#L75-L91 | train |
getsentry/raven-python | raven/contrib/django/utils.py | get_host | def get_host(request):
"""
A reimplementation of Django's get_host, without the
SuspiciousOperation check.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in request.META):
host = request.META['HTTP... | python | def get_host(request):
"""
A reimplementation of Django's get_host, without the
SuspiciousOperation check.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in request.META):
host = request.META['HTTP... | [
"def",
"get_host",
"(",
"request",
")",
":",
"if",
"settings",
".",
"USE_X_FORWARDED_HOST",
"and",
"(",
"'HTTP_X_FORWARDED_HOST'",
"in",
"request",
".",
"META",
")",
":",
"host",
"=",
"request",
".",
"META",
"[",
"'HTTP_X_FORWARDED_HOST'",
"]",
"elif",
"'HTTP_... | A reimplementation of Django's get_host, without the
SuspiciousOperation check. | [
"A",
"reimplementation",
"of",
"Django",
"s",
"get_host",
"without",
"the",
"SuspiciousOperation",
"check",
"."
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/utils.py#L84-L101 | train |
getsentry/raven-python | raven/contrib/django/models.py | install_middleware | def install_middleware(middleware_name, lookup_names=None):
"""
Install specified middleware
"""
if lookup_names is None:
lookup_names = (middleware_name,)
# default settings.MIDDLEWARE is None
middleware_attr = 'MIDDLEWARE' if getattr(settings,
... | python | def install_middleware(middleware_name, lookup_names=None):
"""
Install specified middleware
"""
if lookup_names is None:
lookup_names = (middleware_name,)
# default settings.MIDDLEWARE is None
middleware_attr = 'MIDDLEWARE' if getattr(settings,
... | [
"def",
"install_middleware",
"(",
"middleware_name",
",",
"lookup_names",
"=",
"None",
")",
":",
"if",
"lookup_names",
"is",
"None",
":",
"lookup_names",
"=",
"(",
"middleware_name",
",",
")",
"middleware_attr",
"=",
"'MIDDLEWARE'",
"if",
"getattr",
"(",
"settin... | Install specified middleware | [
"Install",
"specified",
"middleware"
] | d891c20f0f930153f508e9d698d9de42e910face | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/models.py#L222-L238 | train |
sebp/scikit-survival | sksurv/meta/base.py | _fit_and_score | def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params):
"""Train survival model on given data and return its score on test data"""
X_train, y_train = _safe_split(est, x, y, train_index)
train_params = fit_params.copy()
# Training
est.set_params(**para... | python | def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params):
"""Train survival model on given data and return its score on test data"""
X_train, y_train = _safe_split(est, x, y, train_index)
train_params = fit_params.copy()
# Training
est.set_params(**para... | [
"def",
"_fit_and_score",
"(",
"est",
",",
"x",
",",
"y",
",",
"scorer",
",",
"train_index",
",",
"test_index",
",",
"parameters",
",",
"fit_params",
",",
"predict_params",
")",
":",
"X_train",
",",
"y_train",
"=",
"_safe_split",
"(",
"est",
",",
"x",
","... | Train survival model on given data and return its score on test data | [
"Train",
"survival",
"model",
"on",
"given",
"data",
"and",
"return",
"its",
"score",
"on",
"test",
"data"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/base.py#L17-L35 | train |
sebp/scikit-survival | sksurv/linear_model/coxnet.py | CoxnetSurvivalAnalysis._interpolate_coefficients | def _interpolate_coefficients(self, alpha):
"""Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training."""
exact = False
coef_idx = None
for i, val in enumerate(self.... | python | def _interpolate_coefficients(self, alpha):
"""Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training."""
exact = False
coef_idx = None
for i, val in enumerate(self.... | [
"def",
"_interpolate_coefficients",
"(",
"self",
",",
"alpha",
")",
":",
"exact",
"=",
"False",
"coef_idx",
"=",
"None",
"for",
"i",
",",
"val",
"in",
"enumerate",
"(",
"self",
".",
"alphas_",
")",
":",
"if",
"val",
">",
"alpha",
":",
"coef_idx",
"=",
... | Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to
neighbors of alpha in the list of alphas constructed during training. | [
"Interpolate",
"coefficients",
"by",
"calculating",
"the",
"weighted",
"average",
"of",
"coefficient",
"vectors",
"corresponding",
"to",
"neighbors",
"of",
"alpha",
"in",
"the",
"list",
"of",
"alphas",
"constructed",
"during",
"training",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L239-L263 | train |
sebp/scikit-survival | sksurv/linear_model/coxnet.py | CoxnetSurvivalAnalysis.predict | def predict(self, X, alpha=None):
"""The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty... | python | def predict(self, X, alpha=None):
"""The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty... | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"alpha",
"=",
"None",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
")",
"coef",
"=",
"self",
".",
"_get_coef",
"(",
"alpha",
")",
"return",
"numpy",
".",
"dot",
"(",
"X",
",",
"coef",
")"
] | The linear predictor of the model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test data of which to calculate log-likelihood from
alpha : float, optional
Constant that multiplies the penalty terms. If the same alpha was used during tra... | [
"The",
"linear",
"predictor",
"of",
"the",
"model",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L265-L285 | train |
sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._create_base_ensemble | def _create_base_ensemble(self, out, n_estimators, n_folds):
"""For each base estimator collect models trained on each fold"""
ensemble_scores = numpy.empty((n_estimators, n_folds))
base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object)
for model, fold, score, est in out:
... | python | def _create_base_ensemble(self, out, n_estimators, n_folds):
"""For each base estimator collect models trained on each fold"""
ensemble_scores = numpy.empty((n_estimators, n_folds))
base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object)
for model, fold, score, est in out:
... | [
"def",
"_create_base_ensemble",
"(",
"self",
",",
"out",
",",
"n_estimators",
",",
"n_folds",
")",
":",
"ensemble_scores",
"=",
"numpy",
".",
"empty",
"(",
"(",
"n_estimators",
",",
"n_folds",
")",
")",
"base_ensemble",
"=",
"numpy",
".",
"empty_like",
"(",
... | For each base estimator collect models trained on each fold | [
"For",
"each",
"base",
"estimator",
"collect",
"models",
"trained",
"on",
"each",
"fold"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L152-L160 | train |
sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._create_cv_ensemble | def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None):
"""For each selected base estimator, average models trained on each fold"""
fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object)
for i, idx in enumerate(idx_models_included):
mod... | python | def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None):
"""For each selected base estimator, average models trained on each fold"""
fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object)
for i, idx in enumerate(idx_models_included):
mod... | [
"def",
"_create_cv_ensemble",
"(",
"self",
",",
"base_ensemble",
",",
"idx_models_included",
",",
"model_names",
"=",
"None",
")",
":",
"fitted_models",
"=",
"numpy",
".",
"empty",
"(",
"len",
"(",
"idx_models_included",
")",
",",
"dtype",
"=",
"numpy",
".",
... | For each selected base estimator, average models trained on each fold | [
"For",
"each",
"selected",
"base",
"estimator",
"average",
"models",
"trained",
"on",
"each",
"fold"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L162-L170 | train |
sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._get_base_estimators | def _get_base_estimators(self, X):
"""Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
... | python | def _get_base_estimators(self, X):
"""Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
... | [
"def",
"_get_base_estimators",
"(",
"self",
",",
"X",
")",
":",
"base_estimators",
"=",
"[",
"]",
"kernel_cache",
"=",
"{",
"}",
"kernel_fns",
"=",
"{",
"}",
"for",
"i",
",",
"(",
"name",
",",
"estimator",
")",
"in",
"enumerate",
"(",
"self",
".",
"b... | Takes special care of estimators using custom kernel function
Parameters
----------
X : array, shape = (n_samples, n_features)
Samples to pre-compute kernel matrix from.
Returns
-------
base_estimators : list
Same as `self.base_estimators`, expec... | [
"Takes",
"special",
"care",
"of",
"estimators",
"using",
"custom",
"kernel",
"function"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L172-L214 | train |
sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._restore_base_estimators | def _restore_base_estimators(self, kernel_cache, out, X, cv):
"""Restore custom kernel functions of estimators for predictions"""
train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)}
for idx, fold, _, est in out:
if idx in kernel_cache:
if no... | python | def _restore_base_estimators(self, kernel_cache, out, X, cv):
"""Restore custom kernel functions of estimators for predictions"""
train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)}
for idx, fold, _, est in out:
if idx in kernel_cache:
if no... | [
"def",
"_restore_base_estimators",
"(",
"self",
",",
"kernel_cache",
",",
"out",
",",
"X",
",",
"cv",
")",
":",
"train_folds",
"=",
"{",
"fold",
":",
"train_index",
"for",
"fold",
",",
"(",
"train_index",
",",
"_",
")",
"in",
"enumerate",
"(",
"cv",
")... | Restore custom kernel functions of estimators for predictions | [
"Restore",
"custom",
"kernel",
"functions",
"of",
"estimators",
"for",
"predictions"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L216-L230 | train |
sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection._fit_and_score_ensemble | def _fit_and_score_ensemble(self, X, y, cv, **fit_params):
"""Create a cross-validated model by training a model for each fold with the same model parameters"""
fit_params_steps = self._split_fit_params(fit_params)
folds = list(cv.split(X, y))
# Take care of custom kernel functions
... | python | def _fit_and_score_ensemble(self, X, y, cv, **fit_params):
"""Create a cross-validated model by training a model for each fold with the same model parameters"""
fit_params_steps = self._split_fit_params(fit_params)
folds = list(cv.split(X, y))
# Take care of custom kernel functions
... | [
"def",
"_fit_and_score_ensemble",
"(",
"self",
",",
"X",
",",
"y",
",",
"cv",
",",
"**",
"fit_params",
")",
":",
"fit_params_steps",
"=",
"self",
".",
"_split_fit_params",
"(",
"fit_params",
")",
"folds",
"=",
"list",
"(",
"cv",
".",
"split",
"(",
"X",
... | Create a cross-validated model by training a model for each fold with the same model parameters | [
"Create",
"a",
"cross",
"-",
"validated",
"model",
"by",
"training",
"a",
"model",
"for",
"each",
"fold",
"with",
"the",
"same",
"model",
"parameters"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L232-L257 | train |
sebp/scikit-survival | sksurv/meta/ensemble_selection.py | BaseEnsembleSelection.fit | def fit(self, X, y=None, **fit_params):
"""Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
------... | python | def fit(self, X, y=None, **fit_params):
"""Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
------... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"**",
"fit_params",
")",
":",
"self",
".",
"_check_params",
"(",
")",
"cv",
"=",
"check_cv",
"(",
"self",
".",
"cv",
",",
"X",
")",
"self",
".",
"_fit",
"(",
"X",
",",
"y",
",",... | Fit ensemble of models
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self | [
"Fit",
"ensemble",
"of",
"models"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L277-L297 | train |
sebp/scikit-survival | sksurv/io/arffwrite.py | writearff | def writearff(data, filename, relation_name=None, index=True):
"""Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is ... | python | def writearff(data, filename, relation_name=None, index=True):
"""Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is ... | [
"def",
"writearff",
"(",
"data",
",",
"filename",
",",
"relation_name",
"=",
"None",
",",
"index",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"if",
"relation_... | Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is closed by calling this function.
relation_name : string, optional... | [
"Write",
"ARFF",
"file"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L23-L57 | train |
sebp/scikit-survival | sksurv/io/arffwrite.py | _write_header | def _write_header(data, fp, relation_name, index):
"""Write header containing attribute names and types"""
fp.write("@relation {0}\n\n".format(relation_name))
if index:
data = data.reset_index()
attribute_names = _sanitize_column_names(data)
for column, series in data.iteritems():
... | python | def _write_header(data, fp, relation_name, index):
"""Write header containing attribute names and types"""
fp.write("@relation {0}\n\n".format(relation_name))
if index:
data = data.reset_index()
attribute_names = _sanitize_column_names(data)
for column, series in data.iteritems():
... | [
"def",
"_write_header",
"(",
"data",
",",
"fp",
",",
"relation_name",
",",
"index",
")",
":",
"fp",
".",
"write",
"(",
"\"@relation {0}\\n\\n\"",
".",
"format",
"(",
"relation_name",
")",
")",
"if",
"index",
":",
"data",
"=",
"data",
".",
"reset_index",
... | Write header containing attribute names and types | [
"Write",
"header",
"containing",
"attribute",
"names",
"and",
"types"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L60-L85 | train |
sebp/scikit-survival | sksurv/io/arffwrite.py | _sanitize_column_names | def _sanitize_column_names(data):
"""Replace illegal characters with underscore"""
new_names = {}
for name in data.columns:
new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name)
return new_names | python | def _sanitize_column_names(data):
"""Replace illegal characters with underscore"""
new_names = {}
for name in data.columns:
new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name)
return new_names | [
"def",
"_sanitize_column_names",
"(",
"data",
")",
":",
"new_names",
"=",
"{",
"}",
"for",
"name",
"in",
"data",
".",
"columns",
":",
"new_names",
"[",
"name",
"]",
"=",
"_ILLEGAL_CHARACTER_PAT",
".",
"sub",
"(",
"\"_\"",
",",
"name",
")",
"return",
"new... | Replace illegal characters with underscore | [
"Replace",
"illegal",
"characters",
"with",
"underscore"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L88-L93 | train |
sebp/scikit-survival | sksurv/io/arffwrite.py | _write_data | def _write_data(data, fp):
"""Write the data section"""
fp.write("@data\n")
def to_str(x):
if pandas.isnull(x):
return '?'
else:
return str(x)
data = data.applymap(to_str)
n_rows = data.shape[0]
for i in range(n_rows):
str_values = list(data.iloc... | python | def _write_data(data, fp):
"""Write the data section"""
fp.write("@data\n")
def to_str(x):
if pandas.isnull(x):
return '?'
else:
return str(x)
data = data.applymap(to_str)
n_rows = data.shape[0]
for i in range(n_rows):
str_values = list(data.iloc... | [
"def",
"_write_data",
"(",
"data",
",",
"fp",
")",
":",
"fp",
".",
"write",
"(",
"\"@data\\n\"",
")",
"def",
"to_str",
"(",
"x",
")",
":",
"if",
"pandas",
".",
"isnull",
"(",
"x",
")",
":",
"return",
"'?'",
"else",
":",
"return",
"str",
"(",
"x",... | Write the data section | [
"Write",
"the",
"data",
"section"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L130-L146 | train |
sebp/scikit-survival | sksurv/meta/stacking.py | Stacking.fit | def fit(self, X, y=None, **fit_params):
"""Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
... | python | def fit(self, X, y=None, **fit_params):
"""Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"**",
"fit_params",
")",
":",
"X",
"=",
"numpy",
".",
"asarray",
"(",
"X",
")",
"self",
".",
"_fit_estimators",
"(",
"X",
",",
"y",
",",
"**",
"fit_params",
")",
"Xt",
"=",
"self"... | Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
self | [
"Fit",
"base",
"estimators",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/stacking.py#L115-L135 | train |
sebp/scikit-survival | sksurv/column.py | standardize | def standardize(table, with_std=True):
"""
Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not... | python | def standardize(table, with_std=True):
"""
Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not... | [
"def",
"standardize",
"(",
"table",
",",
"with_std",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"DataFrame",
")",
":",
"cat_columns",
"=",
"table",
".",
"select_dtypes",
"(",
"include",
"=",
"[",
"'category'",
"]",
")",
... | Perform Z-Normalization on each numeric column of the given table.
Parameters
----------
table : pandas.DataFrame or numpy.ndarray
Data to standardize.
with_std : bool, optional, default: True
If ``False`` data is only centered and not converted to unit variance.
Returns
-----... | [
"Perform",
"Z",
"-",
"Normalization",
"on",
"each",
"numeric",
"column",
"of",
"the",
"given",
"table",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L47-L77 | train |
sebp/scikit-survival | sksurv/column.py | encode_categorical | def encode_categorical(table, columns=None, **kwargs):
"""
Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, defa... | python | def encode_categorical(table, columns=None, **kwargs):
"""
Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, defa... | [
"def",
"encode_categorical",
"(",
"table",
",",
"columns",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"Series",
")",
":",
"if",
"not",
"is_categorical_dtype",
"(",
"table",
".",
"dtype",
")",
"and",
... | Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, default: None
Column names in the DataFrame to be encoded.
... | [
"Encode",
"categorical",
"columns",
"with",
"M",
"categories",
"into",
"M",
"-",
"1",
"columns",
"according",
"to",
"the",
"one",
"-",
"hot",
"scheme",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L97-L146 | train |
sebp/scikit-survival | sksurv/column.py | categorical_to_numeric | def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with ca... | python | def categorical_to_numeric(table):
"""Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with ca... | [
"def",
"categorical_to_numeric",
"(",
"table",
")",
":",
"def",
"transform",
"(",
"column",
")",
":",
"if",
"is_categorical_dtype",
"(",
"column",
".",
"dtype",
")",
":",
"return",
"column",
".",
"cat",
".",
"codes",
"if",
"column",
".",
"dtype",
".",
"c... | Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
... | [
"Encode",
"categorical",
"columns",
"to",
"numeric",
"by",
"converting",
"each",
"category",
"to",
"an",
"integer",
"value",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L171-L208 | train |
sebp/scikit-survival | sksurv/util.py | check_y_survival | def check_y_survival(y_or_event, *args, allow_all_censored=False):
"""Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
... | python | def check_y_survival(y_or_event, *args, allow_all_censored=False):
"""Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
... | [
"def",
"check_y_survival",
"(",
"y_or_event",
",",
"*",
"args",
",",
"allow_all_censored",
"=",
"False",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"y",
"=",
"y_or_event",
"if",
"not",
"isinstance",
"(",
"y",
",",
"numpy",
".",
"ndarray",... | Check that array correctly represents an outcome for survival analysis.
Parameters
----------
y_or_event : structured array with two fields, or boolean array
If a structured array, it must contain the binary event indicator
as first field, and time of event or time of censoring as
s... | [
"Check",
"that",
"array",
"correctly",
"represents",
"an",
"outcome",
"for",
"survival",
"analysis",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L104-L164 | train |
sebp/scikit-survival | sksurv/util.py | check_arrays_survival | def check_arrays_survival(X, y, **kwargs):
"""Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
a... | python | def check_arrays_survival(X, y, **kwargs):
"""Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
a... | [
"def",
"check_arrays_survival",
"(",
"X",
",",
"y",
",",
"**",
"kwargs",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
")",
"kwargs",
".",
"setdefault",
"(",
"\"dtype\"",
",",
"numpy",
".",
"float64",
")",
"X",
"=",
"check_array",
... | Check that all arrays have consistent first dimensions.
Parameters
----------
X : array-like
Data matrix containing feature vectors.
y : structured array with two fields
A structured array containing the binary event indicator
as first field, and time of event or time of censor... | [
"Check",
"that",
"all",
"arrays",
"have",
"consistent",
"first",
"dimensions",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L167-L198 | train |
sebp/scikit-survival | sksurv/util.py | Surv.from_arrays | def from_arrays(event, time, name_event=None, name_time=None):
"""Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
... | python | def from_arrays(event, time, name_event=None, name_time=None):
"""Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
... | [
"def",
"from_arrays",
"(",
"event",
",",
"time",
",",
"name_event",
"=",
"None",
",",
"name_time",
"=",
"None",
")",
":",
"name_event",
"=",
"name_event",
"or",
"'event'",
"name_time",
"=",
"name_time",
"or",
"'time'",
"if",
"name_time",
"==",
"name_event",
... | Create structured array.
Parameters
----------
event : array-like
Event indicator. A boolean array or array with values 0/1.
time : array-like
Observed time.
name_event : str|None
Name of event, optional, default: 'event'
name_time : s... | [
"Create",
"structured",
"array",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L28-L73 | train |
sebp/scikit-survival | sksurv/util.py | Surv.from_dataframe | def from_dataframe(event, time, data):
"""Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
... | python | def from_dataframe(event, time, data):
"""Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
... | [
"def",
"from_dataframe",
"(",
"event",
",",
"time",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"pandas",
".",
"DataFrame",
")",
":",
"raise",
"TypeError",
"(",
"\"exepected pandas.DataFrame, but got {!r}\"",
".",
"format",
"(",
"type",... | Create structured array from data frame.
Parameters
----------
event : object
Identifier of column containing event indicator.
time : object
Identifier of column containing time.
data : pandas.DataFrame
Dataset.
Returns
------... | [
"Create",
"structured",
"array",
"from",
"data",
"frame",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L76-L101 | train |
sebp/scikit-survival | sksurv/ensemble/survival_loss.py | CoxPH.update_terminal_regions | def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
"""Least squares does not need to update terminal regions.
But it has to update the predictions.
"""
# upd... | python | def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
"""Least squares does not need to update terminal regions.
But it has to update the predictions.
"""
# upd... | [
"def",
"update_terminal_regions",
"(",
"self",
",",
"tree",
",",
"X",
",",
"y",
",",
"residual",
",",
"y_pred",
",",
"sample_weight",
",",
"sample_mask",
",",
"learning_rate",
"=",
"1.0",
",",
"k",
"=",
"0",
")",
":",
"y_pred",
"[",
":",
",",
"k",
"]... | Least squares does not need to update terminal regions.
But it has to update the predictions. | [
"Least",
"squares",
"does",
"not",
"need",
"to",
"update",
"terminal",
"regions",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/survival_loss.py#L55-L63 | train |
sebp/scikit-survival | sksurv/setup.py | build_from_c_and_cpp_files | def build_from_c_and_cpp_files(extensions):
"""Modify the extensions to build from the .c and .cpp files.
This is useful for releases, this way cython is not required to
run python setup.py install.
"""
for extension in extensions:
sources = []
for sfile in extension.sources:
... | python | def build_from_c_and_cpp_files(extensions):
"""Modify the extensions to build from the .c and .cpp files.
This is useful for releases, this way cython is not required to
run python setup.py install.
"""
for extension in extensions:
sources = []
for sfile in extension.sources:
... | [
"def",
"build_from_c_and_cpp_files",
"(",
"extensions",
")",
":",
"for",
"extension",
"in",
"extensions",
":",
"sources",
"=",
"[",
"]",
"for",
"sfile",
"in",
"extension",
".",
"sources",
":",
"path",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
... | Modify the extensions to build from the .c and .cpp files.
This is useful for releases, this way cython is not required to
run python setup.py install. | [
"Modify",
"the",
"extensions",
"to",
"build",
"from",
"the",
".",
"c",
"and",
".",
"cpp",
"files",
".",
"This",
"is",
"useful",
"for",
"releases",
"this",
"way",
"cython",
"is",
"not",
"required",
"to",
"run",
"python",
"setup",
".",
"py",
"install",
"... | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/setup.py#L20-L36 | train |
sebp/scikit-survival | sksurv/svm/survival_svm.py | SurvivalCounter._count_values | def _count_values(self):
"""Return dict mapping relevance level to sample index"""
indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]}
return indices | python | def _count_values(self):
"""Return dict mapping relevance level to sample index"""
indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]}
return indices | [
"def",
"_count_values",
"(",
"self",
")",
":",
"indices",
"=",
"{",
"yi",
":",
"[",
"i",
"]",
"for",
"i",
",",
"yi",
"in",
"enumerate",
"(",
"self",
".",
"y",
")",
"if",
"self",
".",
"status",
"[",
"i",
"]",
"}",
"return",
"indices"
] | Return dict mapping relevance level to sample index | [
"Return",
"dict",
"mapping",
"relevance",
"level",
"to",
"sample",
"index"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L134-L138 | train |
sebp/scikit-survival | sksurv/svm/survival_svm.py | BaseSurvivalSVM._create_optimizer | def _create_optimizer(self, X, y, status):
"""Samples are ordered by relevance"""
if self.optimizer is None:
self.optimizer = 'avltree'
times, ranks = y
if self.optimizer == 'simple':
optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=sel... | python | def _create_optimizer(self, X, y, status):
"""Samples are ordered by relevance"""
if self.optimizer is None:
self.optimizer = 'avltree'
times, ranks = y
if self.optimizer == 'simple':
optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=sel... | [
"def",
"_create_optimizer",
"(",
"self",
",",
"X",
",",
"y",
",",
"status",
")",
":",
"if",
"self",
".",
"optimizer",
"is",
"None",
":",
"self",
".",
"optimizer",
"=",
"'avltree'",
"times",
",",
"ranks",
"=",
"y",
"if",
"self",
".",
"optimizer",
"=="... | Samples are ordered by relevance | [
"Samples",
"are",
"ordered",
"by",
"relevance"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L608-L633 | train |
sebp/scikit-survival | sksurv/svm/survival_svm.py | BaseSurvivalSVM._argsort_and_resolve_ties | def _argsort_and_resolve_ties(time, random_state):
"""Like numpy.argsort, but resolves ties uniformly at random"""
n_samples = len(time)
order = numpy.argsort(time, kind="mergesort")
i = 0
while i < n_samples - 1:
inext = i + 1
while inext < n_samples and... | python | def _argsort_and_resolve_ties(time, random_state):
"""Like numpy.argsort, but resolves ties uniformly at random"""
n_samples = len(time)
order = numpy.argsort(time, kind="mergesort")
i = 0
while i < n_samples - 1:
inext = i + 1
while inext < n_samples and... | [
"def",
"_argsort_and_resolve_ties",
"(",
"time",
",",
"random_state",
")",
":",
"n_samples",
"=",
"len",
"(",
"time",
")",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"=",
"\"mergesort\"",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"n_... | Like numpy.argsort, but resolves ties uniformly at random | [
"Like",
"numpy",
".",
"argsort",
"but",
"resolves",
"ties",
"uniformly",
"at",
"random"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L702-L717 | train |
sebp/scikit-survival | sksurv/linear_model/aft.py | IPCRidge.fit | def fit(self, X, y):
"""Build an accelerated failure time model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
... | python | def fit(self, X, y):
"""Build an accelerated failure time model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"event",
",",
"time",
"=",
"check_arrays_survival",
"(",
"X",
",",
"y",
")",
"weights",
"=",
"ipc_weights",
"(",
"event",
",",
"time",
")",
"super",
"(",
")",
".",
"fit",
"(",
"... | Build an accelerated failure time model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time o... | [
"Build",
"an",
"accelerated",
"failure",
"time",
"model",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/aft.py#L52-L74 | train |
sebp/scikit-survival | sksurv/linear_model/coxph.py | BreslowEstimator.fit | def fit(self, linear_predictor, event, time):
"""Compute baseline cumulative hazard function.
Parameters
----------
linear_predictor : array-like, shape = (n_samples,)
Linear predictor of risk: `X @ coef`.
event : array-like, shape = (n_samples,)
Contain... | python | def fit(self, linear_predictor, event, time):
"""Compute baseline cumulative hazard function.
Parameters
----------
linear_predictor : array-like, shape = (n_samples,)
Linear predictor of risk: `X @ coef`.
event : array-like, shape = (n_samples,)
Contain... | [
"def",
"fit",
"(",
"self",
",",
"linear_predictor",
",",
"event",
",",
"time",
")",
":",
"risk_score",
"=",
"numpy",
".",
"exp",
"(",
"linear_predictor",
")",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"=",
"\"mergesort\"",
")",
"... | Compute baseline cumulative hazard function.
Parameters
----------
linear_predictor : array-like, shape = (n_samples,)
Linear predictor of risk: `X @ coef`.
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, sh... | [
"Compute",
"baseline",
"cumulative",
"hazard",
"function",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L42-L81 | train |
sebp/scikit-survival | sksurv/linear_model/coxph.py | CoxPHOptimizer.nlog_likelihood | def nlog_likelihood(self, w):
"""Compute negative partial log-likelihood
Parameters
----------
w : array, shape = (n_features,)
Estimate of coefficients
Returns
-------
loss : float
Average negative partial log-likelihood
"""
... | python | def nlog_likelihood(self, w):
"""Compute negative partial log-likelihood
Parameters
----------
w : array, shape = (n_features,)
Estimate of coefficients
Returns
-------
loss : float
Average negative partial log-likelihood
"""
... | [
"def",
"nlog_likelihood",
"(",
"self",
",",
"w",
")",
":",
"time",
"=",
"self",
".",
"time",
"n_samples",
"=",
"self",
".",
"x",
".",
"shape",
"[",
"0",
"]",
"xw",
"=",
"numpy",
".",
"dot",
"(",
"self",
".",
"x",
",",
"w",
")",
"loss",
"=",
"... | Compute negative partial log-likelihood
Parameters
----------
w : array, shape = (n_features,)
Estimate of coefficients
Returns
-------
loss : float
Average negative partial log-likelihood | [
"Compute",
"negative",
"partial",
"log",
"-",
"likelihood"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L138-L168 | train |
sebp/scikit-survival | sksurv/linear_model/coxph.py | CoxPHOptimizer.update | def update(self, w, offset=0):
"""Compute gradient and Hessian matrix with respect to `w`."""
time = self.time
x = self.x
exp_xw = numpy.exp(offset + numpy.dot(x, w))
n_samples, n_features = x.shape
gradient = numpy.zeros((1, n_features), dtype=float)
hessian = n... | python | def update(self, w, offset=0):
"""Compute gradient and Hessian matrix with respect to `w`."""
time = self.time
x = self.x
exp_xw = numpy.exp(offset + numpy.dot(x, w))
n_samples, n_features = x.shape
gradient = numpy.zeros((1, n_features), dtype=float)
hessian = n... | [
"def",
"update",
"(",
"self",
",",
"w",
",",
"offset",
"=",
"0",
")",
":",
"time",
"=",
"self",
".",
"time",
"x",
"=",
"self",
".",
"x",
"exp_xw",
"=",
"numpy",
".",
"exp",
"(",
"offset",
"+",
"numpy",
".",
"dot",
"(",
"x",
",",
"w",
")",
"... | Compute gradient and Hessian matrix with respect to `w`. | [
"Compute",
"gradient",
"and",
"Hessian",
"matrix",
"with",
"respect",
"to",
"w",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L170-L218 | train |
sebp/scikit-survival | sksurv/linear_model/coxph.py | CoxPHSurvivalAnalysis.fit | def fit(self, X, y):
"""Minimize negative partial log-likelihood for provided data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary even... | python | def fit(self, X, y):
"""Minimize negative partial log-likelihood for provided data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary even... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"event",
",",
"time",
"=",
"check_arrays_survival",
"(",
"X",
",",
"y",
")",
"if",
"self",
".",
"alpha",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"alpha must be positive, but was %r... | Minimize negative partial log-likelihood for provided data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first... | [
"Minimize",
"negative",
"partial",
"log",
"-",
"likelihood",
"for",
"provided",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L292-L359 | train |
sebp/scikit-survival | sksurv/nonparametric.py | _compute_counts | def _compute_counts(event, time, order=None):
"""Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order ... | python | def _compute_counts(event, time, order=None):
"""Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order ... | [
"def",
"_compute_counts",
"(",
"event",
",",
"time",
",",
"order",
"=",
"None",
")",
":",
"n_samples",
"=",
"event",
".",
"shape",
"[",
"0",
"]",
"if",
"order",
"is",
"None",
":",
"order",
"=",
"numpy",
".",
"argsort",
"(",
"time",
",",
"kind",
"="... | Count right censored and uncensored samples at each unique time point.
Parameters
----------
event : array
Boolean event indicator.
time : array
Survival time or time of censoring.
order : array or None
Indices to order time in ascending order.
If None, order will ... | [
"Count",
"right",
"censored",
"and",
"uncensored",
"samples",
"at",
"each",
"unique",
"time",
"point",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L28-L94 | train |
sebp/scikit-survival | sksurv/nonparametric.py | _compute_counts_truncated | def _compute_counts_truncated(event, time_enter, time_exit):
"""Compute counts for left truncated and right censored survival data.
Parameters
----------
event : array
Boolean event indicator.
time_start : array
Time when a subject entered the study.
time_exit : array
... | python | def _compute_counts_truncated(event, time_enter, time_exit):
"""Compute counts for left truncated and right censored survival data.
Parameters
----------
event : array
Boolean event indicator.
time_start : array
Time when a subject entered the study.
time_exit : array
... | [
"def",
"_compute_counts_truncated",
"(",
"event",
",",
"time_enter",
",",
"time_exit",
")",
":",
"if",
"(",
"time_enter",
">",
"time_exit",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"exit time must be larger start time for all samples\"",
")",
... | Compute counts for left truncated and right censored survival data.
Parameters
----------
event : array
Boolean event indicator.
time_start : array
Time when a subject entered the study.
time_exit : array
Time when a subject left the study due to an
event or censor... | [
"Compute",
"counts",
"for",
"left",
"truncated",
"and",
"right",
"censored",
"survival",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L97-L167 | train |
sebp/scikit-survival | sksurv/nonparametric.py | kaplan_meier_estimator | def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None):
"""Kaplan-Meier estimator of survival function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time_exit : array-like, shape = (n_samples,)
Contains event... | python | def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None):
"""Kaplan-Meier estimator of survival function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time_exit : array-like, shape = (n_samples,)
Contains event... | [
"def",
"kaplan_meier_estimator",
"(",
"event",
",",
"time_exit",
",",
"time_enter",
"=",
"None",
",",
"time_min",
"=",
"None",
")",
":",
"event",
",",
"time_enter",
",",
"time_exit",
"=",
"check_y_survival",
"(",
"event",
",",
"time_enter",
",",
"time_exit",
... | Kaplan-Meier estimator of survival function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time_exit : array-like, shape = (n_samples,)
Contains event/censoring times.
time_enter : array-like, shape = (n_samples,), optional
... | [
"Kaplan",
"-",
"Meier",
"estimator",
"of",
"survival",
"function",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L170-L228 | train |
sebp/scikit-survival | sksurv/nonparametric.py | nelson_aalen_estimator | def nelson_aalen_estimator(event, time):
"""Nelson-Aalen estimator of cumulative hazard function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
... | python | def nelson_aalen_estimator(event, time):
"""Nelson-Aalen estimator of cumulative hazard function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
... | [
"def",
"nelson_aalen_estimator",
"(",
"event",
",",
"time",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"event",
",",
"time",
")",
"check_consistent_length",
"(",
"event",
",",
"time",
")",
"uniq_times",
",",
"n_events",
",",
"n_at_risk",
"... | Nelson-Aalen estimator of cumulative hazard function.
Parameters
----------
event : array-like, shape = (n_samples,)
Contains binary event indicators.
time : array-like, shape = (n_samples,)
Contains event/censoring times.
Returns
-------
time : array, shape = (n_times,)
... | [
"Nelson",
"-",
"Aalen",
"estimator",
"of",
"cumulative",
"hazard",
"function",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L231-L264 | train |
sebp/scikit-survival | sksurv/nonparametric.py | ipc_weights | def ipc_weights(event, time):
"""Compute inverse probability of censoring weights
Parameters
----------
event : array, shape = (n_samples,)
Boolean event indicator.
time : array, shape = (n_samples,)
Time when a subject experienced an event or was censored.
Returns
-------... | python | def ipc_weights(event, time):
"""Compute inverse probability of censoring weights
Parameters
----------
event : array, shape = (n_samples,)
Boolean event indicator.
time : array, shape = (n_samples,)
Time when a subject experienced an event or was censored.
Returns
-------... | [
"def",
"ipc_weights",
"(",
"event",
",",
"time",
")",
":",
"if",
"event",
".",
"all",
"(",
")",
":",
"return",
"numpy",
".",
"ones",
"(",
"time",
".",
"shape",
"[",
"0",
"]",
")",
"unique_time",
",",
"p",
"=",
"kaplan_meier_estimator",
"(",
"~",
"e... | Compute inverse probability of censoring weights
Parameters
----------
event : array, shape = (n_samples,)
Boolean event indicator.
time : array, shape = (n_samples,)
Time when a subject experienced an event or was censored.
Returns
-------
weights : array, shape = (n_samp... | [
"Compute",
"inverse",
"probability",
"of",
"censoring",
"weights"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L267-L296 | train |
sebp/scikit-survival | sksurv/nonparametric.py | SurvivalFunctionEstimator.fit | def fit(self, y):
"""Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
... | python | def fit(self, y):
"""Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
... | [
"def",
"fit",
"(",
"self",
",",
"y",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
",",
"allow_all_censored",
"=",
"True",
")",
"unique_time",
",",
"prob",
"=",
"kaplan_meier_estimator",
"(",
"event",
",",
"time",
")",
"self",
".",
... | Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Retur... | [
"Estimate",
"survival",
"distribution",
"from",
"training",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L305-L325 | train |
sebp/scikit-survival | sksurv/nonparametric.py | SurvivalFunctionEstimator.predict_proba | def predict_proba(self, time):
"""Return probability of an event after given time point.
:math:`\\hat{S}(t) = P(T > t)`
Parameters
----------
time : array, shape = (n_samples,)
Time to estimate probability at.
Returns
-------
prob : array, s... | python | def predict_proba(self, time):
"""Return probability of an event after given time point.
:math:`\\hat{S}(t) = P(T > t)`
Parameters
----------
time : array, shape = (n_samples,)
Time to estimate probability at.
Returns
-------
prob : array, s... | [
"def",
"predict_proba",
"(",
"self",
",",
"time",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"\"unique_time_\"",
")",
"time",
"=",
"check_array",
"(",
"time",
",",
"ensure_2d",
"=",
"False",
")",
"extends",
"=",
"time",
">",
"self",
".",
"unique_time_"... | Return probability of an event after given time point.
:math:`\\hat{S}(t) = P(T > t)`
Parameters
----------
time : array, shape = (n_samples,)
Time to estimate probability at.
Returns
-------
prob : array, shape = (n_samples,)
Probabilit... | [
"Return",
"probability",
"of",
"an",
"event",
"after",
"given",
"time",
"point",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L327-L364 | train |
sebp/scikit-survival | sksurv/nonparametric.py | CensoringDistributionEstimator.fit | def fit(self, y):
"""Estimate censoring distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
... | python | def fit(self, y):
"""Estimate censoring distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
... | [
"def",
"fit",
"(",
"self",
",",
"y",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
")",
"if",
"event",
".",
"all",
"(",
")",
":",
"self",
".",
"unique_time_",
"=",
"numpy",
".",
"unique",
"(",
"time",
")",
"self",
".",
"prob_... | Estimate censoring distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Retu... | [
"Estimate",
"censoring",
"distribution",
"from",
"training",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L370-L393 | train |
sebp/scikit-survival | sksurv/nonparametric.py | CensoringDistributionEstimator.predict_ipcw | def predict_ipcw(self, y):
"""Return inverse probability of censoring weights at given time points.
:math:`\\omega_i = \\delta_i / \\hat{G}(y_i)`
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicato... | python | def predict_ipcw(self, y):
"""Return inverse probability of censoring weights at given time points.
:math:`\\omega_i = \\delta_i / \\hat{G}(y_i)`
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicato... | [
"def",
"predict_ipcw",
"(",
"self",
",",
"y",
")",
":",
"event",
",",
"time",
"=",
"check_y_survival",
"(",
"y",
")",
"Ghat",
"=",
"self",
".",
"predict_proba",
"(",
"time",
"[",
"event",
"]",
")",
"if",
"(",
"Ghat",
"==",
"0.0",
")",
".",
"any",
... | Return inverse probability of censoring weights at given time points.
:math:`\\omega_i = \\delta_i / \\hat{G}(y_i)`
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time... | [
"Return",
"inverse",
"probability",
"of",
"censoring",
"weights",
"at",
"given",
"time",
"points",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L395-L421 | train |
sebp/scikit-survival | sksurv/metrics.py | concordance_index_censored | def concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8):
"""Concordance index for right-censored data
The concordance index is defined as the proportion of all comparable pairs
in which the predictions and outcomes are concordant.
Samples are comparable if for at least one... | python | def concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8):
"""Concordance index for right-censored data
The concordance index is defined as the proportion of all comparable pairs
in which the predictions and outcomes are concordant.
Samples are comparable if for at least one... | [
"def",
"concordance_index_censored",
"(",
"event_indicator",
",",
"event_time",
",",
"estimate",
",",
"tied_tol",
"=",
"1e-8",
")",
":",
"event_indicator",
",",
"event_time",
",",
"estimate",
"=",
"_check_inputs",
"(",
"event_indicator",
",",
"event_time",
",",
"e... | Concordance index for right-censored data
The concordance index is defined as the proportion of all comparable pairs
in which the predictions and outcomes are concordant.
Samples are comparable if for at least one of them an event occurred.
If the estimated risk is larger for the sample with a higher ... | [
"Concordance",
"index",
"for",
"right",
"-",
"censored",
"data"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/metrics.py#L111-L174 | train |
sebp/scikit-survival | sksurv/metrics.py | concordance_index_ipcw | def concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-8):
"""Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depend on the distributio... | python | def concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-8):
"""Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depend on the distributio... | [
"def",
"concordance_index_ipcw",
"(",
"survival_train",
",",
"survival_test",
",",
"estimate",
",",
"tau",
"=",
"None",
",",
"tied_tol",
"=",
"1e-8",
")",
":",
"test_event",
",",
"test_time",
"=",
"check_y_survival",
"(",
"survival_test",
")",
"if",
"tau",
"is... | Concordance index for right-censored data based on inverse probability of censoring weights.
This is an alternative to the estimator in :func:`concordance_index_censored`
that does not depend on the distribution of censoring times in the test data.
Therefore, the estimate is unbiased and consistent for a p... | [
"Concordance",
"index",
"for",
"right",
"-",
"censored",
"data",
"based",
"on",
"inverse",
"probability",
"of",
"censoring",
"weights",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/metrics.py#L177-L266 | train |
sebp/scikit-survival | sksurv/kernels/clinical.py | _nominal_kernel | def _nominal_kernel(x, y, out):
"""Number of features that match exactly"""
for i in range(x.shape[0]):
for j in range(y.shape[0]):
out[i, j] += (x[i, :] == y[j, :]).sum()
return out | python | def _nominal_kernel(x, y, out):
"""Number of features that match exactly"""
for i in range(x.shape[0]):
for j in range(y.shape[0]):
out[i, j] += (x[i, :] == y[j, :]).sum()
return out | [
"def",
"_nominal_kernel",
"(",
"x",
",",
"y",
",",
"out",
")",
":",
"for",
"i",
"in",
"range",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"y",
".",
"shape",
"[",
"0",
"]",
")",
":",
"out",
"[",
"i",
"... | Number of features that match exactly | [
"Number",
"of",
"features",
"that",
"match",
"exactly"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L26-L32 | train |
sebp/scikit-survival | sksurv/kernels/clinical.py | _get_continuous_and_ordinal_array | def _get_continuous_and_ordinal_array(x):
"""Convert array from continuous and ordered categorical columns"""
nominal_columns = x.select_dtypes(include=['object', 'category']).columns
ordinal_columns = pandas.Index([v for v in nominal_columns if x[v].cat.ordered])
continuous_columns = x.select_dtypes(in... | python | def _get_continuous_and_ordinal_array(x):
"""Convert array from continuous and ordered categorical columns"""
nominal_columns = x.select_dtypes(include=['object', 'category']).columns
ordinal_columns = pandas.Index([v for v in nominal_columns if x[v].cat.ordered])
continuous_columns = x.select_dtypes(in... | [
"def",
"_get_continuous_and_ordinal_array",
"(",
"x",
")",
":",
"nominal_columns",
"=",
"x",
".",
"select_dtypes",
"(",
"include",
"=",
"[",
"'object'",
",",
"'category'",
"]",
")",
".",
"columns",
"ordinal_columns",
"=",
"pandas",
".",
"Index",
"(",
"[",
"v... | Convert array from continuous and ordered categorical columns | [
"Convert",
"array",
"from",
"continuous",
"and",
"ordered",
"categorical",
"columns"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L35-L50 | train |
sebp/scikit-survival | sksurv/kernels/clinical.py | clinical_kernel | def clinical_kernel(x, y=None):
"""Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n... | python | def clinical_kernel(x, y=None):
"""Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n... | [
"def",
"clinical_kernel",
"(",
"x",
",",
"y",
"=",
"None",
")",
":",
"if",
"y",
"is",
"not",
"None",
":",
"if",
"x",
".",
"shape",
"[",
"1",
"]",
"!=",
"y",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'x and y have different numb... | Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n_features)
Testing data
Re... | [
"Computes",
"clinical",
"kernel"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L61-L107 | train |
sebp/scikit-survival | sksurv/kernels/clinical.py | ClinicalKernelTransform._prepare_by_column_dtype | def _prepare_by_column_dtype(self, X):
"""Get distance functions for each column's dtype"""
if not isinstance(X, pandas.DataFrame):
raise TypeError('X must be a pandas DataFrame')
numeric_columns = []
nominal_columns = []
numeric_ranges = []
fit_data = numpy... | python | def _prepare_by_column_dtype(self, X):
"""Get distance functions for each column's dtype"""
if not isinstance(X, pandas.DataFrame):
raise TypeError('X must be a pandas DataFrame')
numeric_columns = []
nominal_columns = []
numeric_ranges = []
fit_data = numpy... | [
"def",
"_prepare_by_column_dtype",
"(",
"self",
",",
"X",
")",
":",
"if",
"not",
"isinstance",
"(",
"X",
",",
"pandas",
".",
"DataFrame",
")",
":",
"raise",
"TypeError",
"(",
"'X must be a pandas DataFrame'",
")",
"numeric_columns",
"=",
"[",
"]",
"nominal_col... | Get distance functions for each column's dtype | [
"Get",
"distance",
"functions",
"for",
"each",
"column",
"s",
"dtype"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L153-L185 | train |
sebp/scikit-survival | sksurv/kernels/clinical.py | ClinicalKernelTransform.fit | def fit(self, X, y=None, **kwargs):
"""Determine transformation parameters from data in X.
Subsequent calls to `transform(Y)` compute the pairwise
distance to `X`.
Parameters of the clinical kernel are only updated
if `fit_once` is `False`, otherwise you have to
explicit... | python | def fit(self, X, y=None, **kwargs):
"""Determine transformation parameters from data in X.
Subsequent calls to `transform(Y)` compute the pairwise
distance to `X`.
Parameters of the clinical kernel are only updated
if `fit_once` is `False`, otherwise you have to
explicit... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"X",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"expected 2d array, but got %d\"",
"%",
"X",
".",
"ndim",
")",
"if",
"self",
".",
"fit_... | Determine transformation parameters from data in X.
Subsequent calls to `transform(Y)` compute the pairwise
distance to `X`.
Parameters of the clinical kernel are only updated
if `fit_once` is `False`, otherwise you have to
explicitly call `prepare()` once.
Parameters
... | [
"Determine",
"transformation",
"parameters",
"from",
"data",
"in",
"X",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L187-L220 | train |
sebp/scikit-survival | sksurv/kernels/clinical.py | ClinicalKernelTransform.transform | def transform(self, Y):
r"""Compute all pairwise distances between `self.X_fit_` and `Y`.
Parameters
----------
y : array-like, shape = (n_samples_y, n_features)
Returns
-------
kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_)
Kernel matrix... | python | def transform(self, Y):
r"""Compute all pairwise distances between `self.X_fit_` and `Y`.
Parameters
----------
y : array-like, shape = (n_samples_y, n_features)
Returns
-------
kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_)
Kernel matrix... | [
"def",
"transform",
"(",
"self",
",",
"Y",
")",
":",
"r",
"check_is_fitted",
"(",
"self",
",",
"'X_fit_'",
")",
"n_samples_x",
",",
"n_features",
"=",
"self",
".",
"X_fit_",
".",
"shape",
"Y",
"=",
"numpy",
".",
"asarray",
"(",
"Y",
")",
"if",
"Y",
... | r"""Compute all pairwise distances between `self.X_fit_` and `Y`.
Parameters
----------
y : array-like, shape = (n_samples_y, n_features)
Returns
-------
kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_)
Kernel matrix. Values are normalized to lie w... | [
"r",
"Compute",
"all",
"pairwise",
"distances",
"between",
"self",
".",
"X_fit_",
"and",
"Y",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L222-L257 | train |
sebp/scikit-survival | sksurv/ensemble/boosting.py | _fit_stage_componentwise | def _fit_stage_componentwise(X, residuals, sample_weight, **fit_params):
"""Fit component-wise weighted least squares model"""
n_features = X.shape[1]
base_learners = []
error = numpy.empty(n_features)
for component in range(n_features):
learner = ComponentwiseLeastSquares(component).fit(X,... | python | def _fit_stage_componentwise(X, residuals, sample_weight, **fit_params):
"""Fit component-wise weighted least squares model"""
n_features = X.shape[1]
base_learners = []
error = numpy.empty(n_features)
for component in range(n_features):
learner = ComponentwiseLeastSquares(component).fit(X,... | [
"def",
"_fit_stage_componentwise",
"(",
"X",
",",
"residuals",
",",
"sample_weight",
",",
"**",
"fit_params",
")",
":",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"base_learners",
"=",
"[",
"]",
"error",
"=",
"numpy",
".",
"empty",
"(",
"n_feat... | Fit component-wise weighted least squares model | [
"Fit",
"component",
"-",
"wise",
"weighted",
"least",
"squares",
"model"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L72-L87 | train |
sebp/scikit-survival | sksurv/ensemble/boosting.py | ComponentwiseGradientBoostingSurvivalAnalysis.coef_ | def coef_(self):
"""Return the aggregated coefficients.
Returns
-------
coef_ : ndarray, shape = (n_features + 1,)
Coefficients of features. The first element denotes the intercept.
"""
coef = numpy.zeros(self.n_features_ + 1, dtype=float)
for estima... | python | def coef_(self):
"""Return the aggregated coefficients.
Returns
-------
coef_ : ndarray, shape = (n_features + 1,)
Coefficients of features. The first element denotes the intercept.
"""
coef = numpy.zeros(self.n_features_ + 1, dtype=float)
for estima... | [
"def",
"coef_",
"(",
"self",
")",
":",
"coef",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"n_features_",
"+",
"1",
",",
"dtype",
"=",
"float",
")",
"for",
"estimator",
"in",
"self",
".",
"estimators_",
":",
"coef",
"[",
"estimator",
".",
"componen... | Return the aggregated coefficients.
Returns
-------
coef_ : ndarray, shape = (n_features + 1,)
Coefficients of features. The first element denotes the intercept. | [
"Return",
"the",
"aggregated",
"coefficients",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L338-L351 | train |
sebp/scikit-survival | sksurv/ensemble/boosting.py | GradientBoostingSurvivalAnalysis._fit_stage | def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask,
random_state, scale, X_idx_sorted, X_csc=None, X_csr=None):
"""Fit another stage of ``n_classes_`` trees to the boosting model. """
assert sample_mask.dtype == numpy.bool
loss = self.loss_
# whether to... | python | def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask,
random_state, scale, X_idx_sorted, X_csc=None, X_csr=None):
"""Fit another stage of ``n_classes_`` trees to the boosting model. """
assert sample_mask.dtype == numpy.bool
loss = self.loss_
# whether to... | [
"def",
"_fit_stage",
"(",
"self",
",",
"i",
",",
"X",
",",
"y",
",",
"y_pred",
",",
"sample_weight",
",",
"sample_mask",
",",
"random_state",
",",
"scale",
",",
"X_idx_sorted",
",",
"X_csc",
"=",
"None",
",",
"X_csr",
"=",
"None",
")",
":",
"assert",
... | Fit another stage of ``n_classes_`` trees to the boosting model. | [
"Fit",
"another",
"stage",
"of",
"n_classes_",
"trees",
"to",
"the",
"boosting",
"model",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L609-L671 | train |
sebp/scikit-survival | sksurv/ensemble/boosting.py | GradientBoostingSurvivalAnalysis._fit_stages | def _fit_stages(self, X, y, y_pred, sample_weight, random_state,
begin_at_stage=0, monitor=None, X_idx_sorted=None):
"""Iteratively fits the stages.
For each stage it computes the progress (OOB, train score)
and delegates to ``_fit_stage``.
Returns the number of stag... | python | def _fit_stages(self, X, y, y_pred, sample_weight, random_state,
begin_at_stage=0, monitor=None, X_idx_sorted=None):
"""Iteratively fits the stages.
For each stage it computes the progress (OOB, train score)
and delegates to ``_fit_stage``.
Returns the number of stag... | [
"def",
"_fit_stages",
"(",
"self",
",",
"X",
",",
"y",
",",
"y_pred",
",",
"sample_weight",
",",
"random_state",
",",
"begin_at_stage",
"=",
"0",
",",
"monitor",
"=",
"None",
",",
"X_idx_sorted",
"=",
"None",
")",
":",
"n_samples",
"=",
"X",
".",
"shap... | Iteratively fits the stages.
For each stage it computes the progress (OOB, train score)
and delegates to ``_fit_stage``.
Returns the number of stages fit; might differ from ``n_estimators``
due to early stopping. | [
"Iteratively",
"fits",
"the",
"stages",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L673-L741 | train |
sebp/scikit-survival | sksurv/ensemble/boosting.py | GradientBoostingSurvivalAnalysis.fit | def fit(self, X, y, sample_weight=None, monitor=None):
"""Fit the gradient boosting model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the bina... | python | def fit(self, X, y, sample_weight=None, monitor=None):
"""Fit the gradient boosting model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the bina... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
",",
"monitor",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_state",
")",
"X",
",",
"event",
",",
"time",
"=",
"check_array... | Fit the gradient boosting model.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event o... | [
"Fit",
"the",
"gradient",
"boosting",
"model",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L743-L823 | train |
sebp/scikit-survival | sksurv/ensemble/boosting.py | GradientBoostingSurvivalAnalysis.staged_predict | def staged_predict(self, X):
"""Predict hazard at each stage for X.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Return... | python | def staged_predict(self, X):
"""Predict hazard at each stage for X.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Return... | [
"def",
"staged_predict",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'estimators_'",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"scale_\"",
")",
":",
"for",
"y",
"in",
"self",
".",
"_staged_decision_function",
"(",
"X",
"... | Predict hazard at each stage for X.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
y : generator ... | [
"Predict",
"hazard",
"at",
"each",
"stage",
"for",
"X",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L886-L911 | train |
sebp/scikit-survival | sksurv/svm/minlip.py | MinlipSurvivalAnalysis.fit | def fit(self, X, y):
"""Build a MINLIP survival model from training data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicat... | python | def fit(self, X, y):
"""Build a MINLIP survival model from training data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicat... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"event",
",",
"time",
"=",
"check_arrays_survival",
"(",
"X",
",",
"y",
")",
"self",
".",
"_fit",
"(",
"X",
",",
"event",
",",
"time",
")",
"return",
"self"
] | Build a MINLIP survival model from training data.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix.
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, a... | [
"Build",
"a",
"MINLIP",
"survival",
"model",
"from",
"training",
"data",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/minlip.py#L227-L247 | train |
sebp/scikit-survival | sksurv/svm/minlip.py | MinlipSurvivalAnalysis.predict | def predict(self, X):
"""Predict risk score of experiencing an event.
Higher scores indicate shorter survival (high risk),
lower scores longer survival (low risk).
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
... | python | def predict(self, X):
"""Predict risk score of experiencing an event.
Higher scores indicate shorter survival (high risk),
lower scores longer survival (low risk).
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
... | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"K",
"=",
"self",
".",
"_get_kernel",
"(",
"X",
",",
"self",
".",
"X_fit_",
")",
"pred",
"=",
"-",
"numpy",
".",
"dot",
"(",
"self",
".",
"coef_",
",",
"K",
".",
"T",
")",
"return",
"pred",
"... | Predict risk score of experiencing an event.
Higher scores indicate shorter survival (high risk),
lower scores longer survival (low risk).
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The input samples.
Returns
-------
... | [
"Predict",
"risk",
"score",
"of",
"experiencing",
"an",
"event",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/minlip.py#L249-L267 | train |
sebp/scikit-survival | sksurv/datasets/base.py | get_x_y | def get_x_y(data_frame, attr_labels, pos_label=None, survival=True):
"""Split data frame into features and labels.
Parameters
----------
data_frame : pandas.DataFrame, shape = (n_samples, n_columns)
A data frame.
attr_labels : sequence of str or None
A list of one or more columns t... | python | def get_x_y(data_frame, attr_labels, pos_label=None, survival=True):
"""Split data frame into features and labels.
Parameters
----------
data_frame : pandas.DataFrame, shape = (n_samples, n_columns)
A data frame.
attr_labels : sequence of str or None
A list of one or more columns t... | [
"def",
"get_x_y",
"(",
"data_frame",
",",
"attr_labels",
",",
"pos_label",
"=",
"None",
",",
"survival",
"=",
"True",
")",
":",
"if",
"survival",
":",
"if",
"len",
"(",
"attr_labels",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"expected sequence of... | Split data frame into features and labels.
Parameters
----------
data_frame : pandas.DataFrame, shape = (n_samples, n_columns)
A data frame.
attr_labels : sequence of str or None
A list of one or more columns that are considered the label.
If `survival` is `True`, then attr_lab... | [
"Split",
"data",
"frame",
"into",
"features",
"and",
"labels",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/datasets/base.py#L46-L88 | train |
sebp/scikit-survival | sksurv/datasets/base.py | load_arff_files_standardized | def load_arff_files_standardized(path_training, attr_labels, pos_label=None, path_testing=None, survival=True,
standardize_numeric=True, to_numeric=True):
"""Load dataset in ARFF format.
Parameters
----------
path_training : str
Path to ARFF file containing data... | python | def load_arff_files_standardized(path_training, attr_labels, pos_label=None, path_testing=None, survival=True,
standardize_numeric=True, to_numeric=True):
"""Load dataset in ARFF format.
Parameters
----------
path_training : str
Path to ARFF file containing data... | [
"def",
"load_arff_files_standardized",
"(",
"path_training",
",",
"attr_labels",
",",
"pos_label",
"=",
"None",
",",
"path_testing",
"=",
"None",
",",
"survival",
"=",
"True",
",",
"standardize_numeric",
"=",
"True",
",",
"to_numeric",
"=",
"True",
")",
":",
"... | Load dataset in ARFF format.
Parameters
----------
path_training : str
Path to ARFF file containing data.
attr_labels : sequence of str
Names of attributes denoting dependent variables.
If ``survival`` is set, it must be a sequence with two items:
the name of the event ... | [
"Load",
"dataset",
"in",
"ARFF",
"format",
"."
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/datasets/base.py#L91-L179 | train |
sebp/scikit-survival | sksurv/datasets/base.py | load_aids | def load_aids(endpoint="aids"):
"""Load and return the AIDS Clinical Trial dataset
The dataset has 1,151 samples and 11 features.
The dataset has 2 endpoints:
1. AIDS defining event, which occurred for 96 patients (8.3%)
2. Death, which occurred for 26 patients (2.3%)
Parameters
---------... | python | def load_aids(endpoint="aids"):
"""Load and return the AIDS Clinical Trial dataset
The dataset has 1,151 samples and 11 features.
The dataset has 2 endpoints:
1. AIDS defining event, which occurred for 96 patients (8.3%)
2. Death, which occurred for 26 patients (2.3%)
Parameters
---------... | [
"def",
"load_aids",
"(",
"endpoint",
"=",
"\"aids\"",
")",
":",
"labels_aids",
"=",
"[",
"'censor'",
",",
"'time'",
"]",
"labels_death",
"=",
"[",
"'censor_d'",
",",
"'time_d'",
"]",
"if",
"endpoint",
"==",
"\"aids\"",
":",
"attr_labels",
"=",
"labels_aids",... | Load and return the AIDS Clinical Trial dataset
The dataset has 1,151 samples and 11 features.
The dataset has 2 endpoints:
1. AIDS defining event, which occurred for 96 patients (8.3%)
2. Death, which occurred for 26 patients (2.3%)
Parameters
----------
endpoint : aids|death
The... | [
"Load",
"and",
"return",
"the",
"AIDS",
"Clinical",
"Trial",
"dataset"
] | cfc99fd20454cdd6f4f20fe331b39f2191ccaabc | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/datasets/base.py#L284-L333 | train |
seemethere/nba_py | nba_py/__init__.py | _api_scrape | def _api_scrape(json_inp, ndx):
"""
Internal method to streamline the getting of data from the json
Args:
json_inp (json): json input from our caller
ndx (int): index where the data is located in the api
Returns:
If pandas is present:
DataFrame (pandas.DataFrame): d... | python | def _api_scrape(json_inp, ndx):
"""
Internal method to streamline the getting of data from the json
Args:
json_inp (json): json input from our caller
ndx (int): index where the data is located in the api
Returns:
If pandas is present:
DataFrame (pandas.DataFrame): d... | [
"def",
"_api_scrape",
"(",
"json_inp",
",",
"ndx",
")",
":",
"try",
":",
"headers",
"=",
"json_inp",
"[",
"'resultSets'",
"]",
"[",
"ndx",
"]",
"[",
"'headers'",
"]",
"values",
"=",
"json_inp",
"[",
"'resultSets'",
"]",
"[",
"ndx",
"]",
"[",
"'rowSet'"... | Internal method to streamline the getting of data from the json
Args:
json_inp (json): json input from our caller
ndx (int): index where the data is located in the api
Returns:
If pandas is present:
DataFrame (pandas.DataFrame): data set from ndx within the
API'... | [
"Internal",
"method",
"to",
"streamline",
"the",
"getting",
"of",
"data",
"from",
"the",
"json"
] | ffeaf4251d796ff9313367a752a45a0d7b16489e | https://github.com/seemethere/nba_py/blob/ffeaf4251d796ff9313367a752a45a0d7b16489e/nba_py/__init__.py#L34-L67 | train |
seemethere/nba_py | nba_py/player.py | get_player | def get_player(first_name,
last_name=None,
season=constants.CURRENT_SEASON,
only_current=0,
just_id=True):
"""
Calls our PlayerList class to get a full list of players and then returns
just an id if specified or the full row of player information
... | python | def get_player(first_name,
last_name=None,
season=constants.CURRENT_SEASON,
only_current=0,
just_id=True):
"""
Calls our PlayerList class to get a full list of players and then returns
just an id if specified or the full row of player information
... | [
"def",
"get_player",
"(",
"first_name",
",",
"last_name",
"=",
"None",
",",
"season",
"=",
"constants",
".",
"CURRENT_SEASON",
",",
"only_current",
"=",
"0",
",",
"just_id",
"=",
"True",
")",
":",
"if",
"last_name",
"is",
"None",
":",
"name",
"=",
"first... | Calls our PlayerList class to get a full list of players and then returns
just an id if specified or the full row of player information
Args:
:first_name: First name of the player
:last_name: Last name of the player
(this is None if the player only has first name [Nene])
:only_c... | [
"Calls",
"our",
"PlayerList",
"class",
"to",
"get",
"a",
"full",
"list",
"of",
"players",
"and",
"then",
"returns",
"just",
"an",
"id",
"if",
"specified",
"or",
"the",
"full",
"row",
"of",
"player",
"information"
] | ffeaf4251d796ff9313367a752a45a0d7b16489e | https://github.com/seemethere/nba_py/blob/ffeaf4251d796ff9313367a752a45a0d7b16489e/nba_py/player.py#L9-L46 | train |
ishikota/PyPokerEngine | pypokerengine/players.py | BasePokerPlayer.respond_to_ask | def respond_to_ask(self, message):
"""Called from Dealer when ask message received from RoundManager"""
valid_actions, hole_card, round_state = self.__parse_ask_message(message)
return self.declare_action(valid_actions, hole_card, round_state) | python | def respond_to_ask(self, message):
"""Called from Dealer when ask message received from RoundManager"""
valid_actions, hole_card, round_state = self.__parse_ask_message(message)
return self.declare_action(valid_actions, hole_card, round_state) | [
"def",
"respond_to_ask",
"(",
"self",
",",
"message",
")",
":",
"valid_actions",
",",
"hole_card",
",",
"round_state",
"=",
"self",
".",
"__parse_ask_message",
"(",
"message",
")",
"return",
"self",
".",
"declare_action",
"(",
"valid_actions",
",",
"hole_card",
... | Called from Dealer when ask message received from RoundManager | [
"Called",
"from",
"Dealer",
"when",
"ask",
"message",
"received",
"from",
"RoundManager"
] | a52a048a15da276005eca4acae96fb6eeb4dc034 | https://github.com/ishikota/PyPokerEngine/blob/a52a048a15da276005eca4acae96fb6eeb4dc034/pypokerengine/players.py#L45-L48 | train |
ishikota/PyPokerEngine | pypokerengine/players.py | BasePokerPlayer.receive_notification | def receive_notification(self, message):
"""Called from Dealer when notification received from RoundManager"""
msg_type = message["message_type"]
if msg_type == "game_start_message":
info = self.__parse_game_start_message(message)
self.receive_game_start_message(info)
elif msg_type == "rou... | python | def receive_notification(self, message):
"""Called from Dealer when notification received from RoundManager"""
msg_type = message["message_type"]
if msg_type == "game_start_message":
info = self.__parse_game_start_message(message)
self.receive_game_start_message(info)
elif msg_type == "rou... | [
"def",
"receive_notification",
"(",
"self",
",",
"message",
")",
":",
"msg_type",
"=",
"message",
"[",
"\"message_type\"",
"]",
"if",
"msg_type",
"==",
"\"game_start_message\"",
":",
"info",
"=",
"self",
".",
"__parse_game_start_message",
"(",
"message",
")",
"s... | Called from Dealer when notification received from RoundManager | [
"Called",
"from",
"Dealer",
"when",
"notification",
"received",
"from",
"RoundManager"
] | a52a048a15da276005eca4acae96fb6eeb4dc034 | https://github.com/ishikota/PyPokerEngine/blob/a52a048a15da276005eca4acae96fb6eeb4dc034/pypokerengine/players.py#L50-L72 | train |
alex-sherman/unsync | examples/mixing_methods.py | result_continuation | async def result_continuation(task):
"""A preliminary result processor we'll chain on to the original task
This will get executed wherever the source task was executed, in this
case one of the threads in the ThreadPoolExecutor"""
await asyncio.sleep(0.1)
num, res = task.result()
return num... | python | async def result_continuation(task):
"""A preliminary result processor we'll chain on to the original task
This will get executed wherever the source task was executed, in this
case one of the threads in the ThreadPoolExecutor"""
await asyncio.sleep(0.1)
num, res = task.result()
return num... | [
"async",
"def",
"result_continuation",
"(",
"task",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"0.1",
")",
"num",
",",
"res",
"=",
"task",
".",
"result",
"(",
")",
"return",
"num",
",",
"res",
"*",
"2"
] | A preliminary result processor we'll chain on to the original task
This will get executed wherever the source task was executed, in this
case one of the threads in the ThreadPoolExecutor | [
"A",
"preliminary",
"result",
"processor",
"we",
"ll",
"chain",
"on",
"to",
"the",
"original",
"task",
"This",
"will",
"get",
"executed",
"wherever",
"the",
"source",
"task",
"was",
"executed",
"in",
"this",
"case",
"one",
"of",
"the",
"threads",
"in",
"th... | a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe | https://github.com/alex-sherman/unsync/blob/a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe/examples/mixing_methods.py#L16-L22 | train |
alex-sherman/unsync | examples/mixing_methods.py | result_processor | async def result_processor(tasks):
"""An async result aggregator that combines all the results
This gets executed in unsync.loop and unsync.thread"""
output = {}
for task in tasks:
num, res = await task
output[num] = res
return output | python | async def result_processor(tasks):
"""An async result aggregator that combines all the results
This gets executed in unsync.loop and unsync.thread"""
output = {}
for task in tasks:
num, res = await task
output[num] = res
return output | [
"async",
"def",
"result_processor",
"(",
"tasks",
")",
":",
"output",
"=",
"{",
"}",
"for",
"task",
"in",
"tasks",
":",
"num",
",",
"res",
"=",
"await",
"task",
"output",
"[",
"num",
"]",
"=",
"res",
"return",
"output"
] | An async result aggregator that combines all the results
This gets executed in unsync.loop and unsync.thread | [
"An",
"async",
"result",
"aggregator",
"that",
"combines",
"all",
"the",
"results",
"This",
"gets",
"executed",
"in",
"unsync",
".",
"loop",
"and",
"unsync",
".",
"thread"
] | a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe | https://github.com/alex-sherman/unsync/blob/a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe/examples/mixing_methods.py#L25-L32 | train |
fastavro/fastavro | fastavro/_read_py.py | read_union | def read_union(fo, writer_schema, reader_schema=None):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
"""
# schema resolution
index = read_lo... | python | def read_union(fo, writer_schema, reader_schema=None):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
"""
# schema resolution
index = read_lo... | [
"def",
"read_union",
"(",
"fo",
",",
"writer_schema",
",",
"reader_schema",
"=",
"None",
")",
":",
"index",
"=",
"read_long",
"(",
"fo",
")",
"if",
"reader_schema",
":",
"if",
"not",
"isinstance",
"(",
"reader_schema",
",",
"list",
")",
":",
"if",
"match... | A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union. | [
"A",
"union",
"is",
"encoded",
"by",
"first",
"writing",
"a",
"long",
"value",
"indicating",
"the",
"zero",
"-",
"based",
"position",
"within",
"the",
"union",
"of",
"the",
"schema",
"of",
"its",
"value",
"."
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L345-L366 | train |
fastavro/fastavro | fastavro/_read_py.py | read_data | def read_data(fo, writer_schema, reader_schema=None):
"""Read data from file object according to schema."""
record_type = extract_record_type(writer_schema)
logical_type = extract_logical_type(writer_schema)
if reader_schema and record_type in AVRO_TYPES:
# If the schemas are the same, set the... | python | def read_data(fo, writer_schema, reader_schema=None):
"""Read data from file object according to schema."""
record_type = extract_record_type(writer_schema)
logical_type = extract_logical_type(writer_schema)
if reader_schema and record_type in AVRO_TYPES:
# If the schemas are the same, set the... | [
"def",
"read_data",
"(",
"fo",
",",
"writer_schema",
",",
"reader_schema",
"=",
"None",
")",
":",
"record_type",
"=",
"extract_record_type",
"(",
"writer_schema",
")",
"logical_type",
"=",
"extract_logical_type",
"(",
"writer_schema",
")",
"if",
"reader_schema",
"... | Read data from file object according to schema. | [
"Read",
"data",
"from",
"file",
"object",
"according",
"to",
"schema",
"."
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L477-L516 | train |
fastavro/fastavro | fastavro/_read_py.py | _iter_avro_records | def _iter_avro_records(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro records."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
block_count = 0
while True:
... | python | def _iter_avro_records(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro records."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
block_count = 0
while True:
... | [
"def",
"_iter_avro_records",
"(",
"fo",
",",
"header",
",",
"codec",
",",
"writer_schema",
",",
"reader_schema",
")",
":",
"sync_marker",
"=",
"header",
"[",
"'sync'",
"]",
"read_block",
"=",
"BLOCK_READERS",
".",
"get",
"(",
"codec",
")",
"if",
"not",
"re... | Return iterator over avro records. | [
"Return",
"iterator",
"over",
"avro",
"records",
"."
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L559-L579 | train |
fastavro/fastavro | fastavro/_read_py.py | _iter_avro_blocks | def _iter_avro_blocks(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro blocks."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
while True:
offset = fo.tell()
... | python | def _iter_avro_blocks(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro blocks."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
while True:
offset = fo.tell()
... | [
"def",
"_iter_avro_blocks",
"(",
"fo",
",",
"header",
",",
"codec",
",",
"writer_schema",
",",
"reader_schema",
")",
":",
"sync_marker",
"=",
"header",
"[",
"'sync'",
"]",
"read_block",
"=",
"BLOCK_READERS",
".",
"get",
"(",
"codec",
")",
"if",
"not",
"rea... | Return iterator over avro blocks. | [
"Return",
"iterator",
"over",
"avro",
"blocks",
"."
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L582-L606 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_timestamp_millis | def prepare_timestamp_millis(data, schema):
"""Converts datetime.datetime object to int timestamp with milliseconds
"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MLS_PER_SECOND)
t = in... | python | def prepare_timestamp_millis(data, schema):
"""Converts datetime.datetime object to int timestamp with milliseconds
"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MLS_PER_SECOND)
t = in... | [
"def",
"prepare_timestamp_millis",
"(",
"data",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"data",
".",
"tzinfo",
"is",
"not",
"None",
":",
"delta",
"=",
"(",
"data",
"-",
"epoch",
")",
... | Converts datetime.datetime object to int timestamp with milliseconds | [
"Converts",
"datetime",
".",
"datetime",
"object",
"to",
"int",
"timestamp",
"with",
"milliseconds"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L43-L54 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_timestamp_micros | def prepare_timestamp_micros(data, schema):
"""Converts datetime.datetime to int timestamp with microseconds"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MCS_PER_SECOND)
t = int(time.mktim... | python | def prepare_timestamp_micros(data, schema):
"""Converts datetime.datetime to int timestamp with microseconds"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MCS_PER_SECOND)
t = int(time.mktim... | [
"def",
"prepare_timestamp_micros",
"(",
"data",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"data",
".",
"tzinfo",
"is",
"not",
"None",
":",
"delta",
"=",
"(",
"data",
"-",
"epoch",
")",
... | Converts datetime.datetime to int timestamp with microseconds | [
"Converts",
"datetime",
".",
"datetime",
"to",
"int",
"timestamp",
"with",
"microseconds"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L57-L67 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_date | def prepare_date(data, schema):
"""Converts datetime.date to int timestamp"""
if isinstance(data, datetime.date):
return data.toordinal() - DAYS_SHIFT
else:
return data | python | def prepare_date(data, schema):
"""Converts datetime.date to int timestamp"""
if isinstance(data, datetime.date):
return data.toordinal() - DAYS_SHIFT
else:
return data | [
"def",
"prepare_date",
"(",
"data",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"datetime",
".",
"date",
")",
":",
"return",
"data",
".",
"toordinal",
"(",
")",
"-",
"DAYS_SHIFT",
"else",
":",
"return",
"data"
] | Converts datetime.date to int timestamp | [
"Converts",
"datetime",
".",
"date",
"to",
"int",
"timestamp"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L70-L75 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_uuid | def prepare_uuid(data, schema):
"""Converts uuid.UUID to
string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
"""
if isinstance(data, uuid.UUID):
return str(data)
else:
return data | python | def prepare_uuid(data, schema):
"""Converts uuid.UUID to
string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
"""
if isinstance(data, uuid.UUID):
return str(data)
else:
return data | [
"def",
"prepare_uuid",
"(",
"data",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"uuid",
".",
"UUID",
")",
":",
"return",
"str",
"(",
"data",
")",
"else",
":",
"return",
"data"
] | Converts uuid.UUID to
string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx | [
"Converts",
"uuid",
".",
"UUID",
"to",
"string",
"formatted",
"UUID",
"xxxxxxxx",
"-",
"xxxx",
"-",
"xxxx",
"-",
"xxxx",
"-",
"xxxxxxxxxxxx"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L78-L85 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_time_millis | def prepare_time_millis(data, schema):
"""Convert datetime.time to int timestamp with milliseconds"""
if isinstance(data, datetime.time):
return int(
data.hour * MLS_PER_HOUR + data.minute * MLS_PER_MINUTE
+ data.second * MLS_PER_SECOND + int(data.microsecond / 1000))
else:
... | python | def prepare_time_millis(data, schema):
"""Convert datetime.time to int timestamp with milliseconds"""
if isinstance(data, datetime.time):
return int(
data.hour * MLS_PER_HOUR + data.minute * MLS_PER_MINUTE
+ data.second * MLS_PER_SECOND + int(data.microsecond / 1000))
else:
... | [
"def",
"prepare_time_millis",
"(",
"data",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"datetime",
".",
"time",
")",
":",
"return",
"int",
"(",
"data",
".",
"hour",
"*",
"MLS_PER_HOUR",
"+",
"data",
".",
"minute",
"*",
"MLS_PER_MINUTE"... | Convert datetime.time to int timestamp with milliseconds | [
"Convert",
"datetime",
".",
"time",
"to",
"int",
"timestamp",
"with",
"milliseconds"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L88-L95 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_time_micros | def prepare_time_micros(data, schema):
"""Convert datetime.time to int timestamp with microseconds"""
if isinstance(data, datetime.time):
return long(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE
+ data.second * MCS_PER_SECOND + data.microsecond)
else:
return da... | python | def prepare_time_micros(data, schema):
"""Convert datetime.time to int timestamp with microseconds"""
if isinstance(data, datetime.time):
return long(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE
+ data.second * MCS_PER_SECOND + data.microsecond)
else:
return da... | [
"def",
"prepare_time_micros",
"(",
"data",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"datetime",
".",
"time",
")",
":",
"return",
"long",
"(",
"data",
".",
"hour",
"*",
"MCS_PER_HOUR",
"+",
"data",
".",
"minute",
"*",
"MCS_PER_MINUTE... | Convert datetime.time to int timestamp with microseconds | [
"Convert",
"datetime",
".",
"time",
"to",
"int",
"timestamp",
"with",
"microseconds"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L98-L104 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_bytes_decimal | def prepare_bytes_decimal(data, schema):
"""Convert decimal.Decimal to bytes"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
# based on https://github.com/apache/avro/pull/82/
sign, digits, exp = data.as_tuple()
if -exp > scale:
raise Va... | python | def prepare_bytes_decimal(data, schema):
"""Convert decimal.Decimal to bytes"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
# based on https://github.com/apache/avro/pull/82/
sign, digits, exp = data.as_tuple()
if -exp > scale:
raise Va... | [
"def",
"prepare_bytes_decimal",
"(",
"data",
",",
"schema",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"decimal",
".",
"Decimal",
")",
":",
"return",
"data",
"scale",
"=",
"schema",
".",
"get",
"(",
"'scale'",
",",
"0",
")",
"sign",
",",
... | Convert decimal.Decimal to bytes | [
"Convert",
"decimal",
".",
"Decimal",
"to",
"bytes"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L107-L145 | train |
fastavro/fastavro | fastavro/_write_py.py | prepare_fixed_decimal | def prepare_fixed_decimal(data, schema):
"""Converts decimal.Decimal to fixed length bytes array"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
size = schema['size']
# based on https://github.com/apache/avro/pull/82/
sign, digits, exp = data.as_... | python | def prepare_fixed_decimal(data, schema):
"""Converts decimal.Decimal to fixed length bytes array"""
if not isinstance(data, decimal.Decimal):
return data
scale = schema.get('scale', 0)
size = schema['size']
# based on https://github.com/apache/avro/pull/82/
sign, digits, exp = data.as_... | [
"def",
"prepare_fixed_decimal",
"(",
"data",
",",
"schema",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"decimal",
".",
"Decimal",
")",
":",
"return",
"data",
"scale",
"=",
"schema",
".",
"get",
"(",
"'scale'",
",",
"0",
")",
"size",
"=",
... | Converts decimal.Decimal to fixed length bytes array | [
"Converts",
"decimal",
".",
"Decimal",
"to",
"fixed",
"length",
"bytes",
"array"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L148-L203 | train |
fastavro/fastavro | fastavro/_write_py.py | write_crc32 | def write_crc32(fo, bytes):
"""A 4-byte, big-endian CRC32 checksum"""
data = crc32(bytes) & 0xFFFFFFFF
fo.write(pack('>I', data)) | python | def write_crc32(fo, bytes):
"""A 4-byte, big-endian CRC32 checksum"""
data = crc32(bytes) & 0xFFFFFFFF
fo.write(pack('>I', data)) | [
"def",
"write_crc32",
"(",
"fo",
",",
"bytes",
")",
":",
"data",
"=",
"crc32",
"(",
"bytes",
")",
"&",
"0xFFFFFFFF",
"fo",
".",
"write",
"(",
"pack",
"(",
"'>I'",
",",
"data",
")",
")"
] | A 4-byte, big-endian CRC32 checksum | [
"A",
"4",
"-",
"byte",
"big",
"-",
"endian",
"CRC32",
"checksum"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L245-L248 | train |
fastavro/fastavro | fastavro/_write_py.py | write_union | def write_union(fo, datum, schema):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value. The value
is then encoded per the indicated schema within the union."""
if isinstance(datum, tuple):
(name, datum) = datum
... | python | def write_union(fo, datum, schema):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value. The value
is then encoded per the indicated schema within the union."""
if isinstance(datum, tuple):
(name, datum) = datum
... | [
"def",
"write_union",
"(",
"fo",
",",
"datum",
",",
"schema",
")",
":",
"if",
"isinstance",
"(",
"datum",
",",
"tuple",
")",
":",
"(",
"name",
",",
"datum",
")",
"=",
"datum",
"for",
"index",
",",
"candidate",
"in",
"enumerate",
"(",
"schema",
")",
... | A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value. The value
is then encoded per the indicated schema within the union. | [
"A",
"union",
"is",
"encoded",
"by",
"first",
"writing",
"a",
"long",
"value",
"indicating",
"the",
"zero",
"-",
"based",
"position",
"within",
"the",
"union",
"of",
"the",
"schema",
"of",
"its",
"value",
".",
"The",
"value",
"is",
"then",
"encoded",
"pe... | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L302-L341 | train |
fastavro/fastavro | fastavro/_write_py.py | write_data | def write_data(fo, datum, schema):
"""Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use
"""
record_type = extract_record_type(schema)
logical_type = extract_logical... | python | def write_data(fo, datum, schema):
"""Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use
"""
record_type = extract_record_type(schema)
logical_type = extract_logical... | [
"def",
"write_data",
"(",
"fo",
",",
"datum",
",",
"schema",
")",
":",
"record_type",
"=",
"extract_record_type",
"(",
"schema",
")",
"logical_type",
"=",
"extract_logical_type",
"(",
"schema",
")",
"fn",
"=",
"WRITERS",
".",
"get",
"(",
"record_type",
")",
... | Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use | [
"Write",
"a",
"datum",
"of",
"data",
"to",
"output",
"stream",
"."
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L390-L414 | train |
fastavro/fastavro | fastavro/_write_py.py | null_write_block | def null_write_block(fo, block_bytes):
"""Write block in "null" codec."""
write_long(fo, len(block_bytes))
fo.write(block_bytes) | python | def null_write_block(fo, block_bytes):
"""Write block in "null" codec."""
write_long(fo, len(block_bytes))
fo.write(block_bytes) | [
"def",
"null_write_block",
"(",
"fo",
",",
"block_bytes",
")",
":",
"write_long",
"(",
"fo",
",",
"len",
"(",
"block_bytes",
")",
")",
"fo",
".",
"write",
"(",
"block_bytes",
")"
] | Write block in "null" codec. | [
"Write",
"block",
"in",
"null",
"codec",
"."
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L426-L429 | train |
fastavro/fastavro | fastavro/_write_py.py | deflate_write_block | def deflate_write_block(fo, block_bytes):
"""Write block in "deflate" codec."""
# The first two characters and last character are zlib
# wrappers around deflate data.
data = compress(block_bytes)[2:-1]
write_long(fo, len(data))
fo.write(data) | python | def deflate_write_block(fo, block_bytes):
"""Write block in "deflate" codec."""
# The first two characters and last character are zlib
# wrappers around deflate data.
data = compress(block_bytes)[2:-1]
write_long(fo, len(data))
fo.write(data) | [
"def",
"deflate_write_block",
"(",
"fo",
",",
"block_bytes",
")",
":",
"data",
"=",
"compress",
"(",
"block_bytes",
")",
"[",
"2",
":",
"-",
"1",
"]",
"write_long",
"(",
"fo",
",",
"len",
"(",
"data",
")",
")",
"fo",
".",
"write",
"(",
"data",
")"
... | Write block in "deflate" codec. | [
"Write",
"block",
"in",
"deflate",
"codec",
"."
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L432-L439 | train |
fastavro/fastavro | fastavro/_write_py.py | schemaless_writer | def schemaless_writer(fo, schema, record):
"""Write a single record without the schema or header information
Parameters
----------
fo: file-like
Output file
schema: dict
Schema
record: dict
Record to write
Example::
parsed_schema = fastavro.parse_schema(sc... | python | def schemaless_writer(fo, schema, record):
"""Write a single record without the schema or header information
Parameters
----------
fo: file-like
Output file
schema: dict
Schema
record: dict
Record to write
Example::
parsed_schema = fastavro.parse_schema(sc... | [
"def",
"schemaless_writer",
"(",
"fo",
",",
"schema",
",",
"record",
")",
":",
"schema",
"=",
"parse_schema",
"(",
"schema",
")",
"write_data",
"(",
"fo",
",",
"record",
",",
"schema",
")"
] | Write a single record without the schema or header information
Parameters
----------
fo: file-like
Output file
schema: dict
Schema
record: dict
Record to write
Example::
parsed_schema = fastavro.parse_schema(schema)
with open('file.avro', 'rb') as fp:
... | [
"Write",
"a",
"single",
"record",
"without",
"the",
"schema",
"or",
"header",
"information"
] | bafe826293e19eb93e77bbb0f6adfa059c7884b2 | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L636-L658 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.