hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
630d4fcc33ef5a97cde094c940d212e5372e34ac | fractal-napari-plugins-collection/napari_tissuemaps_interface | src/napari_tissuemaps_interface/napari_tissuemaps_interface.py | [
"BSD-3-Clause"
] | Python | apply | List[LayerDataTuple] | def apply(self, token=("", "", ""),
experiment_name="",
channel_name="") -> List[LayerDataTuple]:
# pylint: disable=W0613
"""
Function executed when the "Load Data" button is pressed.
It calls the tissuemaps tissuemaps_interface and returns a napari
Im... |
Function executed when the "Load Data" button is pressed.
It calls the tissuemaps tissuemaps_interface and returns a napari
Image layer
:param token: The access token for querying TissueMAPS
:param experiment_name: The name of a TissueMAPS experiment
:param channel_name... | Function executed when the "Load Data" button is pressed.
It calls the tissuemaps tissuemaps_interface and returns a napari
Image layer | [
"Function",
"executed",
"when",
"the",
"\"",
"Load",
"Data",
"\"",
"button",
"is",
"pressed",
".",
"It",
"calls",
"the",
"tissuemaps",
"tissuemaps_interface",
"and",
"returns",
"a",
"napari",
"Image",
"layer"
] | def apply(self, token=("", "", ""),
experiment_name="",
channel_name="") -> List[LayerDataTuple]:
exp_id = [exp["id"] for exp in self.experiments if exp["name"] == experiment_name][0]
if channel_name == '-- All --':
multi_layer = []
for channel in self... | [
"def",
"apply",
"(",
"self",
",",
"token",
"=",
"(",
"\"\"",
",",
"\"\"",
",",
"\"\"",
")",
",",
"experiment_name",
"=",
"\"\"",
",",
"channel_name",
"=",
"\"\"",
")",
"->",
"List",
"[",
"LayerDataTuple",
"]",
":",
"exp_id",
"=",
"[",
"exp",
"[",
"... | Function executed when the "Load Data" button is pressed. | [
"Function",
"executed",
"when",
"the",
"\"",
"Load",
"Data",
"\"",
"button",
"is",
"pressed",
"."
] | [
"# pylint: disable=W0613",
"\"\"\"\n Function executed when the \"Load Data\" button is pressed.\n It calls the tissuemaps tissuemaps_interface and returns a napari\n Image layer\n\n :param token: The access token for querying TissueMAPS\n :param experiment_name: The name of a T... | [
{
"param": "self",
"type": null
},
{
"param": "token",
"type": null
},
{
"param": "experiment_name",
"type": null
},
{
"param": "channel_name",
"type": null
}
] | {
"returns": [
{
"docstring": "napari_layers.Image object, with access_token stored as metadata",
"docstring_tokens": [
"napari_layers",
".",
"Image",
"object",
"with",
"access_token",
"stored",
"as",
"metadata"
],
"ty... |
630d4fcc33ef5a97cde094c940d212e5372e34ac | fractal-napari-plugins-collection/napari_tissuemaps_interface | src/napari_tissuemaps_interface/napari_tissuemaps_interface.py | [
"BSD-3-Clause"
] | Python | napari_get_reader | <not_specific> | def napari_get_reader(path):
"""
Napari plugin that returns a reader interface for TissueMAPs .
.. note::
This hook does not support a list of paths
:param path: The path of the image
:return: The tissuemaps_interface function or None
"""
if isinstance(path, str) and path.endswith(... |
Napari plugin that returns a reader interface for TissueMAPs .
.. note::
This hook does not support a list of paths
:param path: The path of the image
:return: The tissuemaps_interface function or None
| Napari plugin that returns a reader interface for TissueMAPs .
note::
This hook does not support a list of paths | [
"Napari",
"plugin",
"that",
"returns",
"a",
"reader",
"interface",
"for",
"TissueMAPs",
".",
"note",
"::",
"This",
"hook",
"does",
"not",
"support",
"a",
"list",
"of",
"paths"
] | def napari_get_reader(path):
if isinstance(path, str) and path.endswith(".xmld"):
return tissuemaps_connector
return None | [
"def",
"napari_get_reader",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
"and",
"path",
".",
"endswith",
"(",
"\".xmld\"",
")",
":",
"return",
"tissuemaps_connector",
"return",
"None"
] | Napari plugin that returns a reader interface for TissueMAPs . | [
"Napari",
"plugin",
"that",
"returns",
"a",
"reader",
"interface",
"for",
"TissueMAPs",
"."
] | [
"\"\"\"\n Napari plugin that returns a reader interface for TissueMAPs .\n\n .. note::\n This hook does not support a list of paths\n\n :param path: The path of the image\n :return: The tissuemaps_interface function or None\n \"\"\""
] | [
{
"param": "path",
"type": null
}
] | {
"returns": [
{
"docstring": "The tissuemaps_interface function or None",
"docstring_tokens": [
"The",
"tissuemaps_interface",
"function",
"or",
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "path",
... |
630d4fcc33ef5a97cde094c940d212e5372e34ac | fractal-napari-plugins-collection/napari_tissuemaps_interface | src/napari_tissuemaps_interface/napari_tissuemaps_interface.py | [
"BSD-3-Clause"
] | Python | napari_experimental_provide_dock_widget | <not_specific> | def napari_experimental_provide_dock_widget():
"""
Napari plugin that returns a Magicui widget
:return: The TissueMAPS connection widget
"""
return TissueMAPSConnectionWidget |
Napari plugin that returns a Magicui widget
:return: The TissueMAPS connection widget
| Napari plugin that returns a Magicui widget | [
"Napari",
"plugin",
"that",
"returns",
"a",
"Magicui",
"widget"
] | def napari_experimental_provide_dock_widget():
return TissueMAPSConnectionWidget | [
"def",
"napari_experimental_provide_dock_widget",
"(",
")",
":",
"return",
"TissueMAPSConnectionWidget"
] | Napari plugin that returns a Magicui widget | [
"Napari",
"plugin",
"that",
"returns",
"a",
"Magicui",
"widget"
] | [
"\"\"\"\n Napari plugin that returns a Magicui widget\n :return: The TissueMAPS connection widget\n \"\"\""
] | [] | {
"returns": [
{
"docstring": "The TissueMAPS connection widget",
"docstring_tokens": [
"The",
"TissueMAPS",
"connection",
"widget"
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
924e6cd3af9683abeaf627a2ca0c142deda7da84 | trueship/django-tastypie-swagger | tastypie_swagger/views.py | [
"BSD-2-Clause"
] | Python | render_to_response | <not_specific> | def render_to_response(self, context, **response_kwargs):
"""
Returns a response with a template rendered with the given context.
"""
for k in ['params','view']:
if k in context:
del context[k]
return self.response_class(
json.dumps(context... |
Returns a response with a template rendered with the given context.
| Returns a response with a template rendered with the given context. | [
"Returns",
"a",
"response",
"with",
"a",
"template",
"rendered",
"with",
"the",
"given",
"context",
"."
] | def render_to_response(self, context, **response_kwargs):
for k in ['params','view']:
if k in context:
del context[k]
return self.response_class(
json.dumps(context),
content_type='application/json',
**response_kwargs
) | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"**",
"response_kwargs",
")",
":",
"for",
"k",
"in",
"[",
"'params'",
",",
"'view'",
"]",
":",
"if",
"k",
"in",
"context",
":",
"del",
"context",
"[",
"k",
"]",
"return",
"self",
".",
"re... | Returns a response with a template rendered with the given context. | [
"Returns",
"a",
"response",
"with",
"a",
"template",
"rendered",
"with",
"the",
"given",
"context",
"."
] | [
"\"\"\"\n Returns a response with a template rendered with the given context.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "context",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "context",
"type": null,
"docstring": null,
"docstring_tokens"... |
43440aa1df249515e370c8c0b4016e1bdc213a75 | mindis/Next-Basket-Recommendation-1 | DREAM/train.py | [
"Apache-2.0"
] | Python | bpr_loss | <not_specific> | def bpr_loss(uids, baskets, dynamic_user, item_embedding):
"""
Bayesian personalized ranking loss for implicit feedback.
Args:
uids: batch of users' ID
baskets: batch of users' baskets
dynamic_user: batch of users' dynamic representations
item_emb... |
Bayesian personalized ranking loss for implicit feedback.
Args:
uids: batch of users' ID
baskets: batch of users' baskets
dynamic_user: batch of users' dynamic representations
item_embedding: item_embedding matrix
| Bayesian personalized ranking loss for implicit feedback. | [
"Bayesian",
"personalized",
"ranking",
"loss",
"for",
"implicit",
"feedback",
"."
] | def bpr_loss(uids, baskets, dynamic_user, item_embedding):
loss = 0
for uid, bks, du in zip(uids, baskets, dynamic_user):
du_p_product = torch.mm(du, item_embedding.t())
loss_u = []
for t, basket_t in enumerate(bks):
if basket_t[0] != 0 and t != 0:... | [
"def",
"bpr_loss",
"(",
"uids",
",",
"baskets",
",",
"dynamic_user",
",",
"item_embedding",
")",
":",
"loss",
"=",
"0",
"for",
"uid",
",",
"bks",
",",
"du",
"in",
"zip",
"(",
"uids",
",",
"baskets",
",",
"dynamic_user",
")",
":",
"du_p_product",
"=",
... | Bayesian personalized ranking loss for implicit feedback. | [
"Bayesian",
"personalized",
"ranking",
"loss",
"for",
"implicit",
"feedback",
"."
] | [
"\"\"\"\n Bayesian personalized ranking loss for implicit feedback.\n\n Args:\n uids: batch of users' ID\n baskets: batch of users' baskets\n dynamic_user: batch of users' dynamic representations\n item_embedding: item_embedding matrix\n \"\"\"",
"#... | [
{
"param": "uids",
"type": null
},
{
"param": "baskets",
"type": null
},
{
"param": "dynamic_user",
"type": null
},
{
"param": "item_embedding",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "uids",
"type": null,
"docstring": "batch of users' ID",
"docstring_tokens": [
"batch",
"of",
"users",
"'",
"ID"
],
"default": null,
"is_optional": null
},
{
... |
497ff3ebca125433562c2dc673669cbfe9d32c41 | Moduland/instatag | instatag/instatag.py | [
"MIT"
] | Python | print_line | null | def print_line(number=30,char="-"):
'''
This function print line in screen
:param number: number of items in each line
:param char: each char of line
:return: None
'''
line=""
i=0
while(i<number):
i+=1
line=line+char
print(line) |
This function print line in screen
:param number: number of items in each line
:param char: each char of line
:return: None
| This function print line in screen | [
"This",
"function",
"print",
"line",
"in",
"screen"
] | def print_line(number=30,char="-"):
line=""
i=0
while(i<number):
i+=1
line=line+char
print(line) | [
"def",
"print_line",
"(",
"number",
"=",
"30",
",",
"char",
"=",
"\"-\"",
")",
":",
"line",
"=",
"\"\"",
"i",
"=",
"0",
"while",
"(",
"i",
"<",
"number",
")",
":",
"i",
"+=",
"1",
"line",
"=",
"line",
"+",
"char",
"print",
"(",
"line",
")"
] | This function print line in screen | [
"This",
"function",
"print",
"line",
"in",
"screen"
] | [
"'''\n This function print line in screen\n :param number: number of items in each line\n :param char: each char of line\n :return: None\n '''"
] | [
{
"param": "number",
"type": null
},
{
"param": "char",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "number",
"type": null,
"docstring": "number of items in each line",
"docstring_tokens": [
"number",
... |
497ff3ebca125433562c2dc673669cbfe9d32c41 | Moduland/instatag | instatag/instatag.py | [
"MIT"
] | Python | create_random_sleep | <not_specific> | def create_random_sleep(index=1,min_time=5,max_time=60):
'''
This function generate sleep time with random processes
:param index: index to determine first page and messages(index = 0 is for first page)
:param min_time: minimum time of sleep
:param max_time: maximum time of sleep
:type index:in... |
This function generate sleep time with random processes
:param index: index to determine first page and messages(index = 0 is for first page)
:param min_time: minimum time of sleep
:param max_time: maximum time of sleep
:type index:int
:type min_time:int
:type max_time:int
:return: tim... | This function generate sleep time with random processes | [
"This",
"function",
"generate",
"sleep",
"time",
"with",
"random",
"processes"
] | def create_random_sleep(index=1,min_time=5,max_time=60):
if index==0:
time_sleep = 5
if DEBUG==True:
print("Wait "+str(time_sleep)+" sec for first search . . .")
else:
time_sleep = randint(min_time, max_time)
if DEBUG==True:
print("Wait "+str(time_sleep)+"... | [
"def",
"create_random_sleep",
"(",
"index",
"=",
"1",
",",
"min_time",
"=",
"5",
",",
"max_time",
"=",
"60",
")",
":",
"if",
"index",
"==",
"0",
":",
"time_sleep",
"=",
"5",
"if",
"DEBUG",
"==",
"True",
":",
"print",
"(",
"\"Wait \"",
"+",
"str",
"... | This function generate sleep time with random processes | [
"This",
"function",
"generate",
"sleep",
"time",
"with",
"random",
"processes"
] | [
"'''\n This function generate sleep time with random processes\n :param index: index to determine first page and messages(index = 0 is for first page)\n :param min_time: minimum time of sleep\n :param max_time: maximum time of sleep\n :type index:int\n :type min_time:int\n :type max_time:int\n... | [
{
"param": "index",
"type": null
},
{
"param": "min_time",
"type": null
},
{
"param": "max_time",
"type": null
}
] | {
"returns": [
{
"docstring": "time of sleep as integer (a number between max and min)",
"docstring_tokens": [
"time",
"of",
"sleep",
"as",
"integer",
"(",
"a",
"number",
"between",
"max",
"and",
"min",
... |
497ff3ebca125433562c2dc673669cbfe9d32c41 | Moduland/instatag | instatag/instatag.py | [
"MIT"
] | Python | step_2_gen | null | def step_2_gen(name_list,tag):
'''
This function extract 2nd users (from 1st users follower and following list)
:param name_list: 1st users id
:param tag: hashtag
:type name:list
:type tag:str
:return: None
'''
try:
file=io.open("insta_data/users_2_"+tag+".txt","a",encoding="... |
This function extract 2nd users (from 1st users follower and following list)
:param name_list: 1st users id
:param tag: hashtag
:type name:list
:type tag:str
:return: None
| This function extract 2nd users (from 1st users follower and following list) | [
"This",
"function",
"extract",
"2nd",
"users",
"(",
"from",
"1st",
"users",
"follower",
"and",
"following",
"list",
")"
] | def step_2_gen(name_list,tag):
try:
file=io.open("insta_data/users_2_"+tag+".txt","a",encoding="utf-8")
user_list=[]
for i in range(len(name_list)):
print("ID : "+name_list[i])
user_url=step_2_url_maker(name_list[i])
raw_html=get_html(user_url,max_delay=8)... | [
"def",
"step_2_gen",
"(",
"name_list",
",",
"tag",
")",
":",
"try",
":",
"file",
"=",
"io",
".",
"open",
"(",
"\"insta_data/users_2_\"",
"+",
"tag",
"+",
"\".txt\"",
",",
"\"a\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"user_list",
"=",
"[",
"]",
"for... | This function extract 2nd users (from 1st users follower and following list) | [
"This",
"function",
"extract",
"2nd",
"users",
"(",
"from",
"1st",
"users",
"follower",
"and",
"following",
"list",
")"
] | [
"'''\n This function extract 2nd users (from 1st users follower and following list)\n :param name_list: 1st users id\n :param tag: hashtag\n :type name:list\n :type tag:str\n :return: None\n '''"
] | [
{
"param": "name_list",
"type": null
},
{
"param": "tag",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "name_list",
"type": null,
"docstring": "1st users id",
"docstring_tokens": [
"1st",
"users",
... |
497ff3ebca125433562c2dc673669cbfe9d32c41 | Moduland/instatag | instatag/instatag.py | [
"MIT"
] | Python | user_list_gen | null | def user_list_gen(tag):
'''
This function extract user_list for each tag in first step and then run step_2_gen for second users
:param tag: hastag
:type tag:str
:return: None
'''
try:
hash_list = post_list_gen(tag)
file=io.open("insta_data/users_1_"+tag+".txt","a",encoding="u... |
This function extract user_list for each tag in first step and then run step_2_gen for second users
:param tag: hastag
:type tag:str
:return: None
| This function extract user_list for each tag in first step and then run step_2_gen for second users | [
"This",
"function",
"extract",
"user_list",
"for",
"each",
"tag",
"in",
"first",
"step",
"and",
"then",
"run",
"step_2_gen",
"for",
"second",
"users"
] | def user_list_gen(tag):
try:
hash_list = post_list_gen(tag)
file=io.open("insta_data/users_1_"+tag+".txt","a",encoding="utf-8")
user_list=[]
for i in range(len(hash_list)):
print("Code : "+hash_list[i])
user_url = post_url_maker(hash_list[i])
raw_h... | [
"def",
"user_list_gen",
"(",
"tag",
")",
":",
"try",
":",
"hash_list",
"=",
"post_list_gen",
"(",
"tag",
")",
"file",
"=",
"io",
".",
"open",
"(",
"\"insta_data/users_1_\"",
"+",
"tag",
"+",
"\".txt\"",
",",
"\"a\"",
",",
"encoding",
"=",
"\"utf-8\"",
")... | This function extract user_list for each tag in first step and then run step_2_gen for second users | [
"This",
"function",
"extract",
"user_list",
"for",
"each",
"tag",
"in",
"first",
"step",
"and",
"then",
"run",
"step_2_gen",
"for",
"second",
"users"
] | [
"'''\n This function extract user_list for each tag in first step and then run step_2_gen for second users\n :param tag: hastag\n :type tag:str\n :return: None\n '''"
] | [
{
"param": "tag",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "tag",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"... |
015fefde675b0538e9b09afbfb97d0a06782fcb1 | congruency/txpoloniex | test/test_queue.py | [
"Apache-2.0"
] | Python | _flush | null | def _flush(self):
"""
Flush state for a clean testing slate
"""
self.count = 0
self.queue.clear() |
Flush state for a clean testing slate
| Flush state for a clean testing slate | [
"Flush",
"state",
"for",
"a",
"clean",
"testing",
"slate"
] | def _flush(self):
self.count = 0
self.queue.clear() | [
"def",
"_flush",
"(",
"self",
")",
":",
"self",
".",
"count",
"=",
"0",
"self",
".",
"queue",
".",
"clear",
"(",
")"
] | Flush state for a clean testing slate | [
"Flush",
"state",
"for",
"a",
"clean",
"testing",
"slate"
] | [
"\"\"\"\n Flush state for a clean testing slate\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
063e3368cef2e7571262453ab7276f557e7fec49 | congruency/txpoloniex | examples/ticker.py | [
"Apache-2.0"
] | Python | ticker | null | def ticker(reactor):
"""
Print the last price for each symbol
"""
tick = yield Poloniex().ticker()
for pair in sorted(tick):
last = tick[pair]['last']
print('{pair}: {last}'.format(pair=pair, last=last)) |
Print the last price for each symbol
| Print the last price for each symbol | [
"Print",
"the",
"last",
"price",
"for",
"each",
"symbol"
] | def ticker(reactor):
tick = yield Poloniex().ticker()
for pair in sorted(tick):
last = tick[pair]['last']
print('{pair}: {last}'.format(pair=pair, last=last)) | [
"def",
"ticker",
"(",
"reactor",
")",
":",
"tick",
"=",
"yield",
"Poloniex",
"(",
")",
".",
"ticker",
"(",
")",
"for",
"pair",
"in",
"sorted",
"(",
"tick",
")",
":",
"last",
"=",
"tick",
"[",
"pair",
"]",
"[",
"'last'",
"]",
"print",
"(",
"'{pair... | Print the last price for each symbol | [
"Print",
"the",
"last",
"price",
"for",
"each",
"symbol"
] | [
"\"\"\"\n Print the last price for each symbol\n \"\"\""
] | [
{
"param": "reactor",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "reactor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ea2939c51d6b63765b5838f2fa4e8d0261214da8 | congruency/txpoloniex | txpoloniex/queue.py | [
"Apache-2.0"
] | Python | _nextDelay | <not_specific> | def _nextDelay(self):
"""
Returns the amount of time to delay the next call
"""
length = len(self._times)
limit = self.maxPerSecond
remainder = length % limit
difference = 0
base = length // self.maxPerSecond
if not limit or not length or not... |
Returns the amount of time to delay the next call
| Returns the amount of time to delay the next call | [
"Returns",
"the",
"amount",
"of",
"time",
"to",
"delay",
"the",
"next",
"call"
] | def _nextDelay(self):
length = len(self._times)
limit = self.maxPerSecond
remainder = length % limit
difference = 0
base = length // self.maxPerSecond
if not limit or not length or not base:
return 0.0
last = self._times[-1]
i = length - limit
... | [
"def",
"_nextDelay",
"(",
"self",
")",
":",
"length",
"=",
"len",
"(",
"self",
".",
"_times",
")",
"limit",
"=",
"self",
".",
"maxPerSecond",
"remainder",
"=",
"length",
"%",
"limit",
"difference",
"=",
"0",
"base",
"=",
"length",
"//",
"self",
".",
... | Returns the amount of time to delay the next call | [
"Returns",
"the",
"amount",
"of",
"time",
"to",
"delay",
"the",
"next",
"call"
] | [
"\"\"\"\n Returns the amount of time to delay the next call\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ea2939c51d6b63765b5838f2fa4e8d0261214da8 | congruency/txpoloniex | txpoloniex/queue.py | [
"Apache-2.0"
] | Python | _called | null | def _called(self, ignoredResult):
"""
Record the time that the deferred was called
"""
self._times.append(self.reactor.seconds())
# Once a second has passed, remove the recorded time
de = self.reactor.callLater(1.0, self._expire)
self._expirations.append(de) |
Record the time that the deferred was called
| Record the time that the deferred was called | [
"Record",
"the",
"time",
"that",
"the",
"deferred",
"was",
"called"
] | def _called(self, ignoredResult):
self._times.append(self.reactor.seconds())
de = self.reactor.callLater(1.0, self._expire)
self._expirations.append(de) | [
"def",
"_called",
"(",
"self",
",",
"ignoredResult",
")",
":",
"self",
".",
"_times",
".",
"append",
"(",
"self",
".",
"reactor",
".",
"seconds",
"(",
")",
")",
"de",
"=",
"self",
".",
"reactor",
".",
"callLater",
"(",
"1.0",
",",
"self",
".",
"_ex... | Record the time that the deferred was called | [
"Record",
"the",
"time",
"that",
"the",
"deferred",
"was",
"called"
] | [
"\"\"\"\n Record the time that the deferred was called\n \"\"\"",
"# Once a second has passed, remove the recorded time"
] | [
{
"param": "self",
"type": null
},
{
"param": "ignoredResult",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ignoredResult",
"type": null,
"docstring": null,
"docstring_t... |
ea2939c51d6b63765b5838f2fa4e8d0261214da8 | congruency/txpoloniex | txpoloniex/queue.py | [
"Apache-2.0"
] | Python | _expire | null | def _expire(self):
"""
Called to remove the time from calculations after a second has expired
"""
self._times.pop(0) |
Called to remove the time from calculations after a second has expired
| Called to remove the time from calculations after a second has expired | [
"Called",
"to",
"remove",
"the",
"time",
"from",
"calculations",
"after",
"a",
"second",
"has",
"expired"
] | def _expire(self):
self._times.pop(0) | [
"def",
"_expire",
"(",
"self",
")",
":",
"self",
".",
"_times",
".",
"pop",
"(",
"0",
")"
] | Called to remove the time from calculations after a second has expired | [
"Called",
"to",
"remove",
"the",
"time",
"from",
"calculations",
"after",
"a",
"second",
"has",
"expired"
] | [
"\"\"\"\n Called to remove the time from calculations after a second has expired\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ea2939c51d6b63765b5838f2fa4e8d0261214da8 | congruency/txpoloniex | txpoloniex/queue.py | [
"Apache-2.0"
] | Python | _cancel | null | def _cancel(self, d):
"""
Remove d from waiting and cancel the expiration
"""
i = self.waiting.index(d)
self.waiting.pop(i)
df = self._expirations.pop(i)
df.cancel() |
Remove d from waiting and cancel the expiration
| Remove d from waiting and cancel the expiration | [
"Remove",
"d",
"from",
"waiting",
"and",
"cancel",
"the",
"expiration"
] | def _cancel(self, d):
i = self.waiting.index(d)
self.waiting.pop(i)
df = self._expirations.pop(i)
df.cancel() | [
"def",
"_cancel",
"(",
"self",
",",
"d",
")",
":",
"i",
"=",
"self",
".",
"waiting",
".",
"index",
"(",
"d",
")",
"self",
".",
"waiting",
".",
"pop",
"(",
"i",
")",
"df",
"=",
"self",
".",
"_expirations",
".",
"pop",
"(",
"i",
")",
"df",
".",... | Remove d from waiting and cancel the expiration | [
"Remove",
"d",
"from",
"waiting",
"and",
"cancel",
"the",
"expiration"
] | [
"\"\"\"\n Remove d from waiting and cancel the expiration\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "d",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "d",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
ea2939c51d6b63765b5838f2fa4e8d0261214da8 | congruency/txpoloniex | txpoloniex/queue.py | [
"Apache-2.0"
] | Python | clear | null | def clear(self):
"""
Cancel all pending calls and flush state
"""
for d in self.waiting:
self._cancel(d)
for d in self._expirations:
d.cancel()
self._times = []
self._expirations = [] |
Cancel all pending calls and flush state
| Cancel all pending calls and flush state | [
"Cancel",
"all",
"pending",
"calls",
"and",
"flush",
"state"
] | def clear(self):
for d in self.waiting:
self._cancel(d)
for d in self._expirations:
d.cancel()
self._times = []
self._expirations = [] | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"d",
"in",
"self",
".",
"waiting",
":",
"self",
".",
"_cancel",
"(",
"d",
")",
"for",
"d",
"in",
"self",
".",
"_expirations",
":",
"d",
".",
"cancel",
"(",
")",
"self",
".",
"_times",
"=",
"[",
"]",... | Cancel all pending calls and flush state | [
"Cancel",
"all",
"pending",
"calls",
"and",
"flush",
"state"
] | [
"\"\"\"\n Cancel all pending calls and flush state\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f969f26bec4648a67c39be2eb1a579f2f97b1a7f | davidthaler/Greek_media | models.py | [
"MIT"
] | Python | decision_function | <not_specific> | def decision_function(self, x):
'''
Computes a matrix of real-valued scores reflecting the strength
of belief that an instance is in a particular class.
Params:
x - input features
Returns:
a real-valued matrix of dimension (# instances) x (# classes)
'''
zdv = self.lm.... |
Computes a matrix of real-valued scores reflecting the strength
of belief that an instance is in a particular class.
Params:
x - input features
Returns:
a real-valued matrix of dimension (# instances) x (# classes)
| Computes a matrix of real-valued scores reflecting the strength
of belief that an instance is in a particular class.
input features
a real-valued matrix of dimension (# instances) x (# classes) | [
"Computes",
"a",
"matrix",
"of",
"real",
"-",
"valued",
"scores",
"reflecting",
"the",
"strength",
"of",
"belief",
"that",
"an",
"instance",
"is",
"in",
"a",
"particular",
"class",
".",
"input",
"features",
"a",
"real",
"-",
"valued",
"matrix",
"of",
"dime... | def decision_function(self, x):
zdv = self.lm.decision_function(x)
return self.pca.inverse_transform(zdv) | [
"def",
"decision_function",
"(",
"self",
",",
"x",
")",
":",
"zdv",
"=",
"self",
".",
"lm",
".",
"decision_function",
"(",
"x",
")",
"return",
"self",
".",
"pca",
".",
"inverse_transform",
"(",
"zdv",
")"
] | Computes a matrix of real-valued scores reflecting the strength
of belief that an instance is in a particular class. | [
"Computes",
"a",
"matrix",
"of",
"real",
"-",
"valued",
"scores",
"reflecting",
"the",
"strength",
"of",
"belief",
"that",
"an",
"instance",
"is",
"in",
"a",
"particular",
"class",
"."
] | [
"'''\n Computes a matrix of real-valued scores reflecting the strength \n of belief that an instance is in a particular class.\n \n Params:\n x - input features\n \n Returns:\n a real-valued matrix of dimension (# instances) x (# classes)\n '''"
] | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
f969f26bec4648a67c39be2eb1a579f2f97b1a7f | davidthaler/Greek_media | models.py | [
"MIT"
] | Python | predict | <not_specific> | def predict(self, x):
'''
Computes a 0-1 matrix of predicted labels for each instance.
Params:
x - input features
Returns:
A 0-1 matrix of predicted labels.
'''
dv = self.decision_function(x)
return repredict(dv, self.t1, self.t2) |
Computes a 0-1 matrix of predicted labels for each instance.
Params:
x - input features
Returns:
A 0-1 matrix of predicted labels.
| Computes a 0-1 matrix of predicted labels for each instance.
Params:
x - input features
A 0-1 matrix of predicted labels. | [
"Computes",
"a",
"0",
"-",
"1",
"matrix",
"of",
"predicted",
"labels",
"for",
"each",
"instance",
".",
"Params",
":",
"x",
"-",
"input",
"features",
"A",
"0",
"-",
"1",
"matrix",
"of",
"predicted",
"labels",
"."
] | def predict(self, x):
dv = self.decision_function(x)
return repredict(dv, self.t1, self.t2) | [
"def",
"predict",
"(",
"self",
",",
"x",
")",
":",
"dv",
"=",
"self",
".",
"decision_function",
"(",
"x",
")",
"return",
"repredict",
"(",
"dv",
",",
"self",
".",
"t1",
",",
"self",
".",
"t2",
")"
] | Computes a 0-1 matrix of predicted labels for each instance. | [
"Computes",
"a",
"0",
"-",
"1",
"matrix",
"of",
"predicted",
"labels",
"for",
"each",
"instance",
"."
] | [
"'''\n Computes a 0-1 matrix of predicted labels for each instance.\n \n Params:\n x - input features\n \n Returns:\n A 0-1 matrix of predicted labels.\n '''"
] | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
f969f26bec4648a67c39be2eb1a579f2f97b1a7f | davidthaler/Greek_media | models.py | [
"MIT"
] | Python | predict | <not_specific> | def predict(self, x):
'''
Prediction method predicts class membership of instances with decision
values above threshold t1 or within t2 of the highest decision value
on that instance.
Params:
x - input features, not used
y - 0-1 label matrix, not used
Returns:
A 0-1 m... |
Prediction method predicts class membership of instances with decision
values above threshold t1 or within t2 of the highest decision value
on that instance.
Params:
x - input features, not used
y - 0-1 label matrix, not used
Returns:
A 0-1 matrix of predicted labels of ... | Prediction method predicts class membership of instances with decision
values above threshold t1 or within t2 of the highest decision value
on that instance.
input features, not used
y - 0-1 label matrix, not used
A 0-1 matrix of predicted labels of size (# instances) x (# classes). | [
"Prediction",
"method",
"predicts",
"class",
"membership",
"of",
"instances",
"with",
"decision",
"values",
"above",
"threshold",
"t1",
"or",
"within",
"t2",
"of",
"the",
"highest",
"decision",
"value",
"on",
"that",
"instance",
".",
"input",
"features",
"not",
... | def predict(self, x):
dvs = self.decision_function(x)
pred = (dvs > self.t1).astype(float)
max_dv = dvs.max(1)
for k in range(pred.shape[0]):
cut = max_dv[k] - self.t2
idx = (dvs[k, :] >= cut)
pred[k, idx] = 1
return pred | [
"def",
"predict",
"(",
"self",
",",
"x",
")",
":",
"dvs",
"=",
"self",
".",
"decision_function",
"(",
"x",
")",
"pred",
"=",
"(",
"dvs",
">",
"self",
".",
"t1",
")",
".",
"astype",
"(",
"float",
")",
"max_dv",
"=",
"dvs",
".",
"max",
"(",
"1",
... | Prediction method predicts class membership of instances with decision
values above threshold t1 or within t2 of the highest decision value
on that instance. | [
"Prediction",
"method",
"predicts",
"class",
"membership",
"of",
"instances",
"with",
"decision",
"values",
"above",
"threshold",
"t1",
"or",
"within",
"t2",
"of",
"the",
"highest",
"decision",
"value",
"on",
"that",
"instance",
"."
] | [
"'''\n Prediction method predicts class membership of instances with decision \n values above threshold t1 or within t2 of the highest decision value \n on that instance.\n \n Params:\n x - input features, not used\n y - 0-1 label matrix, not used\n \n Returns:\n A 0-1 matrix of pr... | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
f969f26bec4648a67c39be2eb1a579f2f97b1a7f | davidthaler/Greek_media | models.py | [
"MIT"
] | Python | predict | <not_specific> | def predict(self, x):
'''
Computes a 0-1 matrix of predicted labels for each instance.
Params:
x - input features
Returns:
A 0-1 matrix of predicted labels.
'''
dv = self.decision_function(x)
return repredict(dv, self.thr, self.t2) |
Computes a 0-1 matrix of predicted labels for each instance.
Params:
x - input features
Returns:
A 0-1 matrix of predicted labels.
| Computes a 0-1 matrix of predicted labels for each instance.
Params:
x - input features
A 0-1 matrix of predicted labels. | [
"Computes",
"a",
"0",
"-",
"1",
"matrix",
"of",
"predicted",
"labels",
"for",
"each",
"instance",
".",
"Params",
":",
"x",
"-",
"input",
"features",
"A",
"0",
"-",
"1",
"matrix",
"of",
"predicted",
"labels",
"."
] | def predict(self, x):
dv = self.decision_function(x)
return repredict(dv, self.thr, self.t2) | [
"def",
"predict",
"(",
"self",
",",
"x",
")",
":",
"dv",
"=",
"self",
".",
"decision_function",
"(",
"x",
")",
"return",
"repredict",
"(",
"dv",
",",
"self",
".",
"thr",
",",
"self",
".",
"t2",
")"
] | Computes a 0-1 matrix of predicted labels for each instance. | [
"Computes",
"a",
"0",
"-",
"1",
"matrix",
"of",
"predicted",
"labels",
"for",
"each",
"instance",
"."
] | [
"'''\n Computes a 0-1 matrix of predicted labels for each instance.\n \n Params:\n x - input features\n \n Returns:\n A 0-1 matrix of predicted labels.\n '''"
] | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
f969f26bec4648a67c39be2eb1a579f2f97b1a7f | davidthaler/Greek_media | models.py | [
"MIT"
] | Python | dv2f | <not_specific> | def dv2f(self, dv, dv0, x):
'''
Computes the features used in the StackModel. These are:
the decision value (DV) and max DV by row under the UniformOVA
model; the DV and max DV by row under RidgePCA model; the
median dv for positive and negative instances of each class;
the estimated counts und... |
Computes the features used in the StackModel. These are:
the decision value (DV) and max DV by row under the UniformOVA
model; the DV and max DV by row under RidgePCA model; the
median dv for positive and negative instances of each class;
the estimated counts under the count model.
| Computes the features used in the StackModel. These are:
the decision value (DV) and max DV by row under the UniformOVA
model; the DV and max DV by row under RidgePCA model; the
median dv for positive and negative instances of each class;
the estimated counts under the count model. | [
"Computes",
"the",
"features",
"used",
"in",
"the",
"StackModel",
".",
"These",
"are",
":",
"the",
"decision",
"value",
"(",
"DV",
")",
"and",
"max",
"DV",
"by",
"row",
"under",
"the",
"UniformOVA",
"model",
";",
"the",
"DV",
"and",
"max",
"DV",
"by",
... | def dv2f(self, dv, dv0, x):
rowmax = dv.max(1)
row_dv = (dv.transpose() - rowmax).transpose()
rowmax0 = dv0.max(1)
row_dv0 = (dv0.transpose() - rowmax0).transpose()
rates = np.tile(self.yrate, (dv.shape[0], 1) )
posdv = np.tile(self.posdv, (dv.shape[0], 1) )
posdv0 = np.tile(self.posdv0, (dv... | [
"def",
"dv2f",
"(",
"self",
",",
"dv",
",",
"dv0",
",",
"x",
")",
":",
"rowmax",
"=",
"dv",
".",
"max",
"(",
"1",
")",
"row_dv",
"=",
"(",
"dv",
".",
"transpose",
"(",
")",
"-",
"rowmax",
")",
".",
"transpose",
"(",
")",
"rowmax0",
"=",
"dv0"... | Computes the features used in the StackModel. | [
"Computes",
"the",
"features",
"used",
"in",
"the",
"StackModel",
"."
] | [
"'''\n Computes the features used in the StackModel. These are:\n the decision value (DV) and max DV by row under the UniformOVA\n model; the DV and max DV by row under RidgePCA model; the \n median dv for positive and negative instances of each class;\n the estimated counts under the count model. \n... | [
{
"param": "self",
"type": null
},
{
"param": "dv",
"type": null
},
{
"param": "dv0",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dv",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
f969f26bec4648a67c39be2eb1a579f2f97b1a7f | davidthaler/Greek_media | models.py | [
"MIT"
] | Python | cvdv | <not_specific> | def cvdv(model, x, y, k=3, use_predict=False):
"""
Get dvs for all of x by training on k folds, predicting on 1,
and aggregating the predictions into an object the same shape as y.
Params:
x - input features
y - 0-1 label matrix
k - # of cross-validation folds
use_predict - If true, use predi... |
Get dvs for all of x by training on k folds, predicting on 1,
and aggregating the predictions into an object the same shape as y.
Params:
x - input features
y - 0-1 label matrix
k - # of cross-validation folds
use_predict - If true, use predict() instead of decision_value()
to get the ... | Get dvs for all of x by training on k folds, predicting on 1,
and aggregating the predictions into an object the same shape as y.
a real matrix of predictions made within cross-validation | [
"Get",
"dvs",
"for",
"all",
"of",
"x",
"by",
"training",
"on",
"k",
"folds",
"predicting",
"on",
"1",
"and",
"aggregating",
"the",
"predictions",
"into",
"an",
"object",
"the",
"same",
"shape",
"as",
"y",
".",
"a",
"real",
"matrix",
"of",
"predictions",
... | def cvdv(model, x, y, k=3, use_predict=False):
folds = KFold(y.shape[0], k)
dv = 0*y
for train, val in folds:
model.fit(x[train], y[train])
if use_predict:
dv[val] = model.predict(x[val])
else:
dv[val] = model.decision_function(x[val])
return dv | [
"def",
"cvdv",
"(",
"model",
",",
"x",
",",
"y",
",",
"k",
"=",
"3",
",",
"use_predict",
"=",
"False",
")",
":",
"folds",
"=",
"KFold",
"(",
"y",
".",
"shape",
"[",
"0",
"]",
",",
"k",
")",
"dv",
"=",
"0",
"*",
"y",
"for",
"train",
",",
"... | Get dvs for all of x by training on k folds, predicting on 1,
and aggregating the predictions into an object the same shape as y. | [
"Get",
"dvs",
"for",
"all",
"of",
"x",
"by",
"training",
"on",
"k",
"folds",
"predicting",
"on",
"1",
"and",
"aggregating",
"the",
"predictions",
"into",
"an",
"object",
"the",
"same",
"shape",
"as",
"y",
"."
] | [
"\"\"\"\n Get dvs for all of x by training on k folds, predicting on 1,\n and aggregating the predictions into an object the same shape as y.\n \n Params:\n x - input features\n y - 0-1 label matrix\n k - # of cross-validation folds\n use_predict - If true, use predict() instead of decision_value()\... | [
{
"param": "model",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "k",
"type": null
},
{
"param": "use_predict",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
f969f26bec4648a67c39be2eb1a579f2f97b1a7f | davidthaler/Greek_media | models.py | [
"MIT"
] | Python | repredict | <not_specific> | def repredict(dv, t1, t2):
"""
Takes decision values and returns predictions, given thresholds
for the overall level and for distance to the row-wise maximum.
Params:
dv - 2d array of decision values
t1 - either a scalar threshold, or a vector of length(dv.shape[1])
all dvs > t1 are positiv... |
Takes decision values and returns predictions, given thresholds
for the overall level and for distance to the row-wise maximum.
Params:
dv - 2d array of decision values
t1 - either a scalar threshold, or a vector of length(dv.shape[1])
all dvs > t1 are positive
t2 - all dvs >= row_max - ... | Takes decision values and returns predictions, given thresholds
for the overall level and for distance to the row-wise maximum.
2d array of decision values
t1 - either a scalar threshold, or a vector of length(dv.shape[1])
all dvs > t1 are positive
t2 - all dvs >= row_max - t2 are positive
predictions (0-1) from thes... | [
"Takes",
"decision",
"values",
"and",
"returns",
"predictions",
"given",
"thresholds",
"for",
"the",
"overall",
"level",
"and",
"for",
"distance",
"to",
"the",
"row",
"-",
"wise",
"maximum",
".",
"2d",
"array",
"of",
"decision",
"values",
"t1",
"-",
"either"... | def repredict(dv, t1, t2):
pred = ((dv - t1) > 0).astype(float)
max_dv = dv.max(1)
for k in range(pred.shape[0]):
cut = max_dv[k] - t2
idx = (dv[k, :] >= cut)
pred[k, idx] = 1
return pred | [
"def",
"repredict",
"(",
"dv",
",",
"t1",
",",
"t2",
")",
":",
"pred",
"=",
"(",
"(",
"dv",
"-",
"t1",
")",
">",
"0",
")",
".",
"astype",
"(",
"float",
")",
"max_dv",
"=",
"dv",
".",
"max",
"(",
"1",
")",
"for",
"k",
"in",
"range",
"(",
"... | Takes decision values and returns predictions, given thresholds
for the overall level and for distance to the row-wise maximum. | [
"Takes",
"decision",
"values",
"and",
"returns",
"predictions",
"given",
"thresholds",
"for",
"the",
"overall",
"level",
"and",
"for",
"distance",
"to",
"the",
"row",
"-",
"wise",
"maximum",
"."
] | [
"\"\"\"\n Takes decision values and returns predictions, given thresholds \n for the overall level and for distance to the row-wise maximum.\n \n Params:\n dv - 2d array of decision values\n t1 - either a scalar threshold, or a vector of length(dv.shape[1])\n all dvs > t1 are positive\n t2 - al... | [
{
"param": "dv",
"type": null
},
{
"param": "t1",
"type": null
},
{
"param": "t2",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dv",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "t1",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
1fbd88d8dd15474144ab568f68496f2b2a846a9c | davidthaler/Greek_media | eval.py | [
"MIT"
] | Python | dvByLabel | <not_specific> | def dvByLabel(y, dv):
"""
Find the median decision values for the positive and negative instances
of each class.
This function is used for exploratory data analysis/model evaluation.
Params:
y - the 0-1 label matrix; a numpy array
dv - array of decision values returned from a model; a numpy array
... |
Find the median decision values for the positive and negative instances
of each class.
This function is used for exploratory data analysis/model evaluation.
Params:
y - the 0-1 label matrix; a numpy array
dv - array of decision values returned from a model; a numpy array
Returns:
a pandas dat... | Find the median decision values for the positive and negative instances
of each class.
This function is used for exploratory data analysis/model evaluation.
the 0-1 label matrix; a numpy array
dv - array of decision values returned from a model; a numpy array
a pandas data frame of size (# classes) x 3 with the media... | [
"Find",
"the",
"median",
"decision",
"values",
"for",
"the",
"positive",
"and",
"negative",
"instances",
"of",
"each",
"class",
".",
"This",
"function",
"is",
"used",
"for",
"exploratory",
"data",
"analysis",
"/",
"model",
"evaluation",
".",
"the",
"0",
"-",... | def dvByLabel(y, dv):
dv = as_float_array(dv)
result = np.zeros((y.shape[1],2))
for k in range(y.shape[1]):
result[k, 0] = np.median(dv[ y[:, k] == 0, k ])
result[k, 1] = np.median(dv[ y[:, k] == 1, k ])
result = pd.DataFrame(result)
result['tot'] = y.sum(0)
return result | [
"def",
"dvByLabel",
"(",
"y",
",",
"dv",
")",
":",
"dv",
"=",
"as_float_array",
"(",
"dv",
")",
"result",
"=",
"np",
".",
"zeros",
"(",
"(",
"y",
".",
"shape",
"[",
"1",
"]",
",",
"2",
")",
")",
"for",
"k",
"in",
"range",
"(",
"y",
".",
"sh... | Find the median decision values for the positive and negative instances
of each class. | [
"Find",
"the",
"median",
"decision",
"values",
"for",
"the",
"positive",
"and",
"negative",
"instances",
"of",
"each",
"class",
"."
] | [
"\"\"\"\n Find the median decision values for the positive and negative instances\n of each class.\n This function is used for exploratory data analysis/model evaluation.\n \n Params:\n y - the 0-1 label matrix; a numpy array\n dv - array of decision values returned from a model; a numpy array\n\n Retur... | [
{
"param": "y",
"type": null
},
{
"param": "dv",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "y",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dv",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
1fbd88d8dd15474144ab568f68496f2b2a846a9c | davidthaler/Greek_media | eval.py | [
"MIT"
] | Python | grid | <not_specific> | def grid(model, x, y, cvals, t1vals, t2vals, k=3):
"""
Performs grid search for hyperparameters used in the uniformOVA model.
NB: This was re-implemented (vs. using grid search from sklearn) because
sklearn grid search would try every (C, t1, t2) tuple, which would retrain
the SVC with the same C value t1 ... |
Performs grid search for hyperparameters used in the uniformOVA model.
NB: This was re-implemented (vs. using grid search from sklearn) because
sklearn grid search would try every (C, t1, t2) tuple, which would retrain
the SVC with the same C value t1 x t2 times. This trains the SVC once,
and then search... | Performs grid search for hyperparameters used in the uniformOVA model.
NB: This was re-implemented (vs. using grid search from sklearn) because
sklearn grid search would try every (C, t1, t2) tuple, which would retrain
the SVC with the same C value t1 x t2 times. This trains the SVC once,
and then searches over the (t1... | [
"Performs",
"grid",
"search",
"for",
"hyperparameters",
"used",
"in",
"the",
"uniformOVA",
"model",
".",
"NB",
":",
"This",
"was",
"re",
"-",
"implemented",
"(",
"vs",
".",
"using",
"grid",
"search",
"from",
"sklearn",
")",
"because",
"sklearn",
"grid",
"s... | def grid(model, x, y, cvals, t1vals, t2vals, k=3):
result = []
for c in cvals:
model.c = c
(pred, dv) = predictCV(model, x, y, k)
for t1val in t1vals:
for t2val in t2vals:
pred = models.repredict(dv, t1val, t2val)
score = f1_score(y, pred, average='samples')
result.append((... | [
"def",
"grid",
"(",
"model",
",",
"x",
",",
"y",
",",
"cvals",
",",
"t1vals",
",",
"t2vals",
",",
"k",
"=",
"3",
")",
":",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"cvals",
":",
"model",
".",
"c",
"=",
"c",
"(",
"pred",
",",
"dv",
")",
... | Performs grid search for hyperparameters used in the uniformOVA model. | [
"Performs",
"grid",
"search",
"for",
"hyperparameters",
"used",
"in",
"the",
"uniformOVA",
"model",
"."
] | [
"\"\"\"\n Performs grid search for hyperparameters used in the uniformOVA model.\n \n NB: This was re-implemented (vs. using grid search from sklearn) because\n sklearn grid search would try every (C, t1, t2) tuple, which would retrain\n the SVC with the same C value t1 x t2 times. This trains the SVC once, \n... | [
{
"param": "model",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "cvals",
"type": null
},
{
"param": "t1vals",
"type": null
},
{
"param": "t2vals",
"type": null
},
{
"param": "k",
"type": nu... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
1fbd88d8dd15474144ab568f68496f2b2a846a9c | davidthaler/Greek_media | eval.py | [
"MIT"
] | Python | predictCV | <not_specific> | def predictCV(model, x, y, k=3):
"""
Makes predictions over the training set using a cross-validation loop
such that the predictions for each instance are from the model trained
when that instance was held out.
Params:
model - The model used. Model state will be changed by training.
x - training f... |
Makes predictions over the training set using a cross-validation loop
such that the predictions for each instance are from the model trained
when that instance was held out.
Params:
model - The model used. Model state will be changed by training.
x - training features
y - training labels
k ... | Makes predictions over the training set using a cross-validation loop
such that the predictions for each instance are from the model trained
when that instance was held out.
The model used. Model state will be changed by training.
x - training features
y - training labels
k - # of CV folds
a 2-tuple
pred - a numpy ar... | [
"Makes",
"predictions",
"over",
"the",
"training",
"set",
"using",
"a",
"cross",
"-",
"validation",
"loop",
"such",
"that",
"the",
"predictions",
"for",
"each",
"instance",
"are",
"from",
"the",
"model",
"trained",
"when",
"that",
"instance",
"was",
"held",
... | def predictCV(model, x, y, k=3):
folds = KFold(y.shape[0], k)
pred = 0*y
dvs = 0*y
for train, val in folds:
model.fit(x[train], y[train])
dvs[val] = model.decision_function(x[val])
pred[val] = model.predict(x[val])
return (pred, dvs) | [
"def",
"predictCV",
"(",
"model",
",",
"x",
",",
"y",
",",
"k",
"=",
"3",
")",
":",
"folds",
"=",
"KFold",
"(",
"y",
".",
"shape",
"[",
"0",
"]",
",",
"k",
")",
"pred",
"=",
"0",
"*",
"y",
"dvs",
"=",
"0",
"*",
"y",
"for",
"train",
",",
... | Makes predictions over the training set using a cross-validation loop
such that the predictions for each instance are from the model trained
when that instance was held out. | [
"Makes",
"predictions",
"over",
"the",
"training",
"set",
"using",
"a",
"cross",
"-",
"validation",
"loop",
"such",
"that",
"the",
"predictions",
"for",
"each",
"instance",
"are",
"from",
"the",
"model",
"trained",
"when",
"that",
"instance",
"was",
"held",
... | [
"\"\"\"\n Makes predictions over the training set using a cross-validation loop\n such that the predictions for each instance are from the model trained \n when that instance was held out.\n \n Params:\n model - The model used. Model state will be changed by training.\n x - training features\n y - tra... | [
{
"param": "model",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "k",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
1fbd88d8dd15474144ab568f68496f2b2a846a9c | davidthaler/Greek_media | eval.py | [
"MIT"
] | Python | cvk | <not_specific> | def cvk(model, x, y, k=3):
"""
Computes mean F1-score for a provided model and training data.
Params:
model - the model to use in cross-validation
x - training features
y - training labels
k - number of cross-validation folds
Returns:
a numpy array of the mean F1-scores for each fold... |
Computes mean F1-score for a provided model and training data.
Params:
model - the model to use in cross-validation
x - training features
y - training labels
k - number of cross-validation folds
Returns:
a numpy array of the mean F1-scores for each fold
| Computes mean F1-score for a provided model and training data.
a numpy array of the mean F1-scores for each fold | [
"Computes",
"mean",
"F1",
"-",
"score",
"for",
"a",
"provided",
"model",
"and",
"training",
"data",
".",
"a",
"numpy",
"array",
"of",
"the",
"mean",
"F1",
"-",
"scores",
"for",
"each",
"fold"
] | def cvk(model, x, y, k=3):
return cvs(model, x, y, scoring=meanF1scorer, cv=k, n_jobs=3) | [
"def",
"cvk",
"(",
"model",
",",
"x",
",",
"y",
",",
"k",
"=",
"3",
")",
":",
"return",
"cvs",
"(",
"model",
",",
"x",
",",
"y",
",",
"scoring",
"=",
"meanF1scorer",
",",
"cv",
"=",
"k",
",",
"n_jobs",
"=",
"3",
")"
] | Computes mean F1-score for a provided model and training data. | [
"Computes",
"mean",
"F1",
"-",
"score",
"for",
"a",
"provided",
"model",
"and",
"training",
"data",
"."
] | [
"\"\"\"\n Computes mean F1-score for a provided model and training data.\n \n Params:\n model - the model to use in cross-validation\n x - training features\n y - training labels\n k - number of cross-validation folds\n \n Returns:\n a numpy array of the mean F1-scores for each fold\n \"\"\""... | [
{
"param": "model",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "k",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
1fbd88d8dd15474144ab568f68496f2b2a846a9c | davidthaler/Greek_media | eval.py | [
"MIT"
] | Python | meanF1array | <not_specific> | def meanF1array(y, pred):
"""
Function for computing mean F1-score given ground truth labels
and a same-sized numpy array of 0-1 predictions.
Params:
y - 0-1 array of ground truth labels
a numpy array of size (# instances) x (# classes)
pred - 0-1 array of predictions of same size as y
... |
Function for computing mean F1-score given ground truth labels
and a same-sized numpy array of 0-1 predictions.
Params:
y - 0-1 array of ground truth labels
a numpy array of size (# instances) x (# classes)
pred - 0-1 array of predictions of same size as y
Returns:
mean F1-score for... | Function for computing mean F1-score given ground truth labels
and a same-sized numpy array of 0-1 predictions.
0-1 array of ground truth labels
a numpy array of size (# instances) x (# classes)
pred - 0-1 array of predictions of same size as y
mean F1-score for the predictions, pred given the labels, y | [
"Function",
"for",
"computing",
"mean",
"F1",
"-",
"score",
"given",
"ground",
"truth",
"labels",
"and",
"a",
"same",
"-",
"sized",
"numpy",
"array",
"of",
"0",
"-",
"1",
"predictions",
".",
"0",
"-",
"1",
"array",
"of",
"ground",
"truth",
"labels",
"a... | def meanF1array(y, pred):
row_f1 = np.zeros((y.shape[0]))
for k in range(y.shape[0]):
tp = (pred[k] * y[k]).sum()
fp = (pred[k] > y[k]).sum()
fn = (pred[k] < y[k]).sum()
precision = tp/(tp + fp + 1e-9)
recall = tp/(tp + fn + 1e-9)
row_f1[k] = 2 * precision * recall / (precision + recall + 1e... | [
"def",
"meanF1array",
"(",
"y",
",",
"pred",
")",
":",
"row_f1",
"=",
"np",
".",
"zeros",
"(",
"(",
"y",
".",
"shape",
"[",
"0",
"]",
")",
")",
"for",
"k",
"in",
"range",
"(",
"y",
".",
"shape",
"[",
"0",
"]",
")",
":",
"tp",
"=",
"(",
"p... | Function for computing mean F1-score given ground truth labels
and a same-sized numpy array of 0-1 predictions. | [
"Function",
"for",
"computing",
"mean",
"F1",
"-",
"score",
"given",
"ground",
"truth",
"labels",
"and",
"a",
"same",
"-",
"sized",
"numpy",
"array",
"of",
"0",
"-",
"1",
"predictions",
"."
] | [
"\"\"\"\n Function for computing mean F1-score given ground truth labels\n and a same-sized numpy array of 0-1 predictions.\n \n Params:\n y - 0-1 array of ground truth labels\n a numpy array of size (# instances) x (# classes)\n pred - 0-1 array of predictions of same size as y\n \n Returns:\n... | [
{
"param": "y",
"type": null
},
{
"param": "pred",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "y",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pred",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
1fbd88d8dd15474144ab568f68496f2b2a846a9c | davidthaler/Greek_media | eval.py | [
"MIT"
] | Python | meanF1scorer | <not_specific> | def meanF1scorer(model, x, y):
"""
A scoring function for mean F1-score with the right signature
to use as the 'scoring' parameter in sklearn.metric.cross_val_score.
Params:
model - the model to use for prediction
x - features to use for prediction
y - ground truth labels for the examples in x
... |
A scoring function for mean F1-score with the right signature
to use as the 'scoring' parameter in sklearn.metric.cross_val_score.
Params:
model - the model to use for prediction
x - features to use for prediction
y - ground truth labels for the examples in x
a numpy 0-1 array of size (# ... | A scoring function for mean F1-score with the right signature
to use as the 'scoring' parameter in sklearn.metric.cross_val_score.
the model to use for prediction
x - features to use for prediction
y - ground truth labels for the examples in x
a numpy 0-1 array of size (# instances) x (# classes)
the mean F1-score fo... | [
"A",
"scoring",
"function",
"for",
"mean",
"F1",
"-",
"score",
"with",
"the",
"right",
"signature",
"to",
"use",
"as",
"the",
"'",
"scoring",
"'",
"parameter",
"in",
"sklearn",
".",
"metric",
".",
"cross_val_score",
".",
"the",
"model",
"to",
"use",
"for... | def meanF1scorer(model, x, y):
pred = model.predict(x)
return meanF1array(y, pred) | [
"def",
"meanF1scorer",
"(",
"model",
",",
"x",
",",
"y",
")",
":",
"pred",
"=",
"model",
".",
"predict",
"(",
"x",
")",
"return",
"meanF1array",
"(",
"y",
",",
"pred",
")"
] | A scoring function for mean F1-score with the right signature
to use as the 'scoring' parameter in sklearn.metric.cross_val_score. | [
"A",
"scoring",
"function",
"for",
"mean",
"F1",
"-",
"score",
"with",
"the",
"right",
"signature",
"to",
"use",
"as",
"the",
"'",
"scoring",
"'",
"parameter",
"in",
"sklearn",
".",
"metric",
".",
"cross_val_score",
"."
] | [
"\"\"\"\n A scoring function for mean F1-score with the right signature \n to use as the 'scoring' parameter in sklearn.metric.cross_val_score.\n \n Params:\n model - the model to use for prediction\n x - features to use for prediction\n y - ground truth labels for the examples in x\n a numpy 0-... | [
{
"param": "model",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
a0c2ef800308db317b57a4fd3301c5b4f3b66b54 | davidthaler/Greek_media | util.py | [
"MIT"
] | Python | rewrite_train | null | def rewrite_train():
"""
Rewrites train.libsvm into a gzipped, pickled sparse matrix for the features,
and a gzipped, pickled numpy (0-1) array for the labels.
Run this once.
Params: none
Returns:
nothing, but writes out the transformed input files at data/
"""
inpath = os.path.join(DATA, 'tr... |
Rewrites train.libsvm into a gzipped, pickled sparse matrix for the features,
and a gzipped, pickled numpy (0-1) array for the labels.
Run this once.
Params: none
Returns:
nothing, but writes out the transformed input files at data/
| Rewrites train.libsvm into a gzipped, pickled sparse matrix for the features,
and a gzipped, pickled numpy (0-1) array for the labels.
Run this once.
none | [
"Rewrites",
"train",
".",
"libsvm",
"into",
"a",
"gzipped",
"pickled",
"sparse",
"matrix",
"for",
"the",
"features",
"and",
"a",
"gzipped",
"pickled",
"numpy",
"(",
"0",
"-",
"1",
")",
"array",
"for",
"the",
"labels",
".",
"Run",
"this",
"once",
".",
"... | def rewrite_train():
inpath = os.path.join(DATA, 'train.libsvm')
(x, ylist) = load_svmlight_file(inpath,
n_features=NFEATURES,
multilabel=True,
zero_based=False)
with gzip.open(XTRAIN, 'wb') as fx:
cPickle... | [
"def",
"rewrite_train",
"(",
")",
":",
"inpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DATA",
",",
"'train.libsvm'",
")",
"(",
"x",
",",
"ylist",
")",
"=",
"load_svmlight_file",
"(",
"inpath",
",",
"n_features",
"=",
"NFEATURES",
",",
"multilabel",
... | Rewrites train.libsvm into a gzipped, pickled sparse matrix for the features,
and a gzipped, pickled numpy (0-1) array for the labels. | [
"Rewrites",
"train",
".",
"libsvm",
"into",
"a",
"gzipped",
"pickled",
"sparse",
"matrix",
"for",
"the",
"features",
"and",
"a",
"gzipped",
"pickled",
"numpy",
"(",
"0",
"-",
"1",
")",
"array",
"for",
"the",
"labels",
"."
] | [
"\"\"\"\n Rewrites train.libsvm into a gzipped, pickled sparse matrix for the features,\n and a gzipped, pickled numpy (0-1) array for the labels.\n Run this once.\n \n Params: none\n \n Returns: \n nothing, but writes out the transformed input files at data/\n \"\"\""
] | [] | {
"returns": [
{
"docstring": "nothing, but writes out the transformed input files at data",
"docstring_tokens": [
"nothing",
"but",
"writes",
"out",
"the",
"transformed",
"input",
"files",
"at",
"data"
],
"typ... |
a0c2ef800308db317b57a4fd3301c5b4f3b66b54 | davidthaler/Greek_media | util.py | [
"MIT"
] | Python | list2matrix | <not_specific> | def list2matrix(ylist):
"""
Rewrites a list-of-lists of labels for the multilabel case into a
0-1 label matrix. The matrix is a numpy array (dense data type),
but fairly sparse in practice.
Params:
ylist - a list of lists of integer labels for multilabel classification
Returns:
a 0-1 numpy arr... |
Rewrites a list-of-lists of labels for the multilabel case into a
0-1 label matrix. The matrix is a numpy array (dense data type),
but fairly sparse in practice.
Params:
ylist - a list of lists of integer labels for multilabel classification
Returns:
a 0-1 numpy array of size (# instances) x (#... | Rewrites a list-of-lists of labels for the multilabel case into a
0-1 label matrix. The matrix is a numpy array (dense data type),
but fairly sparse in practice.
a list of lists of integer labels for multilabel classification
a 0-1 numpy array of size (# instances) x (# classes) | [
"Rewrites",
"a",
"list",
"-",
"of",
"-",
"lists",
"of",
"labels",
"for",
"the",
"multilabel",
"case",
"into",
"a",
"0",
"-",
"1",
"label",
"matrix",
".",
"The",
"matrix",
"is",
"a",
"numpy",
"array",
"(",
"dense",
"data",
"type",
")",
"but",
"fairly"... | def list2matrix(ylist):
y = np.zeros((NROW_TRAIN, NLABELS))
for k in range(len(ylist)):
yl = ylist[k]
for l in yl:
y[k, l-1] = 1
return y | [
"def",
"list2matrix",
"(",
"ylist",
")",
":",
"y",
"=",
"np",
".",
"zeros",
"(",
"(",
"NROW_TRAIN",
",",
"NLABELS",
")",
")",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"ylist",
")",
")",
":",
"yl",
"=",
"ylist",
"[",
"k",
"]",
"for",
"l",
"... | Rewrites a list-of-lists of labels for the multilabel case into a
0-1 label matrix. | [
"Rewrites",
"a",
"list",
"-",
"of",
"-",
"lists",
"of",
"labels",
"for",
"the",
"multilabel",
"case",
"into",
"a",
"0",
"-",
"1",
"label",
"matrix",
"."
] | [
"\"\"\"\n Rewrites a list-of-lists of labels for the multilabel case into a\n 0-1 label matrix. The matrix is a numpy array (dense data type),\n but fairly sparse in practice.\n \n Params:\n ylist - a list of lists of integer labels for multilabel classification\n \n Returns:\n a 0-1 numpy array of siz... | [
{
"param": "ylist",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ylist",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a0c2ef800308db317b57a4fd3301c5b4f3b66b54 | davidthaler/Greek_media | util.py | [
"MIT"
] | Python | loadTrain | <not_specific> | def loadTrain():
"""
Function loads (uncompresses, unpickles) the training data and labels.
Params: none
Returns:
2-tuple of training set features and labels
"""
with gzip.open(XTRAIN) as fx:
x = cPickle.load(fx)
with gzip.open(YTRAIN) as fy:
y = cPickle.load(fy)
return (x, y) |
Function loads (uncompresses, unpickles) the training data and labels.
Params: none
Returns:
2-tuple of training set features and labels
| Function loads (uncompresses, unpickles) the training data and labels.
Params: none | [
"Function",
"loads",
"(",
"uncompresses",
"unpickles",
")",
"the",
"training",
"data",
"and",
"labels",
".",
"Params",
":",
"none"
] | def loadTrain():
with gzip.open(XTRAIN) as fx:
x = cPickle.load(fx)
with gzip.open(YTRAIN) as fy:
y = cPickle.load(fy)
return (x, y) | [
"def",
"loadTrain",
"(",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"XTRAIN",
")",
"as",
"fx",
":",
"x",
"=",
"cPickle",
".",
"load",
"(",
"fx",
")",
"with",
"gzip",
".",
"open",
"(",
"YTRAIN",
")",
"as",
"fy",
":",
"y",
"=",
"cPickle",
".",
... | Function loads (uncompresses, unpickles) the training data and labels. | [
"Function",
"loads",
"(",
"uncompresses",
"unpickles",
")",
"the",
"training",
"data",
"and",
"labels",
"."
] | [
"\"\"\"\n Function loads (uncompresses, unpickles) the training data and labels.\n \n Params: none\n \n Returns: \n 2-tuple of training set features and labels\n \"\"\""
] | [] | {
"returns": [
{
"docstring": "2-tuple of training set features and labels",
"docstring_tokens": [
"2",
"-",
"tuple",
"of",
"training",
"set",
"features",
"and",
"labels"
],
"type": null
}
],
"raises": [],
"p... |
a0c2ef800308db317b57a4fd3301c5b4f3b66b54 | davidthaler/Greek_media | util.py | [
"MIT"
] | Python | loadTest | <not_specific> | def loadTest():
"""
Function loads (uncompresses, unpickles) the test data.
Params: none
Returns:
the test features
"""
with gzip.open(XTEST) as f:
x = cPickle.load(f)
return x |
Function loads (uncompresses, unpickles) the test data.
Params: none
Returns:
the test features
| Function loads (uncompresses, unpickles) the test data.
Params: none | [
"Function",
"loads",
"(",
"uncompresses",
"unpickles",
")",
"the",
"test",
"data",
".",
"Params",
":",
"none"
] | def loadTest():
with gzip.open(XTEST) as f:
x = cPickle.load(f)
return x | [
"def",
"loadTest",
"(",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"XTEST",
")",
"as",
"f",
":",
"x",
"=",
"cPickle",
".",
"load",
"(",
"f",
")",
"return",
"x"
] | Function loads (uncompresses, unpickles) the test data. | [
"Function",
"loads",
"(",
"uncompresses",
"unpickles",
")",
"the",
"test",
"data",
"."
] | [
"\"\"\"\n Function loads (uncompresses, unpickles) the test data.\n \n Params: none\n \n Returns: \n the test features\n \"\"\""
] | [] | {
"returns": [
{
"docstring": "the test features",
"docstring_tokens": [
"the",
"test",
"features"
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
a0c2ef800308db317b57a4fd3301c5b4f3b66b54 | davidthaler/Greek_media | util.py | [
"MIT"
] | Python | writeSubmission | null | def writeSubmission(submit_num, pred):
"""
Writes out the predictions in the correct form for submission to Kaggle.
NB: This code is pretty slow (~ 15min).
Params:
submit_num - the submission is named submission<submit_num>.csv.gz
pred - a 0-1 numpy array of predictions of dimension
(# ... |
Writes out the predictions in the correct form for submission to Kaggle.
NB: This code is pretty slow (~ 15min).
Params:
submit_num - the submission is named submission<submit_num>.csv.gz
pred - a 0-1 numpy array of predictions of dimension
(# test instances) x (# classes)
Returns:
... | Writes out the predictions in the correct form for submission to Kaggle.
NB: This code is pretty slow (~ 15min).
the submission is named submission.csv.gz
pred - a 0-1 numpy array of predictions of dimension
(# test instances) x (# classes)
nothing, but writes submission file into submissions | [
"Writes",
"out",
"the",
"predictions",
"in",
"the",
"correct",
"form",
"for",
"submission",
"to",
"Kaggle",
".",
"NB",
":",
"This",
"code",
"is",
"pretty",
"slow",
"(",
"~",
"15min",
")",
".",
"the",
"submission",
"is",
"named",
"submission",
".",
"csv",... | def writeSubmission(submit_num, pred):
ss = pd.read_csv(SAMPLE)
for k in range(pred.shape[0]):
s = np.array_str(pred[k].nonzero()[0] + 1)
s = s[1:-1].strip()
s = re.sub(r"\W+", " ", s)
ss.Labels[k] = s
path = SUBMISSION_PATH % submit_num
with gzip.open(path, 'wb') as f:
ss.to_csv(f, index=Fa... | [
"def",
"writeSubmission",
"(",
"submit_num",
",",
"pred",
")",
":",
"ss",
"=",
"pd",
".",
"read_csv",
"(",
"SAMPLE",
")",
"for",
"k",
"in",
"range",
"(",
"pred",
".",
"shape",
"[",
"0",
"]",
")",
":",
"s",
"=",
"np",
".",
"array_str",
"(",
"pred"... | Writes out the predictions in the correct form for submission to Kaggle. | [
"Writes",
"out",
"the",
"predictions",
"in",
"the",
"correct",
"form",
"for",
"submission",
"to",
"Kaggle",
"."
] | [
"\"\"\"\n Writes out the predictions in the correct form for submission to Kaggle.\n\n NB: This code is pretty slow (~ 15min).\n \n Params:\n submit_num - the submission is named submission<submit_num>.csv.gz\n pred - a 0-1 numpy array of predictions of dimension \n (# test instances) x (# clas... | [
{
"param": "submit_num",
"type": null
},
{
"param": "pred",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "submit_num",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pred",
"type": null,
"docstring": null,
"docstring_toke... |
2cab382eb27add1bdf4ee51bcaf5c787ba98a136 | Juvawa/bib2web | bib2web/gscholar.py | [
"MIT"
] | Python | query | <not_specific> | def query(searchstr, outformat=FORMAT_BIBTEX, allresults=False):
"""Query google scholar.
This method queries google scholar and returns a list of citations.
Parameters
----------
searchstr : str
the query
outformat : int, optional
the output format of the citations. Default is... | Query google scholar.
This method queries google scholar and returns a list of citations.
Parameters
----------
searchstr : str
the query
outformat : int, optional
the output format of the citations. Default is bibtex.
allresults : bool, optional
return all results or o... | Query google scholar.
This method queries google scholar and returns a list of citations.
Parameters
searchstr : str
the query
outformat : int, optional
the output format of the citations. Default is bibtex.
allresults : bool, optional
return all results or only the first
Returns
result : list of strings
the list w... | [
"Query",
"google",
"scholar",
".",
"This",
"method",
"queries",
"google",
"scholar",
"and",
"returns",
"a",
"list",
"of",
"citations",
".",
"Parameters",
"searchstr",
":",
"str",
"the",
"query",
"outformat",
":",
"int",
"optional",
"the",
"output",
"format",
... | def query(searchstr, outformat=FORMAT_BIBTEX, allresults=False):
logging.debug("Query: {sstring}".format(sstring=searchstr))
searchstr = '/scholar?q='+quote(searchstr)
url = GOOGLE_SCHOLAR_URL + searchstr
return url | [
"def",
"query",
"(",
"searchstr",
",",
"outformat",
"=",
"FORMAT_BIBTEX",
",",
"allresults",
"=",
"False",
")",
":",
"logging",
".",
"debug",
"(",
"\"Query: {sstring}\"",
".",
"format",
"(",
"sstring",
"=",
"searchstr",
")",
")",
"searchstr",
"=",
"'/scholar... | Query google scholar. | [
"Query",
"google",
"scholar",
"."
] | [
"\"\"\"Query google scholar.\n\n This method queries google scholar and returns a list of citations.\n\n Parameters\n ----------\n searchstr : str\n the query\n outformat : int, optional\n the output format of the citations. Default is bibtex.\n allresults : bool, optional\n r... | [
{
"param": "searchstr",
"type": null
},
{
"param": "outformat",
"type": null
},
{
"param": "allresults",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "searchstr",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "outformat",
"type": null,
"docstring": null,
"docstring_... |
2cab382eb27add1bdf4ee51bcaf5c787ba98a136 | Juvawa/bib2web | bib2web/gscholar.py | [
"MIT"
] | Python | convert_pdf_to_txt | <not_specific> | def convert_pdf_to_txt(pdf):
"""Convert a pdf file to text and return the text.
This method requires pdftotext to be installed.
"""
stdout = subprocess.Popen(["pdftotext", "-q", pdf, "-"],
stdout=subprocess.PIPE).communicate()[0]
return stdout | Convert a pdf file to text and return the text.
This method requires pdftotext to be installed.
| Convert a pdf file to text and return the text.
This method requires pdftotext to be installed. | [
"Convert",
"a",
"pdf",
"file",
"to",
"text",
"and",
"return",
"the",
"text",
".",
"This",
"method",
"requires",
"pdftotext",
"to",
"be",
"installed",
"."
] | def convert_pdf_to_txt(pdf):
stdout = subprocess.Popen(["pdftotext", "-q", pdf, "-"],
stdout=subprocess.PIPE).communicate()[0]
return stdout | [
"def",
"convert_pdf_to_txt",
"(",
"pdf",
")",
":",
"stdout",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"pdftotext\"",
",",
"\"-q\"",
",",
"pdf",
",",
"\"-\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"["... | Convert a pdf file to text and return the text. | [
"Convert",
"a",
"pdf",
"file",
"to",
"text",
"and",
"return",
"the",
"text",
"."
] | [
"\"\"\"Convert a pdf file to text and return the text.\n\n This method requires pdftotext to be installed.\n \"\"\""
] | [
{
"param": "pdf",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pdf",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2cab382eb27add1bdf4ee51bcaf5c787ba98a136 | Juvawa/bib2web | bib2web/gscholar.py | [
"MIT"
] | Python | pdflookup | <not_specific> | def pdflookup(pdf, allresults, outformat):
"""Look a pdf up on google scholar and return bibtex items."""
txt = convert_pdf_to_txt(pdf)
# remove all non alphanumeric characters
txt = re.sub("\W", " ", txt)
words = txt.strip().split()[:20]
gsquery = " ".join(words)
bibtexlist = query(gsquery,... | Look a pdf up on google scholar and return bibtex items. | Look a pdf up on google scholar and return bibtex items. | [
"Look",
"a",
"pdf",
"up",
"on",
"google",
"scholar",
"and",
"return",
"bibtex",
"items",
"."
] | def pdflookup(pdf, allresults, outformat):
txt = convert_pdf_to_txt(pdf)
txt = re.sub("\W", " ", txt)
words = txt.strip().split()[:20]
gsquery = " ".join(words)
bibtexlist = query(gsquery, outformat, allresults)
return bibtexlist | [
"def",
"pdflookup",
"(",
"pdf",
",",
"allresults",
",",
"outformat",
")",
":",
"txt",
"=",
"convert_pdf_to_txt",
"(",
"pdf",
")",
"txt",
"=",
"re",
".",
"sub",
"(",
"\"\\W\"",
",",
"\" \"",
",",
"txt",
")",
"words",
"=",
"txt",
".",
"strip",
"(",
"... | Look a pdf up on google scholar and return bibtex items. | [
"Look",
"a",
"pdf",
"up",
"on",
"google",
"scholar",
"and",
"return",
"bibtex",
"items",
"."
] | [
"\"\"\"Look a pdf up on google scholar and return bibtex items.\"\"\"",
"# remove all non alphanumeric characters"
] | [
{
"param": "pdf",
"type": null
},
{
"param": "allresults",
"type": null
},
{
"param": "outformat",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pdf",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "allresults",
"type": null,
"docstring": null,
"docstring_token... |
2cab382eb27add1bdf4ee51bcaf5c787ba98a136 | Juvawa/bib2web | bib2web/gscholar.py | [
"MIT"
] | Python | _get_bib_element | <not_specific> | def _get_bib_element(bibitem, element):
"""Return element from bibitem or None."""
lst = [i.strip() for i in bibitem.split("\n")]
for i in lst:
if i.startswith(element):
value = i.split("=", 1)[-1]
value = value.strip()
while value.endswith(','):
v... | Return element from bibitem or None. | Return element from bibitem or None. | [
"Return",
"element",
"from",
"bibitem",
"or",
"None",
"."
] | def _get_bib_element(bibitem, element):
lst = [i.strip() for i in bibitem.split("\n")]
for i in lst:
if i.startswith(element):
value = i.split("=", 1)[-1]
value = value.strip()
while value.endswith(','):
value = value[:-1]
while value.start... | [
"def",
"_get_bib_element",
"(",
"bibitem",
",",
"element",
")",
":",
"lst",
"=",
"[",
"i",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"bibitem",
".",
"split",
"(",
"\"\\n\"",
")",
"]",
"for",
"i",
"in",
"lst",
":",
"if",
"i",
".",
"startswith",
"(... | Return element from bibitem or None. | [
"Return",
"element",
"from",
"bibitem",
"or",
"None",
"."
] | [
"\"\"\"Return element from bibitem or None.\"\"\""
] | [
{
"param": "bibitem",
"type": null
},
{
"param": "element",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "bibitem",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "element",
"type": null,
"docstring": null,
"docstring_toke... |
2cab382eb27add1bdf4ee51bcaf5c787ba98a136 | Juvawa/bib2web | bib2web/gscholar.py | [
"MIT"
] | Python | rename_file | null | def rename_file(pdf, bibitem):
"""Attempt to rename pdf according to bibitem."""
year = _get_bib_element(bibitem, "year")
author = _get_bib_element(bibitem, "author")
if author:
author = author.split(",")[0]
title = _get_bib_element(bibitem, "title")
l = []
for i in year, author, tit... | Attempt to rename pdf according to bibitem. | Attempt to rename pdf according to bibitem. | [
"Attempt",
"to",
"rename",
"pdf",
"according",
"to",
"bibitem",
"."
] | def rename_file(pdf, bibitem):
year = _get_bib_element(bibitem, "year")
author = _get_bib_element(bibitem, "author")
if author:
author = author.split(",")[0]
title = _get_bib_element(bibitem, "title")
l = []
for i in year, author, title:
if i:
l.append(i)
filename... | [
"def",
"rename_file",
"(",
"pdf",
",",
"bibitem",
")",
":",
"year",
"=",
"_get_bib_element",
"(",
"bibitem",
",",
"\"year\"",
")",
"author",
"=",
"_get_bib_element",
"(",
"bibitem",
",",
"\"author\"",
")",
"if",
"author",
":",
"author",
"=",
"author",
".",... | Attempt to rename pdf according to bibitem. | [
"Attempt",
"to",
"rename",
"pdf",
"according",
"to",
"bibitem",
"."
] | [
"\"\"\"Attempt to rename pdf according to bibitem.\"\"\""
] | [
{
"param": "pdf",
"type": null
},
{
"param": "bibitem",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pdf",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bibitem",
"type": null,
"docstring": null,
"docstring_tokens":... |
e3d2315110607b1ce57a2717b99f54e3b5d66890 | Juvawa/bib2web | bib2web/bibtexparser/tests/test_bparser.py | [
"MIT"
] | Python | customizations_latex | <not_specific> | def customizations_latex(record):
"""Use all functions related to specific fields
+ converter to latex.
:param record: a record
:returns: -- customized record
"""
record = homogeneize_latex_encoding(record)
record = type(record)
record = author(record)
record = editor(record)
r... | Use all functions related to specific fields
+ converter to latex.
:param record: a record
:returns: -- customized record
| Use all functions related to specific fields
+ converter to latex. | [
"Use",
"all",
"functions",
"related",
"to",
"specific",
"fields",
"+",
"converter",
"to",
"latex",
"."
] | def customizations_latex(record):
record = homogeneize_latex_encoding(record)
record = type(record)
record = author(record)
record = editor(record)
record = journal(record)
record = keyword(record)
record = link(record)
record = page_double_hyphen(record)
record = doi(record)
ret... | [
"def",
"customizations_latex",
"(",
"record",
")",
":",
"record",
"=",
"homogeneize_latex_encoding",
"(",
"record",
")",
"record",
"=",
"type",
"(",
"record",
")",
"record",
"=",
"author",
"(",
"record",
")",
"record",
"=",
"editor",
"(",
"record",
")",
"r... | Use all functions related to specific fields
+ converter to latex. | [
"Use",
"all",
"functions",
"related",
"to",
"specific",
"fields",
"+",
"converter",
"to",
"latex",
"."
] | [
"\"\"\"Use all functions related to specific fields\n + converter to latex.\n\n :param record: a record\n :returns: -- customized record\n \"\"\""
] | [
{
"param": "record",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "record",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | KL_prior | <not_specific> | def KL_prior(self):
"""
Prior of the filter model.
"""
return 0 |
Prior of the filter model.
| Prior of the filter model. | [
"Prior",
"of",
"the",
"filter",
"model",
"."
] | def KL_prior(self):
return 0 | [
"def",
"KL_prior",
"(",
"self",
")",
":",
"return",
"0"
] | Prior of the filter model. | [
"Prior",
"of",
"the",
"filter",
"model",
"."
] | [
"\"\"\"\n Prior of the filter model.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | mc_gen | <not_specific> | def mc_gen(self, q_mu, q_var, samples, neuron):
"""
Function for generating Gaussian MC samples. No MC samples are drawn when the variance is 0.
:param torch.tensor q_mu: the mean of the MC distribution
:param torch.tensor q_var: the (co)variance, type (univariate, multivariate)... |
Function for generating Gaussian MC samples. No MC samples are drawn when the variance is 0.
:param torch.tensor q_mu: the mean of the MC distribution
:param torch.tensor q_var: the (co)variance, type (univariate, multivariate) deduced
from tensor sh... | Function for generating Gaussian MC samples. No MC samples are drawn when the variance is 0. | [
"Function",
"for",
"generating",
"Gaussian",
"MC",
"samples",
".",
"No",
"MC",
"samples",
"are",
"drawn",
"when",
"the",
"variance",
"is",
"0",
"."
] | def mc_gen(self, q_mu, q_var, samples, neuron):
q_mu = q_mu[:, neuron, :]
if isinstance(q_var, Number):
h = q_mu[None, ...].expand(samples, *q_mu.shape).reshape(-1, *q_mu.shape[1:]) if samples > 1 else q_mu
elif len(q_var.shape) == 3:
q_var = q_var[:, neuron, :]
... | [
"def",
"mc_gen",
"(",
"self",
",",
"q_mu",
",",
"q_var",
",",
"samples",
",",
"neuron",
")",
":",
"q_mu",
"=",
"q_mu",
"[",
":",
",",
"neuron",
",",
":",
"]",
"if",
"isinstance",
"(",
"q_var",
",",
"Number",
")",
":",
"h",
"=",
"q_mu",
"[",
"No... | Function for generating Gaussian MC samples. | [
"Function",
"for",
"generating",
"Gaussian",
"MC",
"samples",
"."
] | [
"\"\"\"\n Function for generating Gaussian MC samples. No MC samples are drawn when the variance is 0.\n \n :param torch.tensor q_mu: the mean of the MC distribution\n :param torch.tensor q_var: the (co)variance, type (univariate, multivariate) deduced \n ... | [
{
"param": "self",
"type": null
},
{
"param": "q_mu",
"type": null
},
{
"param": "q_var",
"type": null
},
{
"param": "samples",
"type": null
},
{
"param": "neuron",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": "torch.tensor"
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | gh_gen | <not_specific> | def gh_gen(self, q_mu, q_var, points, neuron):
"""
Computes the Gauss-Hermite quadrature locations and weights.
:param torch.tensor q_mu: the mean of the MC distribution
:param torch.tensor q_var: the (co)variance, type (univariate, multivariate) deduced
... |
Computes the Gauss-Hermite quadrature locations and weights.
:param torch.tensor q_mu: the mean of the MC distribution
:param torch.tensor q_var: the (co)variance, type (univariate, multivariate) deduced
from tensor shape
:param int points: n... | Computes the Gauss-Hermite quadrature locations and weights. | [
"Computes",
"the",
"Gauss",
"-",
"Hermite",
"quadrature",
"locations",
"and",
"weights",
"."
] | def gh_gen(self, q_mu, q_var, points, neuron):
locs, ws = np.polynomial.hermite.hermgauss(points)
locs = torch.tensor(locs, dtype=self.tensor_type).repeat_interleave(q_mu.shape[0], 0).to(self.tbin.device)
ws = torch.tensor(1 / np.sqrt(np.pi) * ws / q_mu.shape[0],
dtyp... | [
"def",
"gh_gen",
"(",
"self",
",",
"q_mu",
",",
"q_var",
",",
"points",
",",
"neuron",
")",
":",
"locs",
",",
"ws",
"=",
"np",
".",
"polynomial",
".",
"hermite",
".",
"hermgauss",
"(",
"points",
")",
"locs",
"=",
"torch",
".",
"tensor",
"(",
"locs"... | Computes the Gauss-Hermite quadrature locations and weights. | [
"Computes",
"the",
"Gauss",
"-",
"Hermite",
"quadrature",
"locations",
"and",
"weights",
"."
] | [
"\"\"\"\n Computes the Gauss-Hermite quadrature locations and weights.\n \n :param torch.tensor q_mu: the mean of the MC distribution\n :param torch.tensor q_var: the (co)variance, type (univariate, multivariate) deduced \n from tensor shape\n :pa... | [
{
"param": "self",
"type": null
},
{
"param": "q_mu",
"type": null
},
{
"param": "q_var",
"type": null
},
{
"param": "points",
"type": null
},
{
"param": "neuron",
"type": null
}
] | {
"returns": [
{
"docstring": "tuple of locations and weights tensors",
"docstring_tokens": [
"tuple",
"of",
"locations",
"and",
"weights",
"tensors"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "self"... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | sample_XZ | <not_specific> | def sample_XZ(self, b, samples, net_input=None, entropy=False):
"""
Draw samples from the covariate distribution, provides an implementation of SVI.
In [1] we amortise the variational parameters with a recognition network. Note the input
to this network is the final output, i.e. all lat... |
Draw samples from the covariate distribution, provides an implementation of SVI.
In [1] we amortise the variational parameters with a recognition network. Note the input
to this network is the final output, i.e. all latents in each layer of a deep GP are mapped
from the final output l... | Draw samples from the covariate distribution, provides an implementation of SVI.
In [1] we amortise the variational parameters with a recognition network. Note the input
to this network is the final output, i.e. all latents in each layer of a deep GP are mapped
from the final output layer.
History in GLMs is incorpora... | [
"Draw",
"samples",
"from",
"the",
"covariate",
"distribution",
"provides",
"an",
"implementation",
"of",
"SVI",
".",
"In",
"[",
"1",
"]",
"we",
"amortise",
"the",
"variational",
"parameters",
"with",
"a",
"recognition",
"network",
".",
"Note",
"the",
"input",
... | def sample_XZ(self, b, samples, net_input=None, entropy=False):
if self.regressor_mode:
XZ, kl_stim = self._time_slice(self._XZ(self.XZ[b], samples))
dummy = torch.zeros(samples*self.trials).to(self.dummy.device)
return XZ, dummy, 0 if entropy else dummy, kl_stim
log... | [
"def",
"sample_XZ",
"(",
"self",
",",
"b",
",",
"samples",
",",
"net_input",
"=",
"None",
",",
"entropy",
"=",
"False",
")",
":",
"if",
"self",
".",
"regressor_mode",
":",
"XZ",
",",
"kl_stim",
"=",
"self",
".",
"_time_slice",
"(",
"self",
".",
"_XZ"... | Draw samples from the covariate distribution, provides an implementation of SVI. | [
"Draw",
"samples",
"from",
"the",
"covariate",
"distribution",
"provides",
"an",
"implementation",
"of",
"SVI",
"."
] | [
"\"\"\"\n Draw samples from the covariate distribution, provides an implementation of SVI.\n In [1] we amortise the variational parameters with a recognition network. Note the input \n to this network is the final output, i.e. all latents in each layer of a deep GP are mapped \n from the... | [
{
"param": "self",
"type": null
},
{
"param": "b",
"type": null
},
{
"param": "samples",
"type": null
},
{
"param": "net_input",
"type": null
},
{
"param": "entropy",
"type": null
}
] | {
"returns": [
{
"docstring": "covariates sample of shape (samples, timesteps, dims), log_prior",
"docstring_tokens": [
"covariates",
"sample",
"of",
"shape",
"(",
"samples",
"timesteps",
"dims",
")",
"log_prior"
],
... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | eval_XZ | <not_specific> | def eval_XZ(self, net_input=None):
"""
Evaluate the (latent) input variables. The latent variable structure is defined by the input
structure to the variational distributions specified.
:param torch.tensor net_input: the input to the VAE for fast inference of shape (time, momen... |
Evaluate the (latent) input variables. The latent variable structure is defined by the input
structure to the variational distributions specified.
:param torch.tensor net_input: the input to the VAE for fast inference of shape (time, moment)
:returns: a list with elements of s... | Evaluate the (latent) input variables. The latent variable structure is defined by the input
structure to the variational distributions specified. | [
"Evaluate",
"the",
"(",
"latent",
")",
"input",
"variables",
".",
"The",
"latent",
"variable",
"structure",
"is",
"defined",
"by",
"the",
"input",
"structure",
"to",
"the",
"variational",
"distributions",
"specified",
"."
] | def eval_XZ(self, net_input=None):
X_loc, X_std = [], []
if self.regressor_mode:
c = torch.cat(tuple(cov for cov in self.XZ), dim=1).permute(2, 1, 0)
X_loc = list(c.cpu().numpy())
X_std = list(np.zeros_like(c.cpu().numpy()))
else:
with torch.no_... | [
"def",
"eval_XZ",
"(",
"self",
",",
"net_input",
"=",
"None",
")",
":",
"X_loc",
",",
"X_std",
"=",
"[",
"]",
",",
"[",
"]",
"if",
"self",
".",
"regressor_mode",
":",
"c",
"=",
"torch",
".",
"cat",
"(",
"tuple",
"(",
"cov",
"for",
"cov",
"in",
... | Evaluate the (latent) input variables. | [
"Evaluate",
"the",
"(",
"latent",
")",
"input",
"variables",
"."
] | [
"\"\"\"\n Evaluate the (latent) input variables. The latent variable structure is defined by the input \n structure to the variational distributions specified.\n \n :param torch.tensor net_input: the input to the VAE for fast inference of shape (time, moment)\n :returns: a list wi... | [
{
"param": "self",
"type": null
},
{
"param": "net_input",
"type": null
}
] | {
"returns": [
{
"docstring": "a list with elements of shape (timesteps,) for input variables, if separate trial runs,\nwe get additional first list dimension over runs/trials",
"docstring_tokens": [
"a",
"list",
"with",
"elements",
"of",
"shape",
... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | compute_F | null | def compute_F(self, XZ):
"""
Computes the posterior over :mathm:`F`, conditioned on the data. In most cases, this is amortized via
learned weights/parameters of some approximate posterior. In ML/MAP settings the approximation is a
delta distribution, meaning there is no variational unc... |
Computes the posterior over :mathm:`F`, conditioned on the data. In most cases, this is amortized via
learned weights/parameters of some approximate posterior. In ML/MAP settings the approximation is a
delta distribution, meaning there is no variational uncertainty in the mapping.
| Computes the posterior over :mathm:`F`, conditioned on the data. In most cases, this is amortized via
learned weights/parameters of some approximate posterior. In ML/MAP settings the approximation is a
delta distribution, meaning there is no variational uncertainty in the mapping. | [
"Computes",
"the",
"posterior",
"over",
":",
"mathm",
":",
"`",
"F",
"`",
"conditioned",
"on",
"the",
"data",
".",
"In",
"most",
"cases",
"this",
"is",
"amortized",
"via",
"learned",
"weights",
"/",
"parameters",
"of",
"some",
"approximate",
"posterior",
"... | def compute_F(self, XZ):
raise NotImplementedError | [
"def",
"compute_F",
"(",
"self",
",",
"XZ",
")",
":",
"raise",
"NotImplementedError"
] | Computes the posterior over :mathm:`F`, conditioned on the data. | [
"Computes",
"the",
"posterior",
"over",
":",
"mathm",
":",
"`",
"F",
"`",
"conditioned",
"on",
"the",
"data",
"."
] | [
"\"\"\"\n Computes the posterior over :mathm:`F`, conditioned on the data. In most cases, this is amortized via \n learned weights/parameters of some approximate posterior. In ML/MAP settings the approximation is a \n delta distribution, meaning there is no variational uncertainty in the mappin... | [
{
"param": "self",
"type": null
},
{
"param": "XZ",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "XZ",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | to_XZ | <not_specific> | def to_XZ(self, covariates, trials=1):
"""
Convert covariates list input to tensors for input to mapping. Convenience function for rate
evaluation functions and sampling functions.
"""
cov_list = []
timesteps = None
for cov_ in covariates:
if len(cov_... |
Convert covariates list input to tensors for input to mapping. Convenience function for rate
evaluation functions and sampling functions.
| Convert covariates list input to tensors for input to mapping. Convenience function for rate
evaluation functions and sampling functions. | [
"Convert",
"covariates",
"list",
"input",
"to",
"tensors",
"for",
"input",
"to",
"mapping",
".",
"Convenience",
"function",
"for",
"rate",
"evaluation",
"functions",
"and",
"sampling",
"functions",
"."
] | def to_XZ(self, covariates, trials=1):
cov_list = []
timesteps = None
for cov_ in covariates:
if len(cov_.shape) == 1:
cov_ = cov_[None, :, None]
elif len(cov_.shape) == 2:
cov_ = cov_[None, ...]
if len(cov_.shape) != 3:
... | [
"def",
"to_XZ",
"(",
"self",
",",
"covariates",
",",
"trials",
"=",
"1",
")",
":",
"cov_list",
"=",
"[",
"]",
"timesteps",
"=",
"None",
"for",
"cov_",
"in",
"covariates",
":",
"if",
"len",
"(",
"cov_",
".",
"shape",
")",
"==",
"1",
":",
"cov_",
"... | Convert covariates list input to tensors for input to mapping. | [
"Convert",
"covariates",
"list",
"input",
"to",
"tensors",
"for",
"input",
"to",
"mapping",
"."
] | [
"\"\"\"\n Convert covariates list input to tensors for input to mapping. Convenience function for rate \n evaluation functions and sampling functions.\n \"\"\"",
"# expand arrays from (timesteps,)",
"# expand arrays (timesteps, dims)"
] | [
{
"param": "self",
"type": null
},
{
"param": "covariates",
"type": null
},
{
"param": "trials",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "covariates",
"type": null,
"docstring": null,
"docstring_toke... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | _samples | <not_specific> | def _samples(self, covariates, neuron, n_samp, full_cov, trials):
"""
Evaluates samples from the variational posterior for the rate.
:param bool full_cov: flag if True allows to draw function samples, False allows faster uncertainty
"""
XZ = self.to_XZ(covariates, trials... |
Evaluates samples from the variational posterior for the rate.
:param bool full_cov: flag if True allows to draw function samples, False allows faster uncertainty
| Evaluates samples from the variational posterior for the rate. | [
"Evaluates",
"samples",
"from",
"the",
"variational",
"posterior",
"for",
"the",
"rate",
"."
] | def _samples(self, covariates, neuron, n_samp, full_cov, trials):
XZ = self.to_XZ(covariates, trials)
with torch.no_grad():
mean, var = self.compute_F(XZ)
if isinstance(var, Number):
samples = self.f(mean)
else:
mean, var = mean[:, n... | [
"def",
"_samples",
"(",
"self",
",",
"covariates",
",",
"neuron",
",",
"n_samp",
",",
"full_cov",
",",
"trials",
")",
":",
"XZ",
"=",
"self",
".",
"to_XZ",
"(",
"covariates",
",",
"trials",
")",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"mean",... | Evaluates samples from the variational posterior for the rate. | [
"Evaluates",
"samples",
"from",
"the",
"variational",
"posterior",
"for",
"the",
"rate",
"."
] | [
"\"\"\"\n Evaluates samples from the variational posterior for the rate.\n \n :param bool full_cov: flag if True allows to draw function samples, False allows faster uncertainty\n \"\"\"",
"# samples, timesteps, dims",
"# compute predictive mean and variance",
"# deterministic mapp... | [
{
"param": "self",
"type": null
},
{
"param": "covariates",
"type": null
},
{
"param": "neuron",
"type": null
},
{
"param": "n_samp",
"type": null
},
{
"param": "full_cov",
"type": null
},
{
"param": "trials",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "covariates",
"type": null,
"docstring": null,
"docstring_toke... |
3dfb3931ebd7d6488d3b23cf9381457131b46b93 | davindicode/universal_count_model | neuroprob/base.py | [
"MIT"
] | Python | eval_rate | <not_specific> | def eval_rate(self, covariates, neuron, mode='mean', percentiles=[0.05, 0.95], n_samp=1000, trials=1):
"""
Evaluate the rate of the model as function of input covariates.
:param np.array covariates: input covariates to evaluate rate over with shape (dims, timesteps)
:param list ... |
Evaluate the rate of the model as function of input covariates.
:param np.array covariates: input covariates to evaluate rate over with shape (dims, timesteps)
:param list neuron: neuron indices over which to evaluate rate
:param string mode: what to evaluate, `mean` gives post... | Evaluate the rate of the model as function of input covariates. | [
"Evaluate",
"the",
"rate",
"of",
"the",
"model",
"as",
"function",
"of",
"input",
"covariates",
"."
] | def eval_rate(self, covariates, neuron, mode='mean', percentiles=[0.05, 0.95], n_samp=1000, trials=1):
if np.max(neuron) >= self.out_dims:
raise ValueError('Accessing output dimensions beyond specified dimensions by model')
if ((mode == 'mean') or (mode == 'posterior') or (mode == 'tuning')... | [
"def",
"eval_rate",
"(",
"self",
",",
"covariates",
",",
"neuron",
",",
"mode",
"=",
"'mean'",
",",
"percentiles",
"=",
"[",
"0.05",
",",
"0.95",
"]",
",",
"n_samp",
"=",
"1000",
",",
"trials",
"=",
"1",
")",
":",
"if",
"np",
".",
"max",
"(",
"ne... | Evaluate the rate of the model as function of input covariates. | [
"Evaluate",
"the",
"rate",
"of",
"the",
"model",
"as",
"function",
"of",
"input",
"covariates",
"."
] | [
"\"\"\"\n Evaluate the rate of the model as function of input covariates.\n \n :param np.array covariates: input covariates to evaluate rate over with shape (dims, timesteps)\n :param list neuron: neuron indices over which to evaluate rate\n :param string mode: what to evaluate, `... | [
{
"param": "self",
"type": null
},
{
"param": "covariates",
"type": null
},
{
"param": "neuron",
"type": null
},
{
"param": "mode",
"type": null
},
{
"param": "percentiles",
"type": null
},
{
"param": "n_samp",
"type": null
},
{
"param": "t... | {
"returns": [
{
"docstring": "output rate to [neurons, steps] or [steps] depending on neuron array or scalar",
"docstring_tokens": [
"output",
"rate",
"to",
"[",
"neurons",
"steps",
"]",
"or",
"[",
"steps",
"]",
... |
b384701fa37381ca6db8cbebe8b74d92412cfba7 | davindicode/universal_count_model | neuroprob/utils/pytorch.py | [
"MIT"
] | Python | compute_nat_grads | null | def compute_nat_grads(param_pairs):
"""
Compute the natural gradients and replace the .grad of the relevant parameters. [1]
Note compared to the Newton method, the gradient here is computed in parallel for each output dimension
while the Newton method uses the exact Hessian involving cross-terms.
R... |
Compute the natural gradients and replace the .grad of the relevant parameters. [1]
Note compared to the Newton method, the gradient here is computed in parallel for each output dimension
while the Newton method uses the exact Hessian involving cross-terms.
References:
[1] `Natural Gradients in P... | Compute the natural gradients and replace the .grad of the relevant parameters. [1]
Note compared to the Newton method, the gradient here is computed in parallel for each output dimension
while the Newton method uses the exact Hessian involving cross-terms.
[1] `Natural Gradients in Practice: Non-Conjugate Variation... | [
"Compute",
"the",
"natural",
"gradients",
"and",
"replace",
"the",
".",
"grad",
"of",
"the",
"relevant",
"parameters",
".",
"[",
"1",
"]",
"Note",
"compared",
"to",
"the",
"Newton",
"method",
"the",
"gradient",
"here",
"is",
"computed",
"in",
"parallel",
"... | def compute_nat_grads(param_pairs):
for k in range(len(param_pairs) // 2):
m = param_pairs[2*k]
L = param_pairs[2*k+1]
grad_m = m.grad
grad_L = torch.tril(L.grad) x M
M = L.shape[-1]
N = L.shape[0]
A = (L.permute(0, 2, 1) @ grad_L)
A.view(N, -1)[:, :... | [
"def",
"compute_nat_grads",
"(",
"param_pairs",
")",
":",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"param_pairs",
")",
"//",
"2",
")",
":",
"m",
"=",
"param_pairs",
"[",
"2",
"*",
"k",
"]",
"L",
"=",
"param_pairs",
"[",
"2",
"*",
"k",
"+",
"1"... | Compute the natural gradients and replace the .grad of the relevant parameters. | [
"Compute",
"the",
"natural",
"gradients",
"and",
"replace",
"the",
".",
"grad",
"of",
"the",
"relevant",
"parameters",
"."
] | [
"\"\"\"\n Compute the natural gradients and replace the .grad of the relevant parameters. [1]\n Note compared to the Newton method, the gradient here is computed in parallel for each output dimension\n while the Newton method uses the exact Hessian involving cross-terms.\n\n References:\n\n [1] `Natu... | [
{
"param": "param_pairs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "param_pairs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b384701fa37381ca6db8cbebe8b74d92412cfba7 | davindicode/universal_count_model | neuroprob/utils/pytorch.py | [
"MIT"
] | Python | compute_newton_grads | null | def compute_newton_grads(params, loss, mode='inverse'):
"""
Newton's method for optimization.
Compute the inverse Hessian gradient product (jvp) to replace the gradients for a chosen
subset of second-order optimized parameters.
"""
#grad_p = torch.cat([p.grad.flatten() for p in self.newton_grad... |
Newton's method for optimization.
Compute the inverse Hessian gradient product (jvp) to replace the gradients for a chosen
subset of second-order optimized parameters.
| Newton's method for optimization.
Compute the inverse Hessian gradient product (jvp) to replace the gradients for a chosen
subset of second-order optimized parameters. | [
"Newton",
"'",
"s",
"method",
"for",
"optimization",
".",
"Compute",
"the",
"inverse",
"Hessian",
"gradient",
"product",
"(",
"jvp",
")",
"to",
"replace",
"the",
"gradients",
"for",
"a",
"chosen",
"subset",
"of",
"second",
"-",
"order",
"optimized",
"paramet... | def compute_newton_grads(params, loss, mode='inverse'):
grad_p = torch.cat([torch.autograd.grad(loss, p, retain_graph=True, create_graph=True)[0].flatten()
for p in params])
v = torch.ones(len(grad_p), device=grad_p.device, requires_grad=True)
a = torch.dot(grad_p, v)
Hv = torch... | [
"def",
"compute_newton_grads",
"(",
"params",
",",
"loss",
",",
"mode",
"=",
"'inverse'",
")",
":",
"grad_p",
"=",
"torch",
".",
"cat",
"(",
"[",
"torch",
".",
"autograd",
".",
"grad",
"(",
"loss",
",",
"p",
",",
"retain_graph",
"=",
"True",
",",
"cr... | Newton's method for optimization. | [
"Newton",
"'",
"s",
"method",
"for",
"optimization",
"."
] | [
"\"\"\"\n Newton's method for optimization.\n Compute the inverse Hessian gradient product (jvp) to replace the gradients for a chosen \n subset of second-order optimized parameters.\n \"\"\"",
"#grad_p = torch.cat([p.grad.flatten() for p in self.newton_grad])",
"# compute Hessian vector product",
... | [
{
"param": "params",
"type": null
},
{
"param": "loss",
"type": null
},
{
"param": "mode",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "params",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "loss",
"type": null,
"docstring": null,
"docstring_tokens":... |
b384701fa37381ca6db8cbebe8b74d92412cfba7 | davindicode/universal_count_model | neuroprob/utils/pytorch.py | [
"MIT"
] | Python | step | <not_specific> | def step(self, closure, b=None, M_inv=None):
"""
Performs a single optimization step.
Arguments:
closure (callable): A closure that re-evaluates the model
and returns a tuple of the loss and the output.
b (callable, optional): A closure that calculates the... |
Performs a single optimization step.
Arguments:
closure (callable): A closure that re-evaluates the model
and returns a tuple of the loss and the output.
b (callable, optional): A closure that calculates the vector b in
the minimization problem x^... | Performs a single optimization step. | [
"Performs",
"a",
"single",
"optimization",
"step",
"."
] | def step(self, closure, b=None, M_inv=None):
assert len(self.param_groups) == 1
group = self.param_groups[0]
alpha = group['alpha']
delta_decay = group['delta_decay']
cg_max_iter = group['cg_max_iter']
damping = group['damping']
use_gnm = group['use_gnm']
... | [
"def",
"step",
"(",
"self",
",",
"closure",
",",
"b",
"=",
"None",
",",
"M_inv",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"self",
".",
"param_groups",
")",
"==",
"1",
"group",
"=",
"self",
".",
"param_groups",
"[",
"0",
"]",
"alpha",
"=",
"gr... | Performs a single optimization step. | [
"Performs",
"a",
"single",
"optimization",
"step",
"."
] | [
"\"\"\"\n Performs a single optimization step.\n Arguments:\n closure (callable): A closure that re-evaluates the model\n and returns a tuple of the loss and the output.\n b (callable, optional): A closure that calculates the vector b in\n the minimi... | [
{
"param": "self",
"type": null
},
{
"param": "closure",
"type": null
},
{
"param": "b",
"type": null
},
{
"param": "M_inv",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "closure",
"type": null,
"docstring": "A closure that re-evaluates t... |
b384701fa37381ca6db8cbebe8b74d92412cfba7 | davindicode/universal_count_model | neuroprob/utils/pytorch.py | [
"MIT"
] | Python | _Hv | <not_specific> | def _Hv(self, gradient, vec, damping):
"""
Computes the Hessian vector product.
"""
Hv = self._Rop(gradient, self._params, vec)
# Tikhonov damping (Section 20.8.1)
return Hv.detach() + damping * vec |
Computes the Hessian vector product.
| Computes the Hessian vector product. | [
"Computes",
"the",
"Hessian",
"vector",
"product",
"."
] | def _Hv(self, gradient, vec, damping):
Hv = self._Rop(gradient, self._params, vec)
return Hv.detach() + damping * vec | [
"def",
"_Hv",
"(",
"self",
",",
"gradient",
",",
"vec",
",",
"damping",
")",
":",
"Hv",
"=",
"self",
".",
"_Rop",
"(",
"gradient",
",",
"self",
".",
"_params",
",",
"vec",
")",
"return",
"Hv",
".",
"detach",
"(",
")",
"+",
"damping",
"*",
"vec"
] | Computes the Hessian vector product. | [
"Computes",
"the",
"Hessian",
"vector",
"product",
"."
] | [
"\"\"\"\n Computes the Hessian vector product.\n \"\"\"",
"# Tikhonov damping (Section 20.8.1)"
] | [
{
"param": "self",
"type": null
},
{
"param": "gradient",
"type": null
},
{
"param": "vec",
"type": null
},
{
"param": "damping",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "gradient",
"type": null,
"docstring": null,
"docstring_tokens... |
b384701fa37381ca6db8cbebe8b74d92412cfba7 | davindicode/universal_count_model | neuroprob/utils/pytorch.py | [
"MIT"
] | Python | _Gv | <not_specific> | def _Gv(self, loss, output, vec, damping):
"""
Computes the generalized Gauss-Newton vector product.
"""
Jv = self._Rop(output, self._params, vec)
gradient = torch.autograd.grad(loss, output, create_graph=True)
HJv = self._Rop(gradient, output, Jv)
JHJv = torch.... |
Computes the generalized Gauss-Newton vector product.
| Computes the generalized Gauss-Newton vector product. | [
"Computes",
"the",
"generalized",
"Gauss",
"-",
"Newton",
"vector",
"product",
"."
] | def _Gv(self, loss, output, vec, damping):
Jv = self._Rop(output, self._params, vec)
gradient = torch.autograd.grad(loss, output, create_graph=True)
HJv = self._Rop(gradient, output, Jv)
JHJv = torch.autograd.grad(
output, self._params, grad_outputs=HJv.reshape_as(output), re... | [
"def",
"_Gv",
"(",
"self",
",",
"loss",
",",
"output",
",",
"vec",
",",
"damping",
")",
":",
"Jv",
"=",
"self",
".",
"_Rop",
"(",
"output",
",",
"self",
".",
"_params",
",",
"vec",
")",
"gradient",
"=",
"torch",
".",
"autograd",
".",
"grad",
"(",... | Computes the generalized Gauss-Newton vector product. | [
"Computes",
"the",
"generalized",
"Gauss",
"-",
"Newton",
"vector",
"product",
"."
] | [
"\"\"\"\n Computes the generalized Gauss-Newton vector product.\n \"\"\"",
"# Tikhonov damping (Section 20.8.1)"
] | [
{
"param": "self",
"type": null
},
{
"param": "loss",
"type": null
},
{
"param": "output",
"type": null
},
{
"param": "vec",
"type": null
},
{
"param": "damping",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "loss",
"type": null,
"docstring": null,
"docstring_tokens": [... |
b384701fa37381ca6db8cbebe8b74d92412cfba7 | davindicode/universal_count_model | neuroprob/utils/pytorch.py | [
"MIT"
] | Python | step | <not_specific> | def step(self, closure=None):
""" Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for... | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
| Performs a single optimization step. | [
"Performs",
"a",
"single",
"optimization",
"step",
"."
] | def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
weight_decay = group['weight_decay']
large_lr = (group['lr']*group['kappa'])/(group['smallConst'])
Alpha = 1.0 - ((group['smallConst'... | [
"def",
"step",
"(",
"self",
",",
"closure",
"=",
"None",
")",
":",
"loss",
"=",
"None",
"if",
"closure",
"is",
"not",
"None",
":",
"loss",
"=",
"closure",
"(",
")",
"for",
"group",
"in",
"self",
".",
"param_groups",
":",
"weight_decay",
"=",
"group",... | Performs a single optimization step. | [
"Performs",
"a",
"single",
"optimization",
"step",
"."
] | [
"\"\"\" Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "closure",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "closure",
"type": null,
"docstring": "A closure that reevaluates th... |
9a1a5cf0b01b6605724122d2bd564f1c4aa373f5 | davindicode/universal_count_model | neuroprob/utils/signal.py | [
"MIT"
] | Python | lagged_input | <not_specific> | def lagged_input(input, hist_len, hist_stride=1, time_stride=1, tensor_type=torch.float):
"""
Introduce lagged history input from time series.
:param torch.tensor input: input of shape (dimensions, timesteps)
:param int hist_len:
:param int hist_stride:
:param int time_stride:
:param... |
Introduce lagged history input from time series.
:param torch.tensor input: input of shape (dimensions, timesteps)
:param int hist_len:
:param int hist_stride:
:param int time_stride:
:param dtype tensor_type:
:returns: lagged input tensor of shape (dimensions, time-H+1, history)
... | Introduce lagged history input from time series. | [
"Introduce",
"lagged",
"history",
"input",
"from",
"time",
"series",
"."
] | def lagged_input(input, hist_len, hist_stride=1, time_stride=1, tensor_type=torch.float):
in_unfold = input.unfold(-1, hist_len, time_stride)[:, :, ::hist_stride]
return in_unfold | [
"def",
"lagged_input",
"(",
"input",
",",
"hist_len",
",",
"hist_stride",
"=",
"1",
",",
"time_stride",
"=",
"1",
",",
"tensor_type",
"=",
"torch",
".",
"float",
")",
":",
"in_unfold",
"=",
"input",
".",
"unfold",
"(",
"-",
"1",
",",
"hist_len",
",",
... | Introduce lagged history input from time series. | [
"Introduce",
"lagged",
"history",
"input",
"from",
"time",
"series",
"."
] | [
"\"\"\"\n Introduce lagged history input from time series.\n \n :param torch.tensor input: input of shape (dimensions, timesteps)\n :param int hist_len: \n :param int hist_stride: \n :param int time_stride: \n :param dtype tensor_type:\n :returns: lagged input tensor of shape (dimensions, ti... | [
{
"param": "input",
"type": null
},
{
"param": "hist_len",
"type": null
},
{
"param": "hist_stride",
"type": null
},
{
"param": "time_stride",
"type": null
},
{
"param": "tensor_type",
"type": null
}
] | {
"returns": [
{
"docstring": "lagged input tensor of shape (dimensions, time-H+1, history)",
"docstring_tokens": [
"lagged",
"input",
"tensor",
"of",
"shape",
"(",
"dimensions",
"time",
"-",
"H",
"+",
"1",... |
9a1a5cf0b01b6605724122d2bd564f1c4aa373f5 | davindicode/universal_count_model | neuroprob/utils/signal.py | [
"MIT"
] | Python | ConsecutiveArrays | <not_specific> | def ConsecutiveArrays(arr, step=1):
"""
Finds consecutive subarrays satisfying monotonic stepping with step in array.
Returns on each array element the island index (starting from 1).
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: f... |
Finds consecutive subarrays satisfying monotonic stepping with step in array.
Returns on each array element the island index (starting from 1).
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
| Finds consecutive subarrays satisfying monotonic stepping with step in array.
Returns on each array element the island index (starting from 1). | [
"Finds",
"consecutive",
"subarrays",
"satisfying",
"monotonic",
"stepping",
"with",
"step",
"in",
"array",
".",
"Returns",
"on",
"each",
"array",
"element",
"the",
"island",
"index",
"(",
"starting",
"from",
"1",
")",
"."
] | def ConsecutiveArrays(arr, step=1):
islands = 1
island_ind = np.zeros(arr.shape)
on_isl = False
for k in range(1, arr.shape[0]):
if arr[k] == arr[k-1] + step:
if on_isl is False:
island_ind[k-1] = islands
on_isl = True
island_ind[k] = isla... | [
"def",
"ConsecutiveArrays",
"(",
"arr",
",",
"step",
"=",
"1",
")",
":",
"islands",
"=",
"1",
"island_ind",
"=",
"np",
".",
"zeros",
"(",
"arr",
".",
"shape",
")",
"on_isl",
"=",
"False",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"arr",
".",
"sha... | Finds consecutive subarrays satisfying monotonic stepping with step in array. | [
"Finds",
"consecutive",
"subarrays",
"satisfying",
"monotonic",
"stepping",
"with",
"step",
"in",
"array",
"."
] | [
"\"\"\"\n Finds consecutive subarrays satisfying monotonic stepping with step in array.\n Returns on each array element the island index (starting from 1).\n \n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n :returns: figure and axis\n :rtype... | [
{
"param": "arr",
"type": null
},
{
"param": "step",
"type": null
}
] | {
"returns": [
{
"docstring": "figure and axis",
"docstring_tokens": [
"figure",
"and",
"axis"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "arr",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9a1a5cf0b01b6605724122d2bd564f1c4aa373f5 | davindicode/universal_count_model | neuroprob/utils/signal.py | [
"MIT"
] | Python | resultant_length | <not_specific> | def resultant_length(x, y):
"""
Returns the mean resultant length R of the residual distribution
"""
return torch.sqrt(torch.mean(torch.cos(x-y))**2 + torch.mean(torch.sin(x-y))**2) |
Returns the mean resultant length R of the residual distribution
| Returns the mean resultant length R of the residual distribution | [
"Returns",
"the",
"mean",
"resultant",
"length",
"R",
"of",
"the",
"residual",
"distribution"
] | def resultant_length(x, y):
return torch.sqrt(torch.mean(torch.cos(x-y))**2 + torch.mean(torch.sin(x-y))**2) | [
"def",
"resultant_length",
"(",
"x",
",",
"y",
")",
":",
"return",
"torch",
".",
"sqrt",
"(",
"torch",
".",
"mean",
"(",
"torch",
".",
"cos",
"(",
"x",
"-",
"y",
")",
")",
"**",
"2",
"+",
"torch",
".",
"mean",
"(",
"torch",
".",
"sin",
"(",
"... | Returns the mean resultant length R of the residual distribution | [
"Returns",
"the",
"mean",
"resultant",
"length",
"R",
"of",
"the",
"residual",
"distribution"
] | [
"\"\"\"\n Returns the mean resultant length R of the residual distribution\n \"\"\""
] | [
{
"param": "x",
"type": null
},
{
"param": "y",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9a1a5cf0b01b6605724122d2bd564f1c4aa373f5 | davindicode/universal_count_model | neuroprob/utils/signal.py | [
"MIT"
] | Python | filter_signal | <not_specific> | def filter_signal(signal, f_min, f_max, sample_bin):
"""
Filter in Fourier space by multiplying with a box function for (f_min, f_max).
"""
track_samples = signal.shape[0]
Df = 1/sample_bin/track_samples
low_ind = np.floor(f_min/Df).astype(int)
high_ind = np.ceil(f_max/Df).astype(int)
g... |
Filter in Fourier space by multiplying with a box function for (f_min, f_max).
| Filter in Fourier space by multiplying with a box function for (f_min, f_max). | [
"Filter",
"in",
"Fourier",
"space",
"by",
"multiplying",
"with",
"a",
"box",
"function",
"for",
"(",
"f_min",
"f_max",
")",
"."
] | def filter_signal(signal, f_min, f_max, sample_bin):
track_samples = signal.shape[0]
Df = 1/sample_bin/track_samples
low_ind = np.floor(f_min/Df).astype(int)
high_ind = np.ceil(f_max/Df).astype(int)
g_fft = np.fft.rfft(signal)
mask = np.zeros_like(g_fft)
mask[low_ind:high_ind] = 1.
g_fft... | [
"def",
"filter_signal",
"(",
"signal",
",",
"f_min",
",",
"f_max",
",",
"sample_bin",
")",
":",
"track_samples",
"=",
"signal",
".",
"shape",
"[",
"0",
"]",
"Df",
"=",
"1",
"/",
"sample_bin",
"/",
"track_samples",
"low_ind",
"=",
"np",
".",
"floor",
"(... | Filter in Fourier space by multiplying with a box function for (f_min, f_max). | [
"Filter",
"in",
"Fourier",
"space",
"by",
"multiplying",
"with",
"a",
"box",
"function",
"for",
"(",
"f_min",
"f_max",
")",
"."
] | [
"\"\"\"\n Filter in Fourier space by multiplying with a box function for (f_min, f_max).\n \"\"\"",
"# odd"
] | [
{
"param": "signal",
"type": null
},
{
"param": "f_min",
"type": null
},
{
"param": "f_max",
"type": null
},
{
"param": "sample_bin",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "signal",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "f_min",
"type": null,
"docstring": null,
"docstring_tokens"... |
069bed145db2914cacf78e654a34377fa6bfffdc | davindicode/universal_count_model | neuroprob/filters.py | [
"MIT"
] | Python | forward | <not_specific> | def forward(self, input, stimulus=None):
"""
Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions.
:param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps)
... |
Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions.
:param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps)
or (samples, neurons, timesteps... | Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions. | [
"Introduces",
"the",
"spike",
"coupling",
"by",
"convolution",
"with",
"the",
"spike",
"train",
"no",
"padding",
"and",
"left",
"removal",
"for",
"causal",
"convolutions",
"."
] | def forward(self, input, stimulus=None):
h_ = self.compute_filter()
return F.conv1d(input, h_, groups=self.conv_groups), 0 | [
"def",
"forward",
"(",
"self",
",",
"input",
",",
"stimulus",
"=",
"None",
")",
":",
"h_",
"=",
"self",
".",
"compute_filter",
"(",
")",
"return",
"F",
".",
"conv1d",
"(",
"input",
",",
"h_",
",",
"groups",
"=",
"self",
".",
"conv_groups",
")",
","... | Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions. | [
"Introduces",
"the",
"spike",
"coupling",
"by",
"convolution",
"with",
"the",
"spike",
"train",
"no",
"padding",
"and",
"left",
"removal",
"for",
"causal",
"convolutions",
"."
] | [
"\"\"\"\n Introduces the spike coupling by convolution with the spike train, no padding and left removal \n for causal convolutions.\n \n :param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps) \n or (samples, ne... | [
{
"param": "self",
"type": null
},
{
"param": "input",
"type": null
},
{
"param": "stimulus",
"type": null
}
] | {
"returns": [
{
"docstring": "filtered input of shape (trials, neurons, timesteps)",
"docstring_tokens": [
"filtered",
"input",
"of",
"shape",
"(",
"trials",
"neurons",
"timesteps",
")"
],
"type": null
}
],
"r... |
069bed145db2914cacf78e654a34377fa6bfffdc | davindicode/universal_count_model | neuroprob/filters.py | [
"MIT"
] | Python | forward | <not_specific> | def forward(self, input, stimulus):
"""
Introduces stimulus-dependent raised cosine basis. The basis function parameters are drawn from a
GP that depends on the stimulus values at that given time
:param torch.tensor input: input spiketrain or covariates with shape (trials, neur... |
Introduces stimulus-dependent raised cosine basis. The basis function parameters are drawn from a
GP that depends on the stimulus values at that given time
:param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps)
... | Introduces stimulus-dependent raised cosine basis. The basis function parameters are drawn from a
GP that depends on the stimulus values at that given time | [
"Introduces",
"stimulus",
"-",
"dependent",
"raised",
"cosine",
"basis",
".",
"The",
"basis",
"function",
"parameters",
"are",
"drawn",
"from",
"a",
"GP",
"that",
"depends",
"on",
"the",
"stimulus",
"values",
"at",
"that",
"given",
"time"
] | def forward(self, input, stimulus):
assert stimulus is not None
assert input.shape[0] == 1
input_unfold = input.unfold(-1, self.history_len, 1)
stim_ = stimulus[:, self.history_len:, :]
K = stim_.shape[0]
T = input_unfold.shape[-2]
inner_batches = np.ceil(T / se... | [
"def",
"forward",
"(",
"self",
",",
"input",
",",
"stimulus",
")",
":",
"assert",
"stimulus",
"is",
"not",
"None",
"assert",
"input",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
"input_unfold",
"=",
"input",
".",
"unfold",
"(",
"-",
"1",
",",
"self",
"... | Introduces stimulus-dependent raised cosine basis. | [
"Introduces",
"stimulus",
"-",
"dependent",
"raised",
"cosine",
"basis",
"."
] | [
"\"\"\"\n Introduces stimulus-dependent raised cosine basis. The basis function parameters are drawn from a \n GP that depends on the stimulus values at that given time\n \n :param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps) \n ... | [
{
"param": "self",
"type": null
},
{
"param": "input",
"type": null
},
{
"param": "stimulus",
"type": null
}
] | {
"returns": [
{
"docstring": "filtered input of shape (trials, neurons, timesteps)",
"docstring_tokens": [
"filtered",
"input",
"of",
"shape",
"(",
"trials",
"neurons",
"timesteps",
")"
],
"type": null
}
],
"r... |
069bed145db2914cacf78e654a34377fa6bfffdc | davindicode/universal_count_model | neuroprob/filters.py | [
"MIT"
] | Python | forward | <not_specific> | def forward(self, input, stimulus=None):
"""
Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions.
:param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps)
... |
Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions.
:param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps)
or (samples, neurons, timesteps... | Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions. | [
"Introduces",
"the",
"spike",
"coupling",
"by",
"convolution",
"with",
"the",
"spike",
"train",
"no",
"padding",
"and",
"left",
"removal",
"for",
"causal",
"convolutions",
"."
] | def forward(self, input, stimulus=None):
h_, v_ = self.compute_filter()
mean_conv = F.conv1d(input, h_, groups=self.conv_groups)
if isinstance(v_, Number) is False:
var_conv = F.conv1d(input, v_, groups=self.conv_groups)
else:
var_conv = 0
return mean_conv... | [
"def",
"forward",
"(",
"self",
",",
"input",
",",
"stimulus",
"=",
"None",
")",
":",
"h_",
",",
"v_",
"=",
"self",
".",
"compute_filter",
"(",
")",
"mean_conv",
"=",
"F",
".",
"conv1d",
"(",
"input",
",",
"h_",
",",
"groups",
"=",
"self",
".",
"c... | Introduces the spike coupling by convolution with the spike train, no padding and left removal
for causal convolutions. | [
"Introduces",
"the",
"spike",
"coupling",
"by",
"convolution",
"with",
"the",
"spike",
"train",
"no",
"padding",
"and",
"left",
"removal",
"for",
"causal",
"convolutions",
"."
] | [
"\"\"\"\n Introduces the spike coupling by convolution with the spike train, no padding and left removal \n for causal convolutions.\n \n :param torch.tensor input: input spiketrain or covariates with shape (trials, neurons, timesteps) \n or (samples, ne... | [
{
"param": "self",
"type": null
},
{
"param": "input",
"type": null
},
{
"param": "stimulus",
"type": null
}
] | {
"returns": [
{
"docstring": "filtered input of shape (trials, neurons, timesteps)",
"docstring_tokens": [
"filtered",
"input",
"of",
"shape",
"(",
"trials",
"neurons",
"timesteps",
")"
],
"type": null
}
],
"r... |
069bed145db2914cacf78e654a34377fa6bfffdc | davindicode/universal_count_model | neuroprob/filters.py | [
"MIT"
] | Python | compute_filter | <not_specific> | def compute_filter(self, stim):
"""
The sample dimension is the label index for all nonzero spike bins.
:param torch.tensor stim: the stimulus variable at all nonzero bins of shape (samples, timestep, dims), note
the sample dimension includes the MC sa... |
The sample dimension is the label index for all nonzero spike bins.
:param torch.tensor stim: the stimulus variable at all nonzero bins of shape (samples, timestep, dims), note
the sample dimension includes the MC samples as well as the history shifts (KxT)
... | The sample dimension is the label index for all nonzero spike bins. | [
"The",
"sample",
"dimension",
"is",
"the",
"label",
"index",
"for",
"all",
"nonzero",
"spike",
"bins",
"."
] | def compute_filter(self, stim):
cov = torch.cat((self.cov.expand(stim.shape[0], *self.cov.shape[1:]), stim), dim=-1)
F_mu, F_var = self.filter_model.compute_F(cov)
if isinstance(F_var, Number) is False:
F_var = F_var.view(stim.shape[0], self.out_dim, self.in_dim, -1)
return... | [
"def",
"compute_filter",
"(",
"self",
",",
"stim",
")",
":",
"cov",
"=",
"torch",
".",
"cat",
"(",
"(",
"self",
".",
"cov",
".",
"expand",
"(",
"stim",
".",
"shape",
"[",
"0",
"]",
",",
"*",
"self",
".",
"cov",
".",
"shape",
"[",
"1",
":",
"]... | The sample dimension is the label index for all nonzero spike bins. | [
"The",
"sample",
"dimension",
"is",
"the",
"label",
"index",
"for",
"all",
"nonzero",
"spike",
"bins",
"."
] | [
"\"\"\"\n The sample dimension is the label index for all nonzero spike bins.\n \n :param torch.tensor stim: the stimulus variable at all nonzero bins of shape (samples, timestep, dims), note \n the sample dimension includes the MC samples as well as the history... | [
{
"param": "self",
"type": null
},
{
"param": "stim",
"type": null
}
] | {
"returns": [
{
"docstring": "filter mean of shape (samples, n_out, n_in, timesteps), filter variance of same shape",
"docstring_tokens": [
"filter",
"mean",
"of",
"shape",
"(",
"samples",
"n_out",
"n_in",
"timesteps",
")... |
069bed145db2914cacf78e654a34377fa6bfffdc | davindicode/universal_count_model | neuroprob/filters.py | [
"MIT"
] | Python | forward | <not_specific> | def forward(self, input, stimulus):
"""
The two modes of stimulus coupling are `unfold` and `repeat`, the first evaluates the filter GP at
stimulus values at the instantaneous time, whereas the latter uses the stimulus value at the time
one wants to evaluate the conditional rate expand... |
The two modes of stimulus coupling are `unfold` and `repeat`, the first evaluates the filter GP at
stimulus values at the instantaneous time, whereas the latter uses the stimulus value at the time
one wants to evaluate the conditional rate expanded across the history.
:param ... | The two modes of stimulus coupling are `unfold` and `repeat`, the first evaluates the filter GP at
stimulus values at the instantaneous time, whereas the latter uses the stimulus value at the time
one wants to evaluate the conditional rate expanded across the history. | [
"The",
"two",
"modes",
"of",
"stimulus",
"coupling",
"are",
"`",
"unfold",
"`",
"and",
"`",
"repeat",
"`",
"the",
"first",
"evaluates",
"the",
"filter",
"GP",
"at",
"stimulus",
"values",
"at",
"the",
"instantaneous",
"time",
"whereas",
"the",
"latter",
"us... | def forward(self, input, stimulus):
assert stimulus is not None
assert input.shape[0] == 1
input_unfold = input.unfold(-1, self.history_len, 1)
if self.mode == 'unfold':
stim_unfold = stimulus[:, :-1, :].unfold(1, self.history_len, 1)
else:
stim_ = stim... | [
"def",
"forward",
"(",
"self",
",",
"input",
",",
"stimulus",
")",
":",
"assert",
"stimulus",
"is",
"not",
"None",
"assert",
"input",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
"input_unfold",
"=",
"input",
".",
"unfold",
"(",
"-",
"1",
",",
"self",
"... | The two modes of stimulus coupling are `unfold` and `repeat`, the first evaluates the filter GP at
stimulus values at the instantaneous time, whereas the latter uses the stimulus value at the time
one wants to evaluate the conditional rate expanded across the history. | [
"The",
"two",
"modes",
"of",
"stimulus",
"coupling",
"are",
"`",
"unfold",
"`",
"and",
"`",
"repeat",
"`",
"the",
"first",
"evaluates",
"the",
"filter",
"GP",
"at",
"stimulus",
"values",
"at",
"the",
"instantaneous",
"time",
"whereas",
"the",
"latter",
"us... | [
"\"\"\"\n The two modes of stimulus coupling are `unfold` and `repeat`, the first evaluates the filter GP at \n stimulus values at the instantaneous time, whereas the latter uses the stimulus value at the time \n one wants to evaluate the conditional rate expanded across the history.\n \... | [
{
"param": "self",
"type": null
},
{
"param": "input",
"type": null
},
{
"param": "stimulus",
"type": null
}
] | {
"returns": [
{
"docstring": "filtered input of shape (trials, neurons, timesteps)",
"docstring_tokens": [
"filtered",
"input",
"of",
"shape",
"(",
"trials",
"neurons",
"timesteps",
")"
],
"type": null
}
],
"r... |
069bed145db2914cacf78e654a34377fa6bfffdc | davindicode/universal_count_model | neuroprob/filters.py | [
"MIT"
] | Python | filtered_rate | <not_specific> | def filtered_rate(self, F_mu, F_var, unobs_neuron, trials, MC_samples=1):
"""
Evaluate the instantaneous rate after spike coupling, with unobserved neurons not contributing
to the filtered population rate.
"""
unobs_neuron = self.likelihood._validate_neuron(unobs_neuron)
... |
Evaluate the instantaneous rate after spike coupling, with unobserved neurons not contributing
to the filtered population rate.
| Evaluate the instantaneous rate after spike coupling, with unobserved neurons not contributing
to the filtered population rate. | [
"Evaluate",
"the",
"instantaneous",
"rate",
"after",
"spike",
"coupling",
"with",
"unobserved",
"neurons",
"not",
"contributing",
"to",
"the",
"filtered",
"population",
"rate",
"."
] | def filtered_rate(self, F_mu, F_var, unobs_neuron, trials, MC_samples=1):
unobs_neuron = self.likelihood._validate_neuron(unobs_neuron)
spk = self.likelihood.spikes[b].to(self.likelihood.tbin.device)
with torch.no_grad():
hist, hist_var = self.spike_filter(spk[..., :-1], XZ)
... | [
"def",
"filtered_rate",
"(",
"self",
",",
"F_mu",
",",
"F_var",
",",
"unobs_neuron",
",",
"trials",
",",
"MC_samples",
"=",
"1",
")",
":",
"unobs_neuron",
"=",
"self",
".",
"likelihood",
".",
"_validate_neuron",
"(",
"unobs_neuron",
")",
"spk",
"=",
"self"... | Evaluate the instantaneous rate after spike coupling, with unobserved neurons not contributing
to the filtered population rate. | [
"Evaluate",
"the",
"instantaneous",
"rate",
"after",
"spike",
"coupling",
"with",
"unobserved",
"neurons",
"not",
"contributing",
"to",
"the",
"filtered",
"population",
"rate",
"."
] | [
"\"\"\"\n Evaluate the instantaneous rate after spike coupling, with unobserved neurons not contributing \n to the filtered population rate.\n \"\"\"",
"# mask",
"# mask"
] | [
{
"param": "self",
"type": null
},
{
"param": "F_mu",
"type": null
},
{
"param": "F_var",
"type": null
},
{
"param": "unobs_neuron",
"type": null
},
{
"param": "trials",
"type": null
},
{
"param": "MC_samples",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "F_mu",
"type": null,
"docstring": null,
"docstring_tokens": [... |
069bed145db2914cacf78e654a34377fa6bfffdc | davindicode/universal_count_model | neuroprob/filters.py | [
"MIT"
] | Python | sample | <not_specific> | def sample(self, rate, neuron=None, XZ=None):
"""
Assumes all neurons outside neuron are observed for spike filtering.
"""
neuron = self.likelihood._validate_neuron(neuron)
#ini_train =
steps = rate.shape[1]
spikes = []
spiketrain = torch.empty(... |
Assumes all neurons outside neuron are observed for spike filtering.
| Assumes all neurons outside neuron are observed for spike filtering. | [
"Assumes",
"all",
"neurons",
"outside",
"neuron",
"are",
"observed",
"for",
"spike",
"filtering",
"."
] | def sample(self, rate, neuron=None, XZ=None):
neuron = self.likelihood._validate_neuron(neuron)
steps = rate.shape[1]
spikes = []
spiketrain = torch.empty((*ini_train.shape[:2], self.history_len), device=self.likelihood.tbin.device)
iterator = tqdm(range(steps), leave=False)
... | [
"def",
"sample",
"(",
"self",
",",
"rate",
",",
"neuron",
"=",
"None",
",",
"XZ",
"=",
"None",
")",
":",
"neuron",
"=",
"self",
".",
"likelihood",
".",
"_validate_neuron",
"(",
"neuron",
")",
"steps",
"=",
"rate",
".",
"shape",
"[",
"1",
"]",
"spik... | Assumes all neurons outside neuron are observed for spike filtering. | [
"Assumes",
"all",
"neurons",
"outside",
"neuron",
"are",
"observed",
"for",
"spike",
"filtering",
"."
] | [
"\"\"\"\n Assumes all neurons outside neuron are observed for spike filtering.\n \"\"\"",
"#ini_train = ",
"# AR sampling",
"# shift in time",
"# spiketrain last time element is dummy, [:-1] used",
"# (trials, neuron)",
"#spikes.append(point_process.gen_IBP(1. - np.exp(-rate_*self.likeliho... | [
{
"param": "self",
"type": null
},
{
"param": "rate",
"type": null
},
{
"param": "neuron",
"type": null
},
{
"param": "XZ",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "rate",
"type": null,
"docstring": null,
"docstring_tokens": [... |
75ae9468ea38fcf9b8882f72c1c96a79eb2b5d1b | davindicode/universal_count_model | neuroprob/utils/animal.py | [
"MIT"
] | Python | collide_wall | <not_specific> | def collide_wall(self, pos, wall):
r"""
Specifies wall with normal facing to the right when x_0 is at bottom, x_1 at top.
Thickness is only in the direction of the normal, length is unaffected.
"""
x_0, ang, L, vdir, ndir, thickness = wall
pos_ = pos - x_0
L_h = n... | r"""
Specifies wall with normal facing to the right when x_0 is at bottom, x_1 at top.
Thickness is only in the direction of the normal, length is unaffected.
| r"""
Specifies wall with normal facing to the right when x_0 is at bottom, x_1 at top.
Thickness is only in the direction of the normal, length is unaffected. | [
"r",
"\"",
"\"",
"\"",
"Specifies",
"wall",
"with",
"normal",
"facing",
"to",
"the",
"right",
"when",
"x_0",
"is",
"at",
"bottom",
"x_1",
"at",
"top",
".",
"Thickness",
"is",
"only",
"in",
"the",
"direction",
"of",
"the",
"normal",
"length",
"is",
"una... | def collide_wall(self, pos, wall):
x_0, ang, L, vdir, ndir, thickness = wall
pos_ = pos - x_0
L_h = np.dot(pos_, vdir)
L_v = np.dot(pos_, ndir)
ang = WrapPi(np.angle(ndir[0] + 1j*ndir[1]), True)
r = L_v - np.sign(L_v)*thickness
if L_h > 0 and L_h < L and np.abs(L_... | [
"def",
"collide_wall",
"(",
"self",
",",
"pos",
",",
"wall",
")",
":",
"x_0",
",",
"ang",
",",
"L",
",",
"vdir",
",",
"ndir",
",",
"thickness",
"=",
"wall",
"pos_",
"=",
"pos",
"-",
"x_0",
"L_h",
"=",
"np",
".",
"dot",
"(",
"pos_",
",",
"vdir",... | r"""
Specifies wall with normal facing to the right when x_0 is at bottom, x_1 at top. | [
"r",
"\"",
"\"",
"\"",
"Specifies",
"wall",
"with",
"normal",
"facing",
"to",
"the",
"right",
"when",
"x_0",
"is",
"at",
"bottom",
"x_1",
"at",
"top",
"."
] | [
"r\"\"\"\n Specifies wall with normal facing to the right when x_0 is at bottom, x_1 at top.\n Thickness is only in the direction of the normal, length is unaffected.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "pos",
"type": null
},
{
"param": "wall",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pos",
"type": null,
"docstring": null,
"docstring_tokens": []... |
7f94b1a5018e98d0810f87f6652b6e6a7c415a99 | davindicode/universal_count_model | neuroprob/GP/linalg.py | [
"MIT"
] | Python | p_F_U | <not_specific> | def p_F_U(out_dims, X, X_u, kernel, f_loc, f_scale_tril=None, Lff=None, cov_type='diagonal',
whiten=False, jitter=1e-6):
r"""
Single kernel parameter set shared over all output dimensions.
:param int out_dims: number of output dimensions
:param torch.Tensor X: Input data to evaluate the posteri... | r"""
Single kernel parameter set shared over all output dimensions.
:param int out_dims: number of output dimensions
:param torch.Tensor X: Input data to evaluate the posterior over
:param torch.Tensor X_u: Input data to conditioned on, inducing points in sparse GP
:param GP.kernels.Kernel kernel: ... | r"""
Single kernel parameter set shared over all output dimensions. | [
"r",
"\"",
"\"",
"\"",
"Single",
"kernel",
"parameter",
"set",
"shared",
"over",
"all",
"output",
"dimensions",
"."
] | def p_F_U(out_dims, X, X_u, kernel, f_loc, f_scale_tril=None, Lff=None, cov_type='diagonal',
whiten=False, jitter=1e-6):
N_u = X_u.size(1)
T = X.size(1)
K = X.size(0)
X = X[None, ...]
X_u = X_u[:, None, ...]
if Lff is None:
Kff = kernel(X_u)[:, 0, ...].contiguous()
Kff.... | [
"def",
"p_F_U",
"(",
"out_dims",
",",
"X",
",",
"X_u",
",",
"kernel",
",",
"f_loc",
",",
"f_scale_tril",
"=",
"None",
",",
"Lff",
"=",
"None",
",",
"cov_type",
"=",
"'diagonal'",
",",
"whiten",
"=",
"False",
",",
"jitter",
"=",
"1e-6",
")",
":",
"N... | r"""
Single kernel parameter set shared over all output dimensions. | [
"r",
"\"",
"\"",
"\"",
"Single",
"kernel",
"parameter",
"set",
"shared",
"over",
"all",
"output",
"dimensions",
"."
] | [
"r\"\"\"\n Single kernel parameter set shared over all output dimensions.\n\n :param int out_dims: number of output dimensions\n :param torch.Tensor X: Input data to evaluate the posterior over\n :param torch.Tensor X_u: Input data to conditioned on, inducing points in sparse GP\n :param GP.kernels.K... | [
{
"param": "out_dims",
"type": null
},
{
"param": "X",
"type": null
},
{
"param": "X_u",
"type": null
},
{
"param": "kernel",
"type": null
},
{
"param": "f_loc",
"type": null
},
{
"param": "f_scale_tril",
"type": null
},
{
"param": "Lff",
... | {
"returns": [
{
"docstring": "loc and covariance matrix (or variance) of :math:`p(f^*(X_{new}))`",
"docstring_tokens": [
"loc",
"and",
"covariance",
"matrix",
"(",
"or",
"variance",
")",
"of",
":",
"math",
... |
7f94b1a5018e98d0810f87f6652b6e6a7c415a99 | davindicode/universal_count_model | neuroprob/GP/linalg.py | [
"MIT"
] | Python | cg_batch | <not_specific> | def cg_batch(A_bmm, B, M_bmm=None, X0=None, rtol=1e-3, atol=0., maxiter=None, verbose=False):
"""
Solves a batch of PD matrix linear systems using the preconditioned CG algorithm.
This function solves a batch of matrix linear systems of the form
A_i X_i = B_i, i=1,...,K,
where A_i is a n x n po... |
Solves a batch of PD matrix linear systems using the preconditioned CG algorithm.
This function solves a batch of matrix linear systems of the form
A_i X_i = B_i, i=1,...,K,
where A_i is a n x n positive definite matrix and B_i is a n x m matrix,
and X_i is the n x m matrix representing the so... | Solves a batch of PD matrix linear systems using the preconditioned CG algorithm.
This function solves a batch of matrix linear systems of the form
A_i X_i = B_i, i=1,...,K,
where A_i is a n x n positive definite matrix and B_i is a n x m matrix,
and X_i is the n x m matrix representing the solution for the ith system... | [
"Solves",
"a",
"batch",
"of",
"PD",
"matrix",
"linear",
"systems",
"using",
"the",
"preconditioned",
"CG",
"algorithm",
".",
"This",
"function",
"solves",
"a",
"batch",
"of",
"matrix",
"linear",
"systems",
"of",
"the",
"form",
"A_i",
"X_i",
"=",
"B_i",
"i"... | def cg_batch(A_bmm, B, M_bmm=None, X0=None, rtol=1e-3, atol=0., maxiter=None, verbose=False):
K, n, m = B.shape
if M_bmm is None:
M_bmm = lambda x: x
if X0 is None:
X0 = M_bmm(B)
if maxiter is None:
maxiter = 5 * n
assert B.shape == (K, n, m)
assert X0.shape == (K, n, m)
... | [
"def",
"cg_batch",
"(",
"A_bmm",
",",
"B",
",",
"M_bmm",
"=",
"None",
",",
"X0",
"=",
"None",
",",
"rtol",
"=",
"1e-3",
",",
"atol",
"=",
"0.",
",",
"maxiter",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"K",
",",
"n",
",",
"m",
"=",... | Solves a batch of PD matrix linear systems using the preconditioned CG algorithm. | [
"Solves",
"a",
"batch",
"of",
"PD",
"matrix",
"linear",
"systems",
"using",
"the",
"preconditioned",
"CG",
"algorithm",
"."
] | [
"\"\"\"\n Solves a batch of PD matrix linear systems using the preconditioned CG algorithm.\n This function solves a batch of matrix linear systems of the form\n A_i X_i = B_i, i=1,...,K,\n where A_i is a n x n positive definite matrix and B_i is a n x m matrix,\n and X_i is the n x m matrix rep... | [
{
"param": "A_bmm",
"type": null
},
{
"param": "B",
"type": null
},
{
"param": "M_bmm",
"type": null
},
{
"param": "X0",
"type": null
},
{
"param": "rtol",
"type": null
},
{
"param": "atol",
"type": null
},
{
"param": "maxiter",
"type":... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "A_bmm",
"type": null,
"docstring": "A callable that performs a batch matrix multiply of A and a K x n x m matrix.",
"docstring_tokens": [
"A",
"callable",
"that",
"performs",
"a",
... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | compute_mesh | <not_specific> | def compute_mesh(grid_n, grid_size, func):
"""
Create a uniformly spaced mesh over which to evaluate func.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
"""
mesh = ()
for n, gn in enumerate... |
Create a uniformly spaced mesh over which to evaluate func.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
| Create a uniformly spaced mesh over which to evaluate func. | [
"Create",
"a",
"uniformly",
"spaced",
"mesh",
"over",
"which",
"to",
"evaluate",
"func",
"."
] | def compute_mesh(grid_n, grid_size, func):
mesh = ()
for n, gn in enumerate(grid_n):
mesh += (np.linspace(grid_size[n][0], grid_size[n][1], gn),)
cc = np.meshgrid(*mesh)
z = np.stack(list(cc))
field = func(z)
return cc, field | [
"def",
"compute_mesh",
"(",
"grid_n",
",",
"grid_size",
",",
"func",
")",
":",
"mesh",
"=",
"(",
")",
"for",
"n",
",",
"gn",
"in",
"enumerate",
"(",
"grid_n",
")",
":",
"mesh",
"+=",
"(",
"np",
".",
"linspace",
"(",
"grid_size",
"[",
"n",
"]",
"[... | Create a uniformly spaced mesh over which to evaluate func. | [
"Create",
"a",
"uniformly",
"spaced",
"mesh",
"over",
"which",
"to",
"evaluate",
"func",
"."
] | [
"\"\"\"\n Create a uniformly spaced mesh over which to evaluate func.\n \n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n :returns: figure and axis\n :rtype: tuple\n \"\"\""
] | [
{
"param": "grid_n",
"type": null
},
{
"param": "grid_size",
"type": null
},
{
"param": "func",
"type": null
}
] | {
"returns": [
{
"docstring": "figure and axis",
"docstring_tokens": [
"figure",
"and",
"axis"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "grid_n",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | add_colorbar | null | def add_colorbar(figax, image, cbar_outline=False, cbar_ori='vertical', cbar_fontsize=12,
cbar_pad=20, ticktitle=None, ticks=None, ticklabels=None, cbar_format=None):
"""
Adds a colorbar object to the axis.
:param string cbar_format: cbar label formatting, scientific mode '%.1e'
"... |
Adds a colorbar object to the axis.
:param string cbar_format: cbar label formatting, scientific mode '%.1e'
| Adds a colorbar object to the axis. | [
"Adds",
"a",
"colorbar",
"object",
"to",
"the",
"axis",
"."
] | def add_colorbar(figax, image, cbar_outline=False, cbar_ori='vertical', cbar_fontsize=12,
cbar_pad=20, ticktitle=None, ticks=None, ticklabels=None, cbar_format=None):
fig, ax = figax
if cbar_ori == 'vertical':
rot = 270
else:
rot = 0
cbar = fig.colorbar(image, cax=ax, o... | [
"def",
"add_colorbar",
"(",
"figax",
",",
"image",
",",
"cbar_outline",
"=",
"False",
",",
"cbar_ori",
"=",
"'vertical'",
",",
"cbar_fontsize",
"=",
"12",
",",
"cbar_pad",
"=",
"20",
",",
"ticktitle",
"=",
"None",
",",
"ticks",
"=",
"None",
",",
"ticklab... | Adds a colorbar object to the axis. | [
"Adds",
"a",
"colorbar",
"object",
"to",
"the",
"axis",
"."
] | [
"\"\"\"\n Adds a colorbar object to the axis.\n \n :param string cbar_format: cbar label formatting, scientific mode '%.1e'\n \"\"\""
] | [
{
"param": "figax",
"type": null
},
{
"param": "image",
"type": null
},
{
"param": "cbar_outline",
"type": null
},
{
"param": "cbar_ori",
"type": null
},
{
"param": "cbar_fontsize",
"type": null
},
{
"param": "cbar_pad",
"type": null
},
{
"... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "figax",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "image",
"type": null,
"docstring": null,
"docstring_tokens":... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | mesh_plot | <not_specific> | def mesh_plot(figax, mesh_tuple, cmap='gray', vmin=None, vmax=None):
"""
Create a mesh plot from a mesh tuple given by compute_mesh.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
"""
fig, ax = ... |
Create a mesh plot from a mesh tuple given by compute_mesh.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
| Create a mesh plot from a mesh tuple given by compute_mesh. | [
"Create",
"a",
"mesh",
"plot",
"from",
"a",
"mesh",
"tuple",
"given",
"by",
"compute_mesh",
"."
] | def mesh_plot(figax, mesh_tuple, cmap='gray', vmin=None, vmax=None):
fig, ax = figax
xx, yy, field = mesh_tuple
im = ax.pcolormesh(xx, yy, field, vmin=vmin, vmax=vmax, cmap=cmap)
return im | [
"def",
"mesh_plot",
"(",
"figax",
",",
"mesh_tuple",
",",
"cmap",
"=",
"'gray'",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"fig",
",",
"ax",
"=",
"figax",
"xx",
",",
"yy",
",",
"field",
"=",
"mesh_tuple",
"im",
"=",
"ax",
".",... | Create a mesh plot from a mesh tuple given by compute_mesh. | [
"Create",
"a",
"mesh",
"plot",
"from",
"a",
"mesh",
"tuple",
"given",
"by",
"compute_mesh",
"."
] | [
"\"\"\"\n Create a mesh plot from a mesh tuple given by compute_mesh.\n \n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n :returns: figure and axis\n :rtype: tuple\n \"\"\""
] | [
{
"param": "figax",
"type": null
},
{
"param": "mesh_tuple",
"type": null
},
{
"param": "cmap",
"type": null
},
{
"param": "vmin",
"type": null
},
{
"param": "vmax",
"type": null
}
] | {
"returns": [
{
"docstring": "figure and axis",
"docstring_tokens": [
"figure",
"and",
"axis"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "figax",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | draw_2d | <not_specific> | def draw_2d(figax, data, vmin=0, vmax=1, cmap='gray', origin='upper', aspect='auto', extent=None,
interp_method=None):
"""
Visualize a 2D array using imshow, the first axis of data is the y-axis.
:param list colors: colors to be included in the colormap
:param string name: name the col... |
Visualize a 2D array using imshow, the first axis of data is the y-axis.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
| Visualize a 2D array using imshow, the first axis of data is the y-axis. | [
"Visualize",
"a",
"2D",
"array",
"using",
"imshow",
"the",
"first",
"axis",
"of",
"data",
"is",
"the",
"y",
"-",
"axis",
"."
] | def draw_2d(figax, data, vmin=0, vmax=1, cmap='gray', origin='upper', aspect='auto', extent=None,
interp_method=None):
fig, ax = figax
im = ax.imshow(data, cmap=cmap, origin=origin, vmin=vmin, vmax=vmax, aspect=aspect,
interpolation=interp_method, extent=extent)
return im | [
"def",
"draw_2d",
"(",
"figax",
",",
"data",
",",
"vmin",
"=",
"0",
",",
"vmax",
"=",
"1",
",",
"cmap",
"=",
"'gray'",
",",
"origin",
"=",
"'upper'",
",",
"aspect",
"=",
"'auto'",
",",
"extent",
"=",
"None",
",",
"interp_method",
"=",
"None",
")",
... | Visualize a 2D array using imshow, the first axis of data is the y-axis. | [
"Visualize",
"a",
"2D",
"array",
"using",
"imshow",
"the",
"first",
"axis",
"of",
"data",
"is",
"the",
"y",
"-",
"axis",
"."
] | [
"\"\"\"\n Visualize a 2D array using imshow, the first axis of data is the y-axis.\n \n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n :returns: figure and axis\n :rtype: tuple\n \"\"\""
] | [
{
"param": "figax",
"type": null
},
{
"param": "data",
"type": null
},
{
"param": "vmin",
"type": null
},
{
"param": "vmax",
"type": null
},
{
"param": "cmap",
"type": null
},
{
"param": "origin",
"type": null
},
{
"param": "aspect",
"t... | {
"returns": [
{
"docstring": "figure and axis",
"docstring_tokens": [
"figure",
"and",
"axis"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "figax",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | raster_plot | <not_specific> | def raster_plot(figax, spikes, time_bins, bin_time_ms, units, colors=None, marker='|', markersize=2):
"""
Visualize a 2D array representing point events, spikes has shape (timstep, units).
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: ... |
Visualize a 2D array representing point events, spikes has shape (timstep, units).
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
| Visualize a 2D array representing point events, spikes has shape (timstep, units). | [
"Visualize",
"a",
"2D",
"array",
"representing",
"point",
"events",
"spikes",
"has",
"shape",
"(",
"timstep",
"units",
")",
"."
] | def raster_plot(figax, spikes, time_bins, bin_time_ms, units, colors=None, marker='|', markersize=2):
fig, ax = figax
if colors is None:
col = ['k']*units
else:
col = colors
for i in range(units):
t = np.nonzero(spikes[i, :])[0]*bin_time_ms
ax.scatter(t, (i+1) * np.ones_l... | [
"def",
"raster_plot",
"(",
"figax",
",",
"spikes",
",",
"time_bins",
",",
"bin_time_ms",
",",
"units",
",",
"colors",
"=",
"None",
",",
"marker",
"=",
"'|'",
",",
"markersize",
"=",
"2",
")",
":",
"fig",
",",
"ax",
"=",
"figax",
"if",
"colors",
"is",... | Visualize a 2D array representing point events, spikes has shape (timstep, units). | [
"Visualize",
"a",
"2D",
"array",
"representing",
"point",
"events",
"spikes",
"has",
"shape",
"(",
"timstep",
"units",
")",
"."
] | [
"\"\"\"\n Visualize a 2D array representing point events, spikes has shape (timstep, units).\n \n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n :returns: figure and axis\n :rtype: tuple\n \"\"\""
] | [
{
"param": "figax",
"type": null
},
{
"param": "spikes",
"type": null
},
{
"param": "time_bins",
"type": null
},
{
"param": "bin_time_ms",
"type": null
},
{
"param": "units",
"type": null
},
{
"param": "colors",
"type": null
},
{
"param": "... | {
"returns": [
{
"docstring": "figure and axis",
"docstring_tokens": [
"figure",
"and",
"axis"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "figax",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | grid_draw_2d | <not_specific> | def grid_draw_2d(data, figsize, nrows, ncols, vmin=0, vmax=1, cmap='gray'):
"""
Visualize batched image data on a grid.
:param np.array data: input data of shape ()
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
... |
Visualize batched image data on a grid.
:param np.array data: input data of shape ()
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
| Visualize batched image data on a grid. | [
"Visualize",
"batched",
"image",
"data",
"on",
"a",
"grid",
"."
] | def grid_draw_2d(data, figsize, nrows, ncols, vmin=0, vmax=1, cmap='gray'):
fig = plt.figure(figsize=figsize)
axes = [ fig.add_subplot(nrows, ncols, r * ncols + c + 1) for r in range(0, nrows) for c in range(0, ncols) ]
chans = data.shape[1]
if chans == 1:
data = data.squeeze(1)
else:
... | [
"def",
"grid_draw_2d",
"(",
"data",
",",
"figsize",
",",
"nrows",
",",
"ncols",
",",
"vmin",
"=",
"0",
",",
"vmax",
"=",
"1",
",",
"cmap",
"=",
"'gray'",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"axes",
"="... | Visualize batched image data on a grid. | [
"Visualize",
"batched",
"image",
"data",
"on",
"a",
"grid",
"."
] | [
"\"\"\"\n Visualize batched image data on a grid.\n \n :param np.array data: input data of shape ()\n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n :returns: figure and axis\n :rtype: tuple\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "figsize",
"type": null
},
{
"param": "nrows",
"type": null
},
{
"param": "ncols",
"type": null
},
{
"param": "vmin",
"type": null
},
{
"param": "vmax",
"type": null
},
{
"param": "cmap",
"t... | {
"returns": [
{
"docstring": "figure and axis",
"docstring_tokens": [
"figure",
"and",
"axis"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": "input data of shape ()",
"docst... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | render_image | <not_specific> | def render_image(fig):
"""
Render an image from a figure buffer.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
"""
fig.canvas.draw() # draw the canvas, cache the renderer
image = np.frombuf... |
Render an image from a figure buffer.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: figure and axis
:rtype: tuple
| Render an image from a figure buffer. | [
"Render",
"an",
"image",
"from",
"a",
"figure",
"buffer",
"."
] | def render_image(fig):
fig.canvas.draw()
image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
return image | [
"def",
"render_image",
"(",
"fig",
")",
":",
"fig",
".",
"canvas",
".",
"draw",
"(",
")",
"image",
"=",
"np",
".",
"frombuffer",
"(",
"fig",
".",
"canvas",
".",
"tostring_rgb",
"(",
")",
",",
"dtype",
"=",
"'uint8'",
")",
"image",
"=",
"image",
"."... | Render an image from a figure buffer. | [
"Render",
"an",
"image",
"from",
"a",
"figure",
"buffer",
"."
] | [
"\"\"\"\n Render an image from a figure buffer.\n \n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n :returns: figure and axis\n :rtype: tuple\n \"\"\"",
"# draw the canvas, cache the renderer"
] | [
{
"param": "fig",
"type": null
}
] | {
"returns": [
{
"docstring": "figure and axis",
"docstring_tokens": [
"figure",
"and",
"axis"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "fig",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | generate_gif | null | def generate_gif(images, out_file, fps=10):
"""
Create a gif from an array of images.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
"""
kwargs_write = {'fps': fps, 'quantizer': 'nq'}
imageio.mimsave(out_file, images, fps=fps) |
Create a gif from an array of images.
:param list colors: colors to be included in the colormap
:param string name: name the colormap
| Create a gif from an array of images. | [
"Create",
"a",
"gif",
"from",
"an",
"array",
"of",
"images",
"."
] | def generate_gif(images, out_file, fps=10):
kwargs_write = {'fps': fps, 'quantizer': 'nq'}
imageio.mimsave(out_file, images, fps=fps) | [
"def",
"generate_gif",
"(",
"images",
",",
"out_file",
",",
"fps",
"=",
"10",
")",
":",
"kwargs_write",
"=",
"{",
"'fps'",
":",
"fps",
",",
"'quantizer'",
":",
"'nq'",
"}",
"imageio",
".",
"mimsave",
"(",
"out_file",
",",
"images",
",",
"fps",
"=",
"... | Create a gif from an array of images. | [
"Create",
"a",
"gif",
"from",
"an",
"array",
"of",
"images",
"."
] | [
"\"\"\"\n Create a gif from an array of images.\n \n :param list colors: colors to be included in the colormap\n :param string name: name the colormap\n \"\"\""
] | [
{
"param": "images",
"type": null
},
{
"param": "out_file",
"type": null
},
{
"param": "fps",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "images",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "out_file",
"type": null,
"docstring": null,
"docstring_toke... |
ae8ac19f56bb7f941b3cd030df4e5898730c1e00 | davindicode/universal_count_model | neuroprob/utils/plot.py | [
"MIT"
] | Python | plot_circ_posterior | null | def plot_circ_posterior(ax, times, wrap_y, y_std, col='k', linewidth=1., step=1, alpha=0.5, line_alpha=1.,
l=None, l_std=None):
"""
Plot circular variables with (approximate) variational uncertainty.
"""
if y_std is not None:
upper = wrap_y + y_std
lower = wrap_y... |
Plot circular variables with (approximate) variational uncertainty.
| Plot circular variables with (approximate) variational uncertainty. | [
"Plot",
"circular",
"variables",
"with",
"(",
"approximate",
")",
"variational",
"uncertainty",
"."
] | def plot_circ_posterior(ax, times, wrap_y, y_std, col='k', linewidth=1., step=1, alpha=0.5, line_alpha=1.,
l=None, l_std=None):
if y_std is not None:
upper = wrap_y + y_std
lower = wrap_y - y_std
T = len(wrap_y)
for i in np.arange(T)[1::step]:
lines = []
... | [
"def",
"plot_circ_posterior",
"(",
"ax",
",",
"times",
",",
"wrap_y",
",",
"y_std",
",",
"col",
"=",
"'k'",
",",
"linewidth",
"=",
"1.",
",",
"step",
"=",
"1",
",",
"alpha",
"=",
"0.5",
",",
"line_alpha",
"=",
"1.",
",",
"l",
"=",
"None",
",",
"l... | Plot circular variables with (approximate) variational uncertainty. | [
"Plot",
"circular",
"variables",
"with",
"(",
"approximate",
")",
"variational",
"uncertainty",
"."
] | [
"\"\"\"\n Plot circular variables with (approximate) variational uncertainty.\n \"\"\"",
"# double locations for uncertainty"
] | [
{
"param": "ax",
"type": null
},
{
"param": "times",
"type": null
},
{
"param": "wrap_y",
"type": null
},
{
"param": "y_std",
"type": null
},
{
"param": "col",
"type": null
},
{
"param": "linewidth",
"type": null
},
{
"param": "step",
"... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ax",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "times",
"type": null,
"docstring": null,
"docstring_tokens": []... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | bin_data | <not_specific> | def bin_data(bin_size, bin_time, spiketimes, track_samples, behaviour_data=None, average_behav=True, binned=False):
"""
Bin the spike train into a given bin size.
:param int bin_size: desired binning of original time steps into new bin
:param float bin_time: time step of each original bin or time p... |
Bin the spike train into a given bin size.
:param int bin_size: desired binning of original time steps into new bin
:param float bin_time: time step of each original bin or time point
:param np.array spiketimes: input spikes in train or index format
:param int track_samples: number of time ste... | Bin the spike train into a given bin size. | [
"Bin",
"the",
"spike",
"train",
"into",
"a",
"given",
"bin",
"size",
"."
] | def bin_data(bin_size, bin_time, spiketimes, track_samples, behaviour_data=None, average_behav=True, binned=False):
tbin = bin_size*bin_time
resamples = int(np.floor(track_samples/bin_size))
centre = bin_size // 2
rcov_t = ()
if behaviour_data is not None:
if isinstance(average_behav, list) ... | [
"def",
"bin_data",
"(",
"bin_size",
",",
"bin_time",
",",
"spiketimes",
",",
"track_samples",
",",
"behaviour_data",
"=",
"None",
",",
"average_behav",
"=",
"True",
",",
"binned",
"=",
"False",
")",
":",
"tbin",
"=",
"bin_size",
"*",
"bin_time",
"resamples",... | Bin the spike train into a given bin size. | [
"Bin",
"the",
"spike",
"train",
"into",
"a",
"given",
"bin",
"size",
"."
] | [
"\"\"\"\n Bin the spike train into a given bin size.\n \n :param int bin_size: desired binning of original time steps into new bin\n :param float bin_time: time step of each original bin or time point\n :param np.array spiketimes: input spikes in train or index format\n :param int track_samples: n... | [
{
"param": "bin_size",
"type": null
},
{
"param": "bin_time",
"type": null
},
{
"param": "spiketimes",
"type": null
},
{
"param": "track_samples",
"type": null
},
{
"param": "behaviour_data",
"type": null
},
{
"param": "average_behav",
"type": null... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "bin_size",
"type": null,
"docstring": "desired binning of original time steps into new bin",
"docstring_tokens": [
"desired",
"binning",
"of",
"original",
"time",
"steps",
... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | binned_to_indices | <not_specific> | def binned_to_indices(spiketrain):
"""
Converts a binned spike train into spike time indices (with duplicates)
:param np.array spiketrain: the spike train to convert
:returns: spike indices denoting spike times in units of time bins
:rtype: np.array
"""
spike_ind = spiketrain.nonzero()[... |
Converts a binned spike train into spike time indices (with duplicates)
:param np.array spiketrain: the spike train to convert
:returns: spike indices denoting spike times in units of time bins
:rtype: np.array
| Converts a binned spike train into spike time indices (with duplicates) | [
"Converts",
"a",
"binned",
"spike",
"train",
"into",
"spike",
"time",
"indices",
"(",
"with",
"duplicates",
")"
] | def binned_to_indices(spiketrain):
spike_ind = spiketrain.nonzero()[0]
bigger = np.where(spiketrain > 1)[0]
add_on = (spike_ind,)
for b in bigger:
add_on += (b*np.ones(int(spiketrain[b])-1, dtype=int),)
spike_ind = np.concatenate(add_on)
return np.sort(spike_ind) | [
"def",
"binned_to_indices",
"(",
"spiketrain",
")",
":",
"spike_ind",
"=",
"spiketrain",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"bigger",
"=",
"np",
".",
"where",
"(",
"spiketrain",
">",
"1",
")",
"[",
"0",
"]",
"add_on",
"=",
"(",
"spike_ind",
","... | Converts a binned spike train into spike time indices (with duplicates) | [
"Converts",
"a",
"binned",
"spike",
"train",
"into",
"spike",
"time",
"indices",
"(",
"with",
"duplicates",
")"
] | [
"\"\"\"\n Converts a binned spike train into spike time indices (with duplicates)\n \n :param np.array spiketrain: the spike train to convert\n :returns: spike indices denoting spike times in units of time bins\n :rtype: np.array\n \"\"\""
] | [
{
"param": "spiketrain",
"type": null
}
] | {
"returns": [
{
"docstring": "spike indices denoting spike times in units of time bins",
"docstring_tokens": [
"spike",
"indices",
"denoting",
"spike",
"times",
"in",
"units",
"of",
"time",
"bins"
],
"type": "... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | covariates_at_spikes | <not_specific> | def covariates_at_spikes(spiketimes, behaviour_data):
"""
Returns tuple of covariate arrays at spiketimes for all neurons
"""
cov_s = tuple([] for n in behaviour_data)
units = len(spiketimes)
for u in range(units):
for k, cov_t in enumerate(behaviour_data):
cov_s[k].append(co... |
Returns tuple of covariate arrays at spiketimes for all neurons
| Returns tuple of covariate arrays at spiketimes for all neurons | [
"Returns",
"tuple",
"of",
"covariate",
"arrays",
"at",
"spiketimes",
"for",
"all",
"neurons"
] | def covariates_at_spikes(spiketimes, behaviour_data):
cov_s = tuple([] for n in behaviour_data)
units = len(spiketimes)
for u in range(units):
for k, cov_t in enumerate(behaviour_data):
cov_s[k].append(cov_t[spiketimes[u]])
return cov_s | [
"def",
"covariates_at_spikes",
"(",
"spiketimes",
",",
"behaviour_data",
")",
":",
"cov_s",
"=",
"tuple",
"(",
"[",
"]",
"for",
"n",
"in",
"behaviour_data",
")",
"units",
"=",
"len",
"(",
"spiketimes",
")",
"for",
"u",
"in",
"range",
"(",
"units",
")",
... | Returns tuple of covariate arrays at spiketimes for all neurons | [
"Returns",
"tuple",
"of",
"covariate",
"arrays",
"at",
"spiketimes",
"for",
"all",
"neurons"
] | [
"\"\"\"\n Returns tuple of covariate arrays at spiketimes for all neurons\n \"\"\""
] | [
{
"param": "spiketimes",
"type": null
},
{
"param": "behaviour_data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "spiketimes",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "behaviour_data",
"type": null,
"docstring": null,
"docs... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | spiketrain_CV | <not_specific> | def spiketrain_CV(folds, spiketrain, track_samples, behaviour_list=None):
"""
Creates subsets of the the neural data (behaviour plus spike trains) and splits it
into folds cross-validation sets with validation data and test data as one out of the
folds subsets, validation data being the rest. Each cro... |
Creates subsets of the the neural data (behaviour plus spike trains) and splits it
into folds cross-validation sets with validation data and test data as one out of the
folds subsets, validation data being the rest. Each cross-validation set will take
a different folds subset for validation data.
... | Creates subsets of the the neural data (behaviour plus spike trains) and splits it
into folds cross-validation sets with validation data and test data as one out of the
folds subsets, validation data being the rest. Each cross-validation set will take
a different folds subset for validation data. | [
"Creates",
"subsets",
"of",
"the",
"the",
"neural",
"data",
"(",
"behaviour",
"plus",
"spike",
"trains",
")",
"and",
"splits",
"it",
"into",
"folds",
"cross",
"-",
"validation",
"sets",
"with",
"validation",
"data",
"and",
"test",
"data",
"as",
"one",
"out... | def spiketrain_CV(folds, spiketrain, track_samples, behaviour_list=None):
behav = np.array(behaviour_list)
df = track_samples // folds
cv_set = []
valset_start = []
blocks_t = []
blocks_c = []
for f in range(folds):
valset_start.append(df*f)
blocks_t.append(spiketrain[:, df*... | [
"def",
"spiketrain_CV",
"(",
"folds",
",",
"spiketrain",
",",
"track_samples",
",",
"behaviour_list",
"=",
"None",
")",
":",
"behav",
"=",
"np",
".",
"array",
"(",
"behaviour_list",
")",
"df",
"=",
"track_samples",
"//",
"folds",
"cv_set",
"=",
"[",
"]",
... | Creates subsets of the the neural data (behaviour plus spike trains) and splits it
into folds cross-validation sets with validation data and test data as one out of the
folds subsets, validation data being the rest. | [
"Creates",
"subsets",
"of",
"the",
"the",
"neural",
"data",
"(",
"behaviour",
"plus",
"spike",
"trains",
")",
"and",
"splits",
"it",
"into",
"folds",
"cross",
"-",
"validation",
"sets",
"with",
"validation",
"data",
"and",
"test",
"data",
"as",
"one",
"out... | [
"\"\"\"\n Creates subsets of the the neural data (behaviour plus spike trains) and splits it \n into folds cross-validation sets with validation data and test data as one out of the \n folds subsets, validation data being the rest. Each cross-validation set will take \n a different folds subset for vali... | [
{
"param": "folds",
"type": null
},
{
"param": "spiketrain",
"type": null
},
{
"param": "track_samples",
"type": null
},
{
"param": "behaviour_list",
"type": null
}
] | {
"returns": [
{
"docstring": "cross-validation set as tuple",
"docstring_tokens": [
"cross",
"-",
"validation",
"set",
"as",
"tuple"
],
"type": "tuple"
}
],
"raises": [],
"params": [
{
"identifier": "folds",
"type":... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | batch_segments | <not_specific> | def batch_segments(segment_lengths, batch_size):
"""
Returns list of batch size and batch links for input to the model batching argument.
:param list segment_lengths: list of time step lengths of continuous segments in the data
"""
batch_list = []
for s in segment_lengths:
if s == 0... |
Returns list of batch size and batch links for input to the model batching argument.
:param list segment_lengths: list of time step lengths of continuous segments in the data
| Returns list of batch size and batch links for input to the model batching argument. | [
"Returns",
"list",
"of",
"batch",
"size",
"and",
"batch",
"links",
"for",
"input",
"to",
"the",
"model",
"batching",
"argument",
"."
] | def batch_segments(segment_lengths, batch_size):
batch_list = []
for s in segment_lengths:
if s == 0:
continue
n = int(np.ceil(s / batch_size))-1
for n_ in range(n):
batch_list.append((batch_size, True if n_ > 0 else False))
batch_list.append((s - n*batch... | [
"def",
"batch_segments",
"(",
"segment_lengths",
",",
"batch_size",
")",
":",
"batch_list",
"=",
"[",
"]",
"for",
"s",
"in",
"segment_lengths",
":",
"if",
"s",
"==",
"0",
":",
"continue",
"n",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"s",
"/",
"batch... | Returns list of batch size and batch links for input to the model batching argument. | [
"Returns",
"list",
"of",
"batch",
"size",
"and",
"batch",
"links",
"for",
"input",
"to",
"the",
"model",
"batching",
"argument",
"."
] | [
"\"\"\"\n Returns list of batch size and batch links for input to the model batching argument.\n \n :param list segment_lengths: list of time step lengths of continuous segments in the data\n \"\"\"",
"# empty segment"
] | [
{
"param": "segment_lengths",
"type": null
},
{
"param": "batch_size",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "segment_lengths",
"type": null,
"docstring": "list of time step lengths of continuous segments in the data",
"docstring_tokens": [
"list",
"of",
"time",
"step",
"lengths",
"of",
... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | spike_threshold | <not_specific> | def spike_threshold(sample_bin, bin_thres, covariates, cov_bins, spiketimes, direct=False):
"""
Only include spikes that correspond to bins with sufficient occupancy time. This is useful
when using histogram models to avoid counting undersampled bins, which suffer from huge
variance when computing the... |
Only include spikes that correspond to bins with sufficient occupancy time. This is useful
when using histogram models to avoid counting undersampled bins, which suffer from huge
variance when computing the average firing rates in a histogram.
:param float sample_bin: binning time
:param flo... | Only include spikes that correspond to bins with sufficient occupancy time. This is useful
when using histogram models to avoid counting undersampled bins, which suffer from huge
variance when computing the average firing rates in a histogram. | [
"Only",
"include",
"spikes",
"that",
"correspond",
"to",
"bins",
"with",
"sufficient",
"occupancy",
"time",
".",
"This",
"is",
"useful",
"when",
"using",
"histogram",
"models",
"to",
"avoid",
"counting",
"undersampled",
"bins",
"which",
"suffer",
"from",
"huge",... | def spike_threshold(sample_bin, bin_thres, covariates, cov_bins, spiketimes, direct=False):
units = len(spiketimes)
c_bins = ()
tg_c = ()
sg_c = [() for u in range(units)]
for k, cov in enumerate(covariates):
c_bins += (len(cov_bins[k])-1,)
tg_c += (np.digitize(cov, cov_bins[k])-1,)
... | [
"def",
"spike_threshold",
"(",
"sample_bin",
",",
"bin_thres",
",",
"covariates",
",",
"cov_bins",
",",
"spiketimes",
",",
"direct",
"=",
"False",
")",
":",
"units",
"=",
"len",
"(",
"spiketimes",
")",
"c_bins",
"=",
"(",
")",
"tg_c",
"=",
"(",
")",
"s... | Only include spikes that correspond to bins with sufficient occupancy time. | [
"Only",
"include",
"spikes",
"that",
"correspond",
"to",
"bins",
"with",
"sufficient",
"occupancy",
"time",
"."
] | [
"\"\"\"\n Only include spikes that correspond to bins with sufficient occupancy time. This is useful \n when using histogram models to avoid counting undersampled bins, which suffer from huge \n variance when computing the average firing rates in a histogram.\n \n :param float sample_bin: binning tim... | [
{
"param": "sample_bin",
"type": null
},
{
"param": "bin_thres",
"type": null
},
{
"param": "covariates",
"type": null
},
{
"param": "cov_bins",
"type": null
},
{
"param": "spiketimes",
"type": null
},
{
"param": "direct",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "sample_bin",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "bin_thres",
"type": null,
"docstring":... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | IPP_model | <not_specific> | def IPP_model(sample_bin, bin_thres, covariates, cov_bins, spiketimes, divide=True):
"""
Compute the occupancy-normalized activity histogram for neural data, corresponding to maximum
likelihood estimation of the rate in an inhomogeneous Poisson process.
:param float sample_bin: binning time
:p... |
Compute the occupancy-normalized activity histogram for neural data, corresponding to maximum
likelihood estimation of the rate in an inhomogeneous Poisson process.
:param float sample_bin: binning time
:param float bin_thres: only count bins with total occupancy time above bin_thres
:param l... | Compute the occupancy-normalized activity histogram for neural data, corresponding to maximum
likelihood estimation of the rate in an inhomogeneous Poisson process. | [
"Compute",
"the",
"occupancy",
"-",
"normalized",
"activity",
"histogram",
"for",
"neural",
"data",
"corresponding",
"to",
"maximum",
"likelihood",
"estimation",
"of",
"the",
"rate",
"in",
"an",
"inhomogeneous",
"Poisson",
"process",
"."
] | def IPP_model(sample_bin, bin_thres, covariates, cov_bins, spiketimes, divide=True):
units = len(spiketimes)
c_bins = ()
tg_c = ()
sg_c = [() for u in range(units)]
for k, cov in enumerate(covariates):
c_bins += (len(cov_bins[k])-1,)
tg_c += (np.digitize(cov, cov_bins[k])-1,)
... | [
"def",
"IPP_model",
"(",
"sample_bin",
",",
"bin_thres",
",",
"covariates",
",",
"cov_bins",
",",
"spiketimes",
",",
"divide",
"=",
"True",
")",
":",
"units",
"=",
"len",
"(",
"spiketimes",
")",
"c_bins",
"=",
"(",
")",
"tg_c",
"=",
"(",
")",
"sg_c",
... | Compute the occupancy-normalized activity histogram for neural data, corresponding to maximum
likelihood estimation of the rate in an inhomogeneous Poisson process. | [
"Compute",
"the",
"occupancy",
"-",
"normalized",
"activity",
"histogram",
"for",
"neural",
"data",
"corresponding",
"to",
"maximum",
"likelihood",
"estimation",
"of",
"the",
"rate",
"in",
"an",
"inhomogeneous",
"Poisson",
"process",
"."
] | [
"\"\"\"\n Compute the occupancy-normalized activity histogram for neural data, corresponding to maximum \n likelihood estimation of the rate in an inhomogeneous Poisson process.\n \n :param float sample_bin: binning time\n :param float bin_thres: only count bins with total occupancy time above bin_th... | [
{
"param": "sample_bin",
"type": null
},
{
"param": "bin_thres",
"type": null
},
{
"param": "covariates",
"type": null
},
{
"param": "cov_bins",
"type": null
},
{
"param": "spiketimes",
"type": null
},
{
"param": "divide",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "sample_bin",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "bin_thres",
"type": null,
"docstring":... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | spike_var_MI | <not_specific> | def spike_var_MI(rate, prob):
"""
Mutual information analysis for inhomogeneous Poisson process rate variable.
.. math::
I(x;\text{spike}) = \int p(x) \, \lambda(x) \, \log{\frac{\lambda(x)}{\langle \lambda \rangle}} \, \mathrm{d}x,
:param np.array rate: rate variables of s... |
Mutual information analysis for inhomogeneous Poisson process rate variable.
.. math::
I(x;\text{spike}) = \int p(x) \, \lambda(x) \, \log{\frac{\lambda(x)}{\langle \lambda \rangle}} \, \mathrm{d}x,
:param np.array rate: rate variables of shape (neurons, covariate_dims...)
... | Mutual information analysis for inhomogeneous Poisson process rate variable. | [
"Mutual",
"information",
"analysis",
"for",
"inhomogeneous",
"Poisson",
"process",
"rate",
"variable",
"."
] | def spike_var_MI(rate, prob):
units = rate.shape[0]
MI = np.empty(units)
logterm = rate/((rate*prob[np.newaxis, :]).sum(axis=tuple(k for k in range(1, len(rate.shape))), keepdims=True) + 1e-12)
logterm[logterm == 0] = 1.0
for u in range(units):
MI[u] = (prob * rate[u] * np.log2(logterm[u])... | [
"def",
"spike_var_MI",
"(",
"rate",
",",
"prob",
")",
":",
"units",
"=",
"rate",
".",
"shape",
"[",
"0",
"]",
"MI",
"=",
"np",
".",
"empty",
"(",
"units",
")",
"logterm",
"=",
"rate",
"/",
"(",
"(",
"rate",
"*",
"prob",
"[",
"np",
".",
"newaxis... | Mutual information analysis for inhomogeneous Poisson process rate variable. | [
"Mutual",
"information",
"analysis",
"for",
"inhomogeneous",
"Poisson",
"process",
"rate",
"variable",
"."
] | [
"\"\"\"\n Mutual information analysis for inhomogeneous Poisson process rate variable.\n \n .. math::\n I(x;\\text{spike}) = \\int p(x) \\, \\lambda(x) \\, \\log{\\frac{\\lambda(x)}{\\langle \\lambda \\rangle}} \\, \\mathrm{d}x,\n \n :param np.array rate: rate variables of shape (n... | [
{
"param": "rate",
"type": null
},
{
"param": "prob",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "rate",
"type": null,
"docstring": "rate variables of shape (neurons, covariate_dims...)",
"docstring_tokens": [
"rate",
"variables",
"of",
"shape",
"(",
"neurons",
"covar... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | KDE_behaviour | <not_specific> | def KDE_behaviour(bins_tuple, covariates, sm_size, L, smooth_modes, dev='cpu'):
"""
Kernel density estimation of the covariates, with Gaussian kernels.
"""
dim = len(bins_tuple)
assert (dim == len(covariates)) and (dim == len(sm_size)) and (dim == len(smooth_modes))
time_samples = covariates[0].... |
Kernel density estimation of the covariates, with Gaussian kernels.
| Kernel density estimation of the covariates, with Gaussian kernels. | [
"Kernel",
"density",
"estimation",
"of",
"the",
"covariates",
"with",
"Gaussian",
"kernels",
"."
] | def KDE_behaviour(bins_tuple, covariates, sm_size, L, smooth_modes, dev='cpu'):
dim = len(bins_tuple)
assert (dim == len(covariates)) and (dim == len(sm_size)) and (dim == len(smooth_modes))
time_samples = covariates[0].shape[0]
c_bins = ()
tg_c = ()
for k, cov in enumerate(covariates):
... | [
"def",
"KDE_behaviour",
"(",
"bins_tuple",
",",
"covariates",
",",
"sm_size",
",",
"L",
",",
"smooth_modes",
",",
"dev",
"=",
"'cpu'",
")",
":",
"dim",
"=",
"len",
"(",
"bins_tuple",
")",
"assert",
"(",
"dim",
"==",
"len",
"(",
"covariates",
")",
")",
... | Kernel density estimation of the covariates, with Gaussian kernels. | [
"Kernel",
"density",
"estimation",
"of",
"the",
"covariates",
"with",
"Gaussian",
"kernels",
"."
] | [
"\"\"\"\n Kernel density estimation of the covariates, with Gaussian kernels.\n \"\"\"",
"# get time spent in each bin",
"# normalize",
"# normalize"
] | [
{
"param": "bins_tuple",
"type": null
},
{
"param": "covariates",
"type": null
},
{
"param": "sm_size",
"type": null
},
{
"param": "L",
"type": null
},
{
"param": "smooth_modes",
"type": null
},
{
"param": "dev",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "bins_tuple",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "covariates",
"type": null,
"docstring": null,
"docstrin... |
0fe8e8ad09b6c834520ea8277f55a305a7350231 | davindicode/universal_count_model | neuroprob/utils/neural.py | [
"MIT"
] | Python | geometric_tuning | <not_specific> | def geometric_tuning(ori_rate, smth_rate, prob):
r"""
Compute coherence and sparsity related to the geometric properties of tuning curves.
"""
# Pearson r correlation
units = ori_rate.shape[0]
coherence = np.empty(units)
for u in range(units):
x_1 = ori_rate[u].flatten()
x_2 ... | r"""
Compute coherence and sparsity related to the geometric properties of tuning curves.
| r"""
Compute coherence and sparsity related to the geometric properties of tuning curves. | [
"r",
"\"",
"\"",
"\"",
"Compute",
"coherence",
"and",
"sparsity",
"related",
"to",
"the",
"geometric",
"properties",
"of",
"tuning",
"curves",
"."
] | def geometric_tuning(ori_rate, smth_rate, prob):
units = ori_rate.shape[0]
coherence = np.empty(units)
for u in range(units):
x_1 = ori_rate[u].flatten()
x_2 = smth_rate[u].flatten()
coherence[u] = np.dot(x_1 - x_1.mean(), x_2 - x_2.mean()) / len(x_1) / x_1.std() / x_2.std()
spar... | [
"def",
"geometric_tuning",
"(",
"ori_rate",
",",
"smth_rate",
",",
"prob",
")",
":",
"units",
"=",
"ori_rate",
".",
"shape",
"[",
"0",
"]",
"coherence",
"=",
"np",
".",
"empty",
"(",
"units",
")",
"for",
"u",
"in",
"range",
"(",
"units",
")",
":",
... | r"""
Compute coherence and sparsity related to the geometric properties of tuning curves. | [
"r",
"\"",
"\"",
"\"",
"Compute",
"coherence",
"and",
"sparsity",
"related",
"to",
"the",
"geometric",
"properties",
"of",
"tuning",
"curves",
"."
] | [
"r\"\"\"\n Compute coherence and sparsity related to the geometric properties of tuning curves.\n \"\"\"",
"# Pearson r correlation",
"# Computes the sparsity of the tuning"
] | [
{
"param": "ori_rate",
"type": null
},
{
"param": "smth_rate",
"type": null
},
{
"param": "prob",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ori_rate",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "smth_rate",
"type": null,
"docstring": null,
"docstring_t... |
b4c4b957ec9214bd64d17ff4842d79bbcdb8639f | davindicode/universal_count_model | scripts/models.py | [
"MIT"
] | Python | forward | <not_specific> | def forward(self, input):
"""
Input of shape (samplesxtime, dims)
"""
embed = torch.cat((torch.cos(input[:, :self.angle_dims]),
torch.sin(input[:, :self.angle_dims]),
input[:, self.angle_dims:]), dim=-1)
return self.net(embe... |
Input of shape (samplesxtime, dims)
| Input of shape (samplesxtime, dims) | [
"Input",
"of",
"shape",
"(",
"samplesxtime",
"dims",
")"
] | def forward(self, input):
embed = torch.cat((torch.cos(input[:, :self.angle_dims]),
torch.sin(input[:, :self.angle_dims]),
input[:, self.angle_dims:]), dim=-1)
return self.net(embed) | [
"def",
"forward",
"(",
"self",
",",
"input",
")",
":",
"embed",
"=",
"torch",
".",
"cat",
"(",
"(",
"torch",
".",
"cos",
"(",
"input",
"[",
":",
",",
":",
"self",
".",
"angle_dims",
"]",
")",
",",
"torch",
".",
"sin",
"(",
"input",
"[",
":",
... | Input of shape (samplesxtime, dims) | [
"Input",
"of",
"shape",
"(",
"samplesxtime",
"dims",
")"
] | [
"\"\"\"\n Input of shape (samplesxtime, dims)\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "input",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "input",
"type": null,
"docstring": null,
"docstring_tokens": ... |
b4c4b957ec9214bd64d17ff4842d79bbcdb8639f | davindicode/universal_count_model | scripts/models.py | [
"MIT"
] | Python | cov_used | <not_specific> | def cov_used(mode, behav_tuple):
"""
Create the used covariates list for different models
"""
resamples = behav_tuple[0].shape[0]
hd_t, w_t, s_t, x_t, y_t, time_t = behav_tuple
if mode == 'hd':
covariates = [hd_t]
elif mode == 'w':
covariates = [w_t]
... |
Create the used covariates list for different models
| Create the used covariates list for different models | [
"Create",
"the",
"used",
"covariates",
"list",
"for",
"different",
"models"
] | def cov_used(mode, behav_tuple):
resamples = behav_tuple[0].shape[0]
hd_t, w_t, s_t, x_t, y_t, time_t = behav_tuple
if mode == 'hd':
covariates = [hd_t]
elif mode == 'w':
covariates = [w_t]
elif mode == 'hd_w' or mode == 'hdTw':
covariates = [hd_t, w_t]
elif mode == 'hd_w... | [
"def",
"cov_used",
"(",
"mode",
",",
"behav_tuple",
")",
":",
"resamples",
"=",
"behav_tuple",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"hd_t",
",",
"w_t",
",",
"s_t",
",",
"x_t",
",",
"y_t",
",",
"time_t",
"=",
"behav_tuple",
"if",
"mode",
"=="... | Create the used covariates list for different models | [
"Create",
"the",
"used",
"covariates",
"list",
"for",
"different",
"models"
] | [
"\"\"\"\n Create the used covariates list for different models\n \"\"\"",
"#hd_t[:, None] np.random.rand(resamples, 1)*2*np.pi"
] | [
{
"param": "mode",
"type": null
},
{
"param": "behav_tuple",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "mode",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "behav_tuple",
"type": null,
"docstring": null,
"docstring_tok... |
64bf48534b4df4f1e1a3768a98a78cf3ee5d1c14 | davindicode/universal_count_model | neuroprob/nonparametrics.py | [
"MIT"
] | Python | compute_F | <not_specific> | def compute_F(self, XZ):
"""
Computes :math:`p(f(x)|u)` and also updating :math:`L_{uu}` matrix
model call uses :math:`L_{uu}` for the MVN, call after this function
Computes the mean and covariance matrix (or variance) of Gaussian Process
posterior on a test input data :... |
Computes :math:`p(f(x)|u)` and also updating :math:`L_{uu}` matrix
model call uses :math:`L_{uu}` for the MVN, call after this function
Computes the mean and covariance matrix (or variance) of Gaussian Process
posterior on a test input data :math:`X_{new}`:
.. ... |
Computes the mean and covariance matrix (or variance) of Gaussian Process
posterior on a test input data :math:`X_{new}`.
covariance_type is a flag to decide if we want to predict full covariance matrix or
just variance.
: The GP is centered around zero with fixed zero mean, but a learnable
mean is added after ... | [
"Computes",
"the",
"mean",
"and",
"covariance",
"matrix",
"(",
"or",
"variance",
")",
"of",
"Gaussian",
"Process",
"posterior",
"on",
"a",
"test",
"input",
"data",
":",
"math",
":",
"`",
"X_",
"{",
"new",
"}",
"`",
".",
"covariance_type",
"is",
"a",
"f... | def compute_F(self, XZ):
XZ = self._XZ(XZ)
if self.gp_mode == 'sparse' or self.gp_mode == 'sparse_MAP':
loc, cov, self.Luu = linalg.p_F_U(self.out_dims, XZ, self.Xu, self.kernel, self.u_loc, self.u_scale_tril,
cov_type=self.covariance_type, wh... | [
"def",
"compute_F",
"(",
"self",
",",
"XZ",
")",
":",
"XZ",
"=",
"self",
".",
"_XZ",
"(",
"XZ",
")",
"if",
"self",
".",
"gp_mode",
"==",
"'sparse'",
"or",
"self",
".",
"gp_mode",
"==",
"'sparse_MAP'",
":",
"loc",
",",
"cov",
",",
"self",
".",
"Lu... | Computes :math:`p(f(x)|u)` and also updating :math:`L_{uu}` matrix
model call uses :math:`L_{uu}` for the MVN, call after this function | [
"Computes",
":",
"math",
":",
"`",
"p",
"(",
"f",
"(",
"x",
")",
"|u",
")",
"`",
"and",
"also",
"updating",
":",
"math",
":",
"`",
"L_",
"{",
"uu",
"}",
"`",
"matrix",
"model",
"call",
"uses",
":",
"math",
":",
"`",
"L_",
"{",
"uu",
"}",
"`... | [
"\"\"\"\n Computes :math:`p(f(x)|u)` and also updating :math:`L_{uu}` matrix\n model call uses :math:`L_{uu}` for the MVN, call after this function\n \n Computes the mean and covariance matrix (or variance) of Gaussian Process\n posterior on a test input data :math:`X_{new}`:\n ... | [
{
"param": "self",
"type": null
},
{
"param": "XZ",
"type": null
}
] | {
"returns": [
{
"docstring": "loc and covariance matrix (or variance) of :math:`p(f^*(X_{new}))`",
"docstring_tokens": [
"loc",
"and",
"covariance",
"matrix",
"(",
"or",
"variance",
")",
"of",
":",
"math",
... |
fd3b136ba3fa6096facd6156e74e1e686a796799 | davindicode/universal_count_model | scripts/validation.py | [
"MIT"
] | Python | CMP_hdc | <not_specific> | def CMP_hdc(sample_bin, track_samples, covariates, neurons, trials=1):
"""
CMP with separate mu and nu tuning curves
"""
# Von Mises fields
angle_0 = np.linspace(0, 2*np.pi, neurons+1)[:-1]
beta = np.random.rand(neurons)*2.0 + 0.5
rate_0 = np.random.rand(neurons)*4.0+4.0
w = np.stack([np... |
CMP with separate mu and nu tuning curves
| CMP with separate mu and nu tuning curves | [
"CMP",
"with",
"separate",
"mu",
"and",
"nu",
"tuning",
"curves"
] | def CMP_hdc(sample_bin, track_samples, covariates, neurons, trials=1):
angle_0 = np.linspace(0, 2*np.pi, neurons+1)[:-1]
beta = np.random.rand(neurons)*2.0 + 0.5
rate_0 = np.random.rand(neurons)*4.0+4.0
w = np.stack([np.log(rate_0), beta*np.cos(angle_0), beta*np.sin(angle_0)]).T
neurons = w.shape[0... | [
"def",
"CMP_hdc",
"(",
"sample_bin",
",",
"track_samples",
",",
"covariates",
",",
"neurons",
",",
"trials",
"=",
"1",
")",
":",
"angle_0",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"2",
"*",
"np",
".",
"pi",
",",
"neurons",
"+",
"1",
")",
"[",
... | CMP with separate mu and nu tuning curves | [
"CMP",
"with",
"separate",
"mu",
"and",
"nu",
"tuning",
"curves"
] | [
"\"\"\"\n CMP with separate mu and nu tuning curves\n \"\"\"",
"# Von Mises fields",
"# beta, phi_0 for theta modulation",
"# Dispersion tuning curve",
"#angle_0 + 0.4*np.random.randn(neurons)#np.random.permutation(angle_0)",
"# beta, phi_0 for theta modulation",
"# sum for mu input",
"# CMP pro... | [
{
"param": "sample_bin",
"type": null
},
{
"param": "track_samples",
"type": null
},
{
"param": "covariates",
"type": null
},
{
"param": "neurons",
"type": null
},
{
"param": "trials",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "sample_bin",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "track_samples",
"type": null,
"docstring": null,
"docst... |
124ae383bf8855b25726d97e2a1fa1628baca482 | davindicode/universal_count_model | neuroprob/point_process.py | [
"MIT"
] | Python | gen_IRP | <not_specific> | def gen_IRP(interval_dist, rate, tbin, samples=100):
"""
Sample event times from an Inhomogenous Renewal Process with a given rate function
samples is an algorithm parameter, should be around the expect number of spikes
Assumes piecewise constant rate function
Samples intervals from :math:`q(\D... |
Sample event times from an Inhomogenous Renewal Process with a given rate function
samples is an algorithm parameter, should be around the expect number of spikes
Assumes piecewise constant rate function
Samples intervals from :math:`q(\Delta)`, parallelizes sampling
:param np.array rate:... | Sample event times from an Inhomogenous Renewal Process with a given rate function
samples is an algorithm parameter, should be around the expect number of spikes
Assumes piecewise constant rate function
Samples intervals from :math:`q(\Delta)`, parallelizes sampling | [
"Sample",
"event",
"times",
"from",
"an",
"Inhomogenous",
"Renewal",
"Process",
"with",
"a",
"given",
"rate",
"function",
"samples",
"is",
"an",
"algorithm",
"parameter",
"should",
"be",
"around",
"the",
"expect",
"number",
"of",
"spikes",
"Assumes",
"piecewise"... | def gen_IRP(interval_dist, rate, tbin, samples=100):
sim_samples = rate.shape[2]
N = rate.shape[1]
trials = rate.shape[0]
T = np.transpose(np.cumsum(rate, axis=-1), (2, 0, 1))*tbin
psT = 0
sT_cont = []
while True:
sT = psT + np.cumsum(interval_dist.sample((samples, trials,)), axis=... | [
"def",
"gen_IRP",
"(",
"interval_dist",
",",
"rate",
",",
"tbin",
",",
"samples",
"=",
"100",
")",
":",
"sim_samples",
"=",
"rate",
".",
"shape",
"[",
"2",
"]",
"N",
"=",
"rate",
".",
"shape",
"[",
"1",
"]",
"trials",
"=",
"rate",
".",
"shape",
"... | Sample event times from an Inhomogenous Renewal Process with a given rate function
samples is an algorithm parameter, should be around the expect number of spikes
Assumes piecewise constant rate function | [
"Sample",
"event",
"times",
"from",
"an",
"Inhomogenous",
"Renewal",
"Process",
"with",
"a",
"given",
"rate",
"function",
"samples",
"is",
"an",
"algorithm",
"parameter",
"should",
"be",
"around",
"the",
"expect",
"number",
"of",
"spikes",
"Assumes",
"piecewise"... | [
"\"\"\"\n Sample event times from an Inhomogenous Renewal Process with a given rate function\n samples is an algorithm parameter, should be around the expect number of spikes\n Assumes piecewise constant rate function\n \n Samples intervals from :math:`q(\\Delta)`, parallelizes sampling\n \n :p... | [
{
"param": "interval_dist",
"type": null
},
{
"param": "rate",
"type": null
},
{
"param": "tbin",
"type": null
},
{
"param": "samples",
"type": null
}
] | {
"returns": [
{
"docstring": "event times as integer indices of the rate array time dimension",
"docstring_tokens": [
"event",
"times",
"as",
"integer",
"indices",
"of",
"the",
"rate",
"array",
"time",
"dimension"... |
124ae383bf8855b25726d97e2a1fa1628baca482 | davindicode/universal_count_model | neuroprob/point_process.py | [
"MIT"
] | Python | gen_IBP | <not_specific> | def gen_IBP(intensity):
"""
Sample of the Inhomogenous Bernoulli Process
:param numpy.array intensity: intensity of the Bernoulli process at array index
:returns: sample of binary variables with same shape as intensity
:rtype: numpy.array
"""
b = Bernoulli(torch.tensor(intensity))
r... |
Sample of the Inhomogenous Bernoulli Process
:param numpy.array intensity: intensity of the Bernoulli process at array index
:returns: sample of binary variables with same shape as intensity
:rtype: numpy.array
| Sample of the Inhomogenous Bernoulli Process | [
"Sample",
"of",
"the",
"Inhomogenous",
"Bernoulli",
"Process"
] | def gen_IBP(intensity):
b = Bernoulli(torch.tensor(intensity))
return b.sample().numpy() | [
"def",
"gen_IBP",
"(",
"intensity",
")",
":",
"b",
"=",
"Bernoulli",
"(",
"torch",
".",
"tensor",
"(",
"intensity",
")",
")",
"return",
"b",
".",
"sample",
"(",
")",
".",
"numpy",
"(",
")"
] | Sample of the Inhomogenous Bernoulli Process | [
"Sample",
"of",
"the",
"Inhomogenous",
"Bernoulli",
"Process"
] | [
"\"\"\"\n Sample of the Inhomogenous Bernoulli Process\n \n :param numpy.array intensity: intensity of the Bernoulli process at array index\n :returns: sample of binary variables with same shape as intensity\n :rtype: numpy.array\n \"\"\""
] | [
{
"param": "intensity",
"type": null
}
] | {
"returns": [
{
"docstring": "sample of binary variables with same shape as intensity",
"docstring_tokens": [
"sample",
"of",
"binary",
"variables",
"with",
"same",
"shape",
"as",
"intensity"
],
"type": "numpy.array"
... |
124ae383bf8855b25726d97e2a1fa1628baca482 | davindicode/universal_count_model | neuroprob/point_process.py | [
"MIT"
] | Python | gen_CMP | <not_specific> | def gen_CMP(mu, nu, max_rejections=1000):
"""
Use rejection sampling to sample from the COM-Poisson count distribution. [1]
References:
[1] `Bayesian Inference, Model Selection and Likelihood Estimation using Fast Rejection
Sampling: The Conway-Maxwell-Poisson Distribution`, Alan Ben... |
Use rejection sampling to sample from the COM-Poisson count distribution. [1]
References:
[1] `Bayesian Inference, Model Selection and Likelihood Estimation using Fast Rejection
Sampling: The Conway-Maxwell-Poisson Distribution`, Alan Benson, Nial Friel (2021)
:param numpy.arra... | Use rejection sampling to sample from the COM-Poisson count distribution. [1]
References.
[1] `Bayesian Inference, Model Selection and Likelihood Estimation using Fast Rejection
Sampling: The Conway-Maxwell-Poisson Distribution`, Alan Benson, Nial Friel (2021) | [
"Use",
"rejection",
"sampling",
"to",
"sample",
"from",
"the",
"COM",
"-",
"Poisson",
"count",
"distribution",
".",
"[",
"1",
"]",
"References",
".",
"[",
"1",
"]",
"`",
"Bayesian",
"Inference",
"Model",
"Selection",
"and",
"Likelihood",
"Estimation",
"using... | def gen_CMP(mu, nu, max_rejections=1000):
trials = mu.shape[0]
neurons = mu.shape[1]
Y = np.empty(mu.shape)
for tr in range(trials):
for n in range(neurons):
mu_, nu_ = mu[tr, n, :], nu[tr, n, :]
k = 0
left_bins = np.where(nu_ >= 1)[0]
while len(le... | [
"def",
"gen_CMP",
"(",
"mu",
",",
"nu",
",",
"max_rejections",
"=",
"1000",
")",
":",
"trials",
"=",
"mu",
".",
"shape",
"[",
"0",
"]",
"neurons",
"=",
"mu",
".",
"shape",
"[",
"1",
"]",
"Y",
"=",
"np",
".",
"empty",
"(",
"mu",
".",
"shape",
... | Use rejection sampling to sample from the COM-Poisson count distribution. | [
"Use",
"rejection",
"sampling",
"to",
"sample",
"from",
"the",
"COM",
"-",
"Poisson",
"count",
"distribution",
"."
] | [
"\"\"\"\n Use rejection sampling to sample from the COM-Poisson count distribution. [1]\n \n References:\n \n [1] `Bayesian Inference, Model Selection and Likelihood Estimation using Fast Rejection \n Sampling: The Conway-Maxwell-Poisson Distribution`, Alan Benson, Nial Friel (2021)\n \n ... | [
{
"param": "mu",
"type": null
},
{
"param": "nu",
"type": null
},
{
"param": "max_rejections",
"type": null
}
] | {
"returns": [
{
"docstring": "inhomogeneous Poisson process sample",
"docstring_tokens": [
"inhomogeneous",
"Poisson",
"process",
"sample"
],
"type": "numpy.array"
}
],
"raises": [],
"params": [
{
"identifier": "mu",
"type": null,
... |
fd811e8e9e5ecdad1d68359084a8ef7ab7179c15 | davindicode/universal_count_model | neuroprob/parametrics.py | [
"MIT"
] | Python | compute_F | <not_specific> | def compute_F(self, XZ):
"""
The input to the ANN will be of shape (samples*timesteps, dims).
:param torch.tensor cov: covariates with shape (samples, timesteps, dims)
:returns: inner product with shape (samples, neurons, timesteps)
:rtype: torch.tensor
"""
... |
The input to the ANN will be of shape (samples*timesteps, dims).
:param torch.tensor cov: covariates with shape (samples, timesteps, dims)
:returns: inner product with shape (samples, neurons, timesteps)
:rtype: torch.tensor
| The input to the ANN will be of shape (samples*timesteps, dims). | [
"The",
"input",
"to",
"the",
"ANN",
"will",
"be",
"of",
"shape",
"(",
"samples",
"*",
"timesteps",
"dims",
")",
"."
] | def compute_F(self, XZ):
XZ = self._XZ(XZ)
incov = XZ.view(-1, XZ.shape[-1])
post_mu = self.mu_ANN(incov).view(*XZ.shape[:2], -1).permute(0, 2, 1)
if self.sigma_ANN is not None:
post_var = self.sigma_ANN(incov).view(*XZ.shape[:2], -1).permute(0, 2, 1)
else:
... | [
"def",
"compute_F",
"(",
"self",
",",
"XZ",
")",
":",
"XZ",
"=",
"self",
".",
"_XZ",
"(",
"XZ",
")",
"incov",
"=",
"XZ",
".",
"view",
"(",
"-",
"1",
",",
"XZ",
".",
"shape",
"[",
"-",
"1",
"]",
")",
"post_mu",
"=",
"self",
".",
"mu_ANN",
"(... | The input to the ANN will be of shape (samples*timesteps, dims). | [
"The",
"input",
"to",
"the",
"ANN",
"will",
"be",
"of",
"shape",
"(",
"samples",
"*",
"timesteps",
"dims",
")",
"."
] | [
"\"\"\"\n The input to the ANN will be of shape (samples*timesteps, dims).\n \n :param torch.tensor cov: covariates with shape (samples, timesteps, dims)\n :returns: inner product with shape (samples, neurons, timesteps)\n :rtype: torch.tensor\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "XZ",
"type": null
}
] | {
"returns": [
{
"docstring": "inner product with shape (samples, neurons, timesteps)",
"docstring_tokens": [
"inner",
"product",
"with",
"shape",
"(",
"samples",
"neurons",
"timesteps",
")"
],
"type": "torch.tensor"
... |
fd811e8e9e5ecdad1d68359084a8ef7ab7179c15 | davindicode/universal_count_model | neuroprob/parametrics.py | [
"MIT"
] | Python | forward_hmm | <not_specific> | def forward_hmm(self, nll, logp_0):
"""
Discrete variable, forward algorithm or message passing to marginalize efficiently.
:param torch.tensor nll: the objective function for each latent state of shape (state, time)
:param torch.tensor logp_0: the initial log probabilities of t... |
Discrete variable, forward algorithm or message passing to marginalize efficiently.
:param torch.tensor nll: the objective function for each latent state of shape (state, time)
:param torch.tensor logp_0: the initial log probabilities of the states at start of the chain
:return... | Discrete variable, forward algorithm or message passing to marginalize efficiently. | [
"Discrete",
"variable",
"forward",
"algorithm",
"or",
"message",
"passing",
"to",
"marginalize",
"efficiently",
"."
] | def forward_hmm(self, nll, logp_0):
trans_logp = torch.log(self.hmm_T + 1e-12)
for t in range(nll.shape[1]):
if t == 0:
logp = logp_0 - nll[:, 0]
else:
logp = (logp.unsqueeze(0) - nll[:, t].unsqueeze(1) + trans_logp).logsumexp(dim=1)
retur... | [
"def",
"forward_hmm",
"(",
"self",
",",
"nll",
",",
"logp_0",
")",
":",
"trans_logp",
"=",
"torch",
".",
"log",
"(",
"self",
".",
"hmm_T",
"+",
"1e-12",
")",
"for",
"t",
"in",
"range",
"(",
"nll",
".",
"shape",
"[",
"1",
"]",
")",
":",
"if",
"t... | Discrete variable, forward algorithm or message passing to marginalize efficiently. | [
"Discrete",
"variable",
"forward",
"algorithm",
"or",
"message",
"passing",
"to",
"marginalize",
"efficiently",
"."
] | [
"\"\"\"\n Discrete variable, forward algorithm or message passing to marginalize efficiently.\n \n :param torch.tensor nll: the objective function for each latent state of shape (state, time)\n :param torch.tensor logp_0: the initial log probabilities of the states at start of the chain\... | [
{
"param": "self",
"type": null
},
{
"param": "nll",
"type": null
},
{
"param": "logp_0",
"type": null
}
] | {
"returns": [
{
"docstring": "negative log probability after marginalizing hidden states and log p(z_t|X})",
"docstring_tokens": [
"negative",
"log",
"probability",
"after",
"marginalizing",
"hidden",
"states",
"and",
"log",
... |
fd811e8e9e5ecdad1d68359084a8ef7ab7179c15 | davindicode/universal_count_model | neuroprob/parametrics.py | [
"MIT"
] | Python | sample_hmm | <not_specific> | def sample_hmm(self, timesteps, logp_0, trials=1, cond_nll=None, viterbi=False):
"""
Sample from the HMM latent variables.
Forward-backward algorithm can perform smoothing estimate, filter is with forward algorithm.
:param torch.tensor cond_data: conditioning on data via nll -lo... |
Sample from the HMM latent variables.
Forward-backward algorithm can perform smoothing estimate, filter is with forward algorithm.
:param torch.tensor cond_data: conditioning on data via nll -log p(x|z), of shape (maps, time)
:param bool viterbi: return the MAP if true, otherwi... | Sample from the HMM latent variables.
Forward-backward algorithm can perform smoothing estimate, filter is with forward algorithm. | [
"Sample",
"from",
"the",
"HMM",
"latent",
"variables",
".",
"Forward",
"-",
"backward",
"algorithm",
"can",
"perform",
"smoothing",
"estimate",
"filter",
"is",
"with",
"forward",
"algorithm",
"."
] | def sample_hmm(self, timesteps, logp_0, trials=1, cond_nll=None, viterbi=False):
state = torch.empty((trials, timesteps), device=self.dummy.device).long()
cc = 0
iterator = tqdm(range(timesteps), leave=False)
for t in iterator:
if cond_nll is not None:
cc = c... | [
"def",
"sample_hmm",
"(",
"self",
",",
"timesteps",
",",
"logp_0",
",",
"trials",
"=",
"1",
",",
"cond_nll",
"=",
"None",
",",
"viterbi",
"=",
"False",
")",
":",
"state",
"=",
"torch",
".",
"empty",
"(",
"(",
"trials",
",",
"timesteps",
")",
",",
"... | Sample from the HMM latent variables. | [
"Sample",
"from",
"the",
"HMM",
"latent",
"variables",
"."
] | [
"\"\"\"\n Sample from the HMM latent variables.\n Forward-backward algorithm can perform smoothing estimate, filter is with forward algorithm.\n \n :param torch.tensor cond_data: conditioning on data via nll -log p(x|z), of shape (maps, time)\n :param bool viterbi: return the MAP ... | [
{
"param": "self",
"type": null
},
{
"param": "timesteps",
"type": null
},
{
"param": "logp_0",
"type": null
},
{
"param": "trials",
"type": null
},
{
"param": "cond_nll",
"type": null
},
{
"param": "viterbi",
"type": null
}
] | {
"returns": [
{
"docstring": "state tensor of shape (trials, time)",
"docstring_tokens": [
"state",
"tensor",
"of",
"shape",
"(",
"trials",
"time",
")"
],
"type": "torch.tensor"
}
],
"raises": [],
"params": [
{
... |
fd811e8e9e5ecdad1d68359084a8ef7ab7179c15 | davindicode/universal_count_model | neuroprob/parametrics.py | [
"MIT"
] | Python | objective | null | def objective(self, nll):
"""
Compute the marginalized likelihood over discrete states.
"""
if self.hmm_obs:
time = torch.arange(nll.shape[1]).to(state.device)
nll_term = nll[self.hmm_state[b].to(d_.device), time].sum()
else: # HMM inference
if... |
Compute the marginalized likelihood over discrete states.
| Compute the marginalized likelihood over discrete states. | [
"Compute",
"the",
"marginalized",
"likelihood",
"over",
"discrete",
"states",
"."
] | def objective(self, nll):
if self.hmm_obs:
time = torch.arange(nll.shape[1]).to(state.device)
nll_term = nll[self.hmm_state[b].to(d_.device), time].sum()
else:
if b == 0:
lp = self.logp_0
else:
lp = self.logp_hmm
... | [
"def",
"objective",
"(",
"self",
",",
"nll",
")",
":",
"if",
"self",
".",
"hmm_obs",
":",
"time",
"=",
"torch",
".",
"arange",
"(",
"nll",
".",
"shape",
"[",
"1",
"]",
")",
".",
"to",
"(",
"state",
".",
"device",
")",
"nll_term",
"=",
"nll",
"[... | Compute the marginalized likelihood over discrete states. | [
"Compute",
"the",
"marginalized",
"likelihood",
"over",
"discrete",
"states",
"."
] | [
"\"\"\"\n Compute the marginalized likelihood over discrete states.\n \"\"\"",
"# HMM inference",
"# continuation between batches with graph cut",
"# marginalize the latent z, direct ML fitting, E-step",
"# cut from computational graph",
"# Welch-Baum algorithm, M-step",
"# use MAP latents... | [
{
"param": "self",
"type": null
},
{
"param": "nll",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "nll",
"type": null,
"docstring": null,
"docstring_tokens": []... |
4e64fcbc8a1e888ed6c2d0f2a48db8eaa9c5aa1d | davindicode/universal_count_model | neuroprob/likelihoods.py | [
"MIT"
] | Python | sample_helper | <not_specific> | def sample_helper(self, h, b, neuron, samples):
"""
NLL helper function for sample evaluation. Note that spikes is batched including history
when the model uses history couplings, hence we sample the spike batches without the
history segments from this function.
"""
rat... |
NLL helper function for sample evaluation. Note that spikes is batched including history
when the model uses history couplings, hence we sample the spike batches without the
history segments from this function.
| NLL helper function for sample evaluation. Note that spikes is batched including history
when the model uses history couplings, hence we sample the spike batches without the
history segments from this function. | [
"NLL",
"helper",
"function",
"for",
"sample",
"evaluation",
".",
"Note",
"that",
"spikes",
"is",
"batched",
"including",
"history",
"when",
"the",
"model",
"uses",
"history",
"couplings",
"hence",
"we",
"sample",
"the",
"spike",
"batches",
"without",
"the",
"h... | def sample_helper(self, h, b, neuron, samples):
rates = self.f(h)
spikes = self.spikes[b][:, neuron, self.filter_len-1:].to(self.tbin.device)
if self.trials != 1 and samples > 1 and self.trials < h.shape[0]:
spikes = spikes.repeat(samples, 1, 1)
if self.inv_link == 'exp': ... | [
"def",
"sample_helper",
"(",
"self",
",",
"h",
",",
"b",
",",
"neuron",
",",
"samples",
")",
":",
"rates",
"=",
"self",
".",
"f",
"(",
"h",
")",
"spikes",
"=",
"self",
".",
"spikes",
"[",
"b",
"]",
"[",
":",
",",
"neuron",
",",
"self",
".",
"... | NLL helper function for sample evaluation. | [
"NLL",
"helper",
"function",
"for",
"sample",
"evaluation",
"."
] | [
"\"\"\"\n NLL helper function for sample evaluation. Note that spikes is batched including history \n when the model uses history couplings, hence we sample the spike batches without the \n history segments from this function.\n \"\"\"",
"# watch out for underflow or overflow here",
... | [
{
"param": "self",
"type": null
},
{
"param": "h",
"type": null
},
{
"param": "b",
"type": null
},
{
"param": "neuron",
"type": null
},
{
"param": "samples",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "h",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.