project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
THUNLP-MT/THUCC | bottle.py | Bottle.trigger_hook | trigger_hook | Trigger a hook and return a list of results. | [
"Trigger",
"a",
"hook",
"and",
"return",
"a",
"list",
"of",
"results."
] | def trigger_hook(self, __name, *args, **kwargs):
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]] | ['def', 'trigger_hook(self,', '__name,', '*args,', '**kwargs):', 'return', '[hook(*args,', '**kwargs)', 'for', 'hook', 'in', 'self._hooks[__name][:]]'] | 916,379 |
THUNLP-MT/THUCC | bottle.py | Bottle.close | close | Close the application and all installed plugins. | [
"Close",
"the",
"application",
"and",
"all",
"installed",
"plugins."
] | def close(self):
for plugin in self.plugins:
if hasattr(plugin, 'close'):
plugin.close() | ['def', 'close(self):', 'for', 'plugin', 'in', 'self.plugins:', 'if', 'hasattr(plugin,', "'close'):", 'plugin.close()'] | 916,386 |
THUNLP-MT/THUCC | bottle.py | Bottle.run | run | Calls :func:`run` with the same parameters. | [
"Calls",
":func:`run`",
"with",
"the",
"same",
"parameters."
] | def run(self, **kwargs):
run(self, **kwargs) | ['def', 'run(self,', '**kwargs):', 'run(self,', '**kwargs)'] | 916,387 |
THUNLP-MT/THUCC | bottle.py | Bottle.put | put | Equals :meth:`route` with a ``PUT`` method parameter. | [
"Equals",
":meth:`route`",
"with",
"a",
"``PUT``",
"method",
"parameter."
] | def put(self, path=None, method='PUT', **options):
return self.route(path, method, **options) | ['def', 'put(self,', 'path=None,', "method='PUT',", '**options):', 'return', 'self.route(path,', 'method,', '**options)'] | 916,392 |
THUNLP-MT/THUCC | bottle.py | Bottle.patch | patch | Equals :meth:`route` with a ``PATCH`` method parameter. | [
"Equals",
":meth:`route`",
"with",
"a",
"``PATCH``",
"method",
"parameter."
] | def patch(self, path=None, method='PATCH', **options):
return self.route(path, method, **options) | ['def', 'patch(self,', 'path=None,', "method='PATCH',", '**options):', 'return', 'self.route(path,', 'method,', '**options)'] | 916,394 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.app | app | Bottle application handling this request. | [
"Bottle",
"application",
"handling",
"this",
"request."
] | def app(self):
raise RuntimeError('This request is not connected to an application.') | ['def', 'app(self):', 'raise', "RuntimeError('This", 'request', 'is', 'not', 'connected', 'to', 'an', "application.')"] | 916,396 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.route | route | The bottle :class:`Route` object that matches this request. | [
"The",
"bottle",
":class:`Route`",
"object",
"that",
"matches",
"this",
"request."
] | def route(self):
raise RuntimeError('This request is not connected to a route.') | ['def', 'route(self):', 'raise', "RuntimeError('This", 'request', 'is', 'not', 'connected', 'to', 'a', "route.')"] | 916,397 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.url_args | url_args | The arguments extracted from the URL. | [
"The",
"arguments",
"extracted",
"from",
"the",
"URL."
] | def url_args(self):
raise RuntimeError('This request is not connected to a route.') | ['def', 'url_args(self):', 'raise', "RuntimeError('This", 'request', 'is', 'not', 'connected', 'to', 'a', "route.')"] | 916,398 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.headers | headers | A :class:`WSGIHeaderDict` that provides case-insensitive access to HTTP request headers. | [
"A",
":class:`WSGIHeaderDict`",
"that",
"provides",
"case-insensitive",
"access",
"to",
"HTTP",
"request",
"headers."
] | def headers(self):
return WSGIHeaderDict(self.environ) | ['def', 'headers(self):', 'return', 'WSGIHeaderDict(self.environ)'] | 916,401 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.chunked | chunked | True if Chunked transfer encoding was. | [
"True",
"if",
"Chunked",
"transfer",
"encoding",
"was."
] | def chunked(self):
return 'chunked' in self.environ.get('HTTP_TRANSFER_ENCODING', '').lower() | ['def', 'chunked(self):', 'return', "'chunked'", 'in', "self.environ.get('HTTP_TRANSFER_ENCODING',", "'').lower()"] | 916,411 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.fullpath | fullpath | Request path including :attr:`script_name` (if present). | [
"Request",
"path",
"including",
":attr:`script_name`",
"(if",
"present)."
] | def fullpath(self):
return urljoin(self.script_name, self.path.lstrip('/')) | ['def', 'fullpath(self):', 'return', 'urljoin(self.script_name,', "self.path.lstrip('/'))"] | 916,415 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.content_type | content_type | The Content-Type header as a lowercase-string (default: empty). | [
"The",
"Content-Type",
"header",
"as",
"a",
"lowercase-string",
"(default:",
"empty)."
] | def content_type(self):
return self.environ.get('CONTENT_TYPE', '').lower() | ['def', 'content_type(self):', 'return', "self.environ.get('CONTENT_TYPE',", "'').lower()"] | 916,420 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.copy | copy | Return a new :class:`Request` with a shallow :attr:`environ` copy. | [
"Return",
"a",
"new",
":class:`Request`",
"with",
"a",
"shallow",
":attr:`environ`",
"copy."
] | def copy(self):
return Request(self.environ.copy()) | ['def', 'copy(self):', 'return', 'Request(self.environ.copy())'] | 916,426 |
THUNLP-MT/THUCC | bottle.py | BaseResponse.copy | copy | Returns a copy of self. | [
"Returns",
"a",
"copy",
"of",
"self."
] | def copy(self, cls=None):
cls = cls or BaseResponse
assert issubclass(cls, BaseResponse)
copy = cls()
copy.status = self.status
copy._headers = dict(((k, v[:]) for (k, v) in self._headers.items()))
if self._cookies:
copy._cookies = SimpleCookie()
copy._cookies.load(self._cookies.... | ['def', 'copy(self,', 'cls=None):', 'cls', '=', 'cls', 'or', 'BaseResponse', 'assert', 'issubclass(cls,', 'BaseResponse)', 'copy', '=', 'cls()', 'copy.status', '=', 'self.status', 'copy._headers', '=', 'dict(((k,', 'v[:])', 'for', '(k,', 'v)', 'in', 'self._headers.items()))', 'if', 'self._cookies:', 'copy._cookies', '=... | 916,427 |
THUNLP-MT/THUCC | bottle.py | BaseResponse.headers | headers | An instance of :class:`HeaderDict`, a case-insensitive dict-like view on the response headers. | [
"An",
"instance",
"of",
":class:`HeaderDict`,",
"a",
"case-insensitive",
"dict-like",
"view",
"on",
"the",
"response",
"headers."
] | def headers(self):
hdict = HeaderDict()
hdict.dict = self._headers
return hdict | ['def', 'headers(self):', 'hdict', '=', 'HeaderDict()', 'hdict.dict', '=', 'self._headers', 'return', 'hdict'] | 916,430 |
THUNLP-MT/THUCC | bottle.py | BaseResponse.set_header | set_header | Create a new response header, replacing any previously defined headers with the same name. | [
"Create",
"a",
"new",
"response",
"header,",
"replacing",
"any",
"previously",
"defined",
"headers",
"with",
"the",
"same",
"name."
] | def set_header(self, name, value):
self._headers[_hkey(name)] = [value if isinstance(value, unicode) else str(value)] | ['def', 'set_header(self,', 'name,', 'value):', 'self._headers[_hkey(name)]', '=', '[value', 'if', 'isinstance(value,', 'unicode)', 'else', 'str(value)]'] | 916,432 |
THUNLP-MT/THUCC | bottle.py | BaseResponse.iter_headers | iter_headers | Yield (header, value) tuples, skipping headers that are not allowed with the current response status code. | [
"Yield",
"(header,",
"value)",
"tuples,",
"skipping",
"headers",
"that",
"are",
"not",
"allowed",
"with",
"the",
"current",
"response",
"status",
"code."
] | def iter_headers(self):
return self.headerlist | ['def', 'iter_headers(self):', 'return', 'self.headerlist'] | 916,434 |
THUNLP-MT/THUCC | bottle.py | BaseResponse.headerlist | headerlist | WSGI conform list of (header, value) tuples. | [
"WSGI",
"conform",
"list",
"of",
"(header,",
"value)",
"tuples."
] | def headerlist(self):
out = []
headers = list(self._headers.items())
if 'Content-Type' not in self._headers:
headers.append(('Content-Type', [self.default_content_type]))
if self._status_code in self.bad_headers:
bad_headers = self.bad_headers[self._status_code]
headers = [h for ... | ['def', 'headerlist(self):', 'out', '=', '[]', 'headers', '=', 'list(self._headers.items())', 'if', "'Content-Type'", 'not', 'in', 'self._headers:', "headers.append(('Content-Type',", '[self.default_content_type]))', 'if', 'self._status_code', 'in', 'self.bad_headers:', 'bad_headers', '=', 'self.bad_headers[self._statu... | 916,435 |
THUNLP-MT/THUCC | bottle.py | MultiDict.replace | replace | Replace the list of values with a single value. | [
"Replace",
"the",
"list",
"of",
"values",
"with",
"a",
"single",
"value."
] | def replace(self, key, value):
self.dict[key] = [value] | ['def', 'replace(self,', 'key,', 'value):', 'self.dict[key]', '=', '[value]'] | 916,440 |
THUNLP-MT/THUCC | bottle.py | FormsDict.getunicode | getunicode | Return the value as a unicode string, or the default. | [
"Return",
"the",
"value",
"as",
"a",
"unicode",
"string,",
"or",
"the",
"default."
] | def getunicode(self, name, default=None, encoding=None):
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default | ['def', 'getunicode(self,', 'name,', 'default=None,', 'encoding=None):', 'try:', 'return', 'self._fix(self[name],', 'encoding)', 'except', '(UnicodeError,', 'KeyError):', 'return', 'default'] | 916,443 |
THUNLP-MT/THUCC | bottle.py | ConfigDict.meta_get | meta_get | Return the value of a meta field for a key. | [
"Return",
"the",
"value",
"of",
"a",
"meta",
"field",
"for",
"a",
"key."
] | def meta_get(self, key, metafield, default=None):
return self._meta.get(key, {}).get(metafield, default) | ['def', 'meta_get(self,', 'key,', 'metafield,', 'default=None):', 'return', 'self._meta.get(key,', '{}).get(metafield,', 'default)'] | 916,448 |
THUNLP-MT/THUCC | bottle.py | ConfigDict.meta_list | meta_list | Return an iterable of meta field names defined for a key. | [
"Return",
"an",
"iterable",
"of",
"meta",
"field",
"names",
"defined",
"for",
"a",
"key."
] | def meta_list(self, key):
return self._meta.get(key, {}).keys() | ['def', 'meta_list(self,', 'key):', 'return', 'self._meta.get(key,', '{}).keys()'] | 916,450 |
THUNLP-MT/THUCC | bottle.py | ResourceManager.open | open | Find a resource and return a file object, or raise IOError. | [
"Find",
"a",
"resource",
"and",
"return",
"a",
"file",
"object,",
"or",
"raise",
"IOError."
] | def open(self, name, mode='r', *args, **kwargs):
fname = self.lookup(name)
if not fname:
raise IOError('Resource %r not found.' % name)
return self.opener(fname, *args, mode=mode, **kwargs) | ['def', 'open(self,', 'name,', "mode='r',", '*args,', '**kwargs):', 'fname', '=', 'self.lookup(name)', 'if', 'not', 'fname:', 'raise', "IOError('Resource", '%r', 'not', "found.'", '%', 'name)', 'return', 'self.opener(fname,', '*args,', 'mode=mode,', '**kwargs)'] | 916,454 |
THUNLP-MT/THUCC | bottle.py | SimpleTemplate.render | render | Render the template using keyword arguments as local variables. | [
"Render",
"the",
"template",
"using",
"keyword",
"arguments",
"as",
"local",
"variables."
] | def render(self, *args, **kwargs):
env = {}
stdout = []
for dictarg in args:
env.update(dictarg)
env.update(kwargs)
self.execute(stdout, env)
return ''.join(stdout) | ['def', 'render(self,', '*args,', '**kwargs):', 'env', '=', '{}', 'stdout', '=', '[]', 'for', 'dictarg', 'in', 'args:', 'env.update(dictarg)', 'env.update(kwargs)', 'self.execute(stdout,', 'env)', 'return', "''.join(stdout)"] | 916,461 |
THUNLP-MT/THUCC | bottle.py | parse_date | parse_date | Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. | [
"Parse",
"rfc1123,",
"rfc850",
"and",
"asctime",
"timestamps",
"and",
"return",
"UTC",
"epoch."
] | def parse_date(ims):
try:
ts = email.utils.parsedate_tz(ims)
return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
except (TypeError, ValueError, IndexError, OverflowError):
return None | ['def', 'parse_date(ims):', 'try:', 'ts', '=', 'email.utils.parsedate_tz(ims)', 'return', 'time.mktime(ts[:8]', '+', '(0,))', '-', '(ts[9]', 'or', '0)', '-', 'time.timezone', 'except', '(TypeError,', 'ValueError,', 'IndexError,', 'OverflowError):', 'return', 'None'] | 916,468 |
THUNLP-MT/THUCC | bottle.py | Router.match | match | Return a (target, url_args) tuple or raise HTTPError(400/404/405). | [
"Return",
"a",
"(target,",
"url_args)",
"tuple",
"or",
"raise",
"HTTPError(400/404/405)."
] | def match(self, environ):
verb = environ['REQUEST_METHOD'].upper()
path = environ['PATH_INFO'] or '/'
if verb == 'HEAD':
methods = ['PROXY', verb, 'GET', 'ANY']
else:
methods = ['PROXY', verb, 'ANY']
for method in methods:
if method in self.static and path in self.static[meth... | ['def', 'match(self,', 'environ):', 'verb', '=', "environ['REQUEST_METHOD'].upper()", 'path', '=', "environ['PATH_INFO']", 'or', "'/'", 'if', 'verb', '==', "'HEAD':", 'methods', '=', "['PROXY',", 'verb,', "'GET',", "'ANY']", 'else:', 'methods', '=', "['PROXY',", 'verb,', "'ANY']", 'for', 'method', 'in', 'methods:', 'if... | 916,488 |
THUNLP-MT/THUCC | bottle.py | BaseRequest.query_string | query_string | The raw :attr:`query` part of the URL (everything in between ``?`` and ``#``) as a string. | [
"The",
"raw",
":attr:`query`",
"part",
"of",
"the",
"URL",
"(everything",
"in",
"between",
"``?``",
"and",
"``#``)",
"as",
"a",
"string."
] | def query_string(self):
return self.environ.get('QUERY_STRING', '') | ['def', 'query_string(self):', 'return', "self.environ.get('QUERY_STRING',", "'')"] | 916,535 |
rfeinman/tictactoe-reinforcement-learning | play.py | GameLearning.beginTeaching | beginTeaching | Loop through game iterations with a teaching agent. | [
"Loop",
"through",
"game",
"iterations",
"with",
"a",
"teaching",
"agent."
] | def beginTeaching(self, episodes):
teacher = Teacher()
while self.games_played < episodes:
game = Game(self.agent, teacher=teacher)
game.start()
self.games_played += 1
if self.games_played % 1000 == 0:
print('Games played: %i' % self.games_played)
self.agent.save(... | ['def', 'beginTeaching(self,', 'episodes):', 'teacher', '=', 'Teacher()', 'while', 'self.games_played', '<', 'episodes:', 'game', '=', 'Game(self.agent,', 'teacher=teacher)', 'game.start()', 'self.games_played', '+=', '1', 'if', 'self.games_played', '%', '1000', '==', '0:', "print('Games", 'played:', "%i'", '%', 'self.... | 916,602 |
rfeinman/tictactoe-reinforcement-learning | game.py | Game.playerMove | playerMove | Querry player for a move and update the board accordingly. | [
"Querry",
"player",
"for",
"a",
"move",
"and",
"update",
"the",
"board",
"accordingly."
] | def playerMove(self):
if self.teacher is not None:
action = self.teacher.makeMove(self.board)
self.board[action[0]][action[1]] = 'X'
else:
printBoard(self.board)
while True:
move = input('Your move! Please select a row and column from 0-2 in the format row,col: ')
... | ['def', 'playerMove(self):', 'if', 'self.teacher', 'is', 'not', 'None:', 'action', '=', 'self.teacher.makeMove(self.board)', 'self.board[action[0]][action[1]]', '=', "'X'", 'else:', 'printBoard(self.board)', 'while', 'True:', 'move', '=', "input('Your", 'move!', 'Please', 'select', 'a', 'row', 'and', 'column', 'from', ... | 916,610 |
rfeinman/tictactoe-reinforcement-learning | game.py | Game.agentMove | agentMove | Update board according to agent's move. | [
"Update",
"board",
"according",
"to",
"agent's",
"move."
] | def agentMove(self, action):
self.board[action[0]][action[1]] = 'O' | ['def', 'agentMove(self,', 'action):', 'self.board[action[0]][action[1]]', '=', "'O'"] | 916,611 |
rfeinman/tictactoe-reinforcement-learning | teacher.py | Teacher.win | win | If we have two in a row and the 3rd is available, take it. | [
"If",
"we",
"have",
"two",
"in",
"a",
"row",
"and",
"the",
"3rd",
"is",
"available,",
"take",
"it."
] | def win(self, board, key='X'):
a = [board[0][0], board[1][1], board[2][2]]
b = [board[0][2], board[1][1], board[2][0]]
if a.count('-') == 1 and a.count(key) == 2:
ind = a.index('-')
return (ind, ind)
elif b.count('-') == 1 and b.count(key) == 2:
ind = b.index('-')
if ind ... | ['def', 'win(self,', 'board,', "key='X'):", 'a', '=', '[board[0][0],', 'board[1][1],', 'board[2][2]]', 'b', '=', '[board[0][2],', 'board[1][1],', 'board[2][0]]', 'if', "a.count('-')", '==', '1', 'and', 'a.count(key)', '==', '2:', 'ind', '=', "a.index('-')", 'return', '(ind,', 'ind)', 'elif', "b.count('-')", '==', '1', ... | 916,617 |
rfeinman/tictactoe-reinforcement-learning | teacher.py | Teacher.blockWin | blockWin | Block the opponent if she has a win available. | [
"Block",
"the",
"opponent",
"if",
"she",
"has",
"a",
"win",
"available."
] | def blockWin(self, board):
return self.win(board, key='O') | ['def', 'blockWin(self,', 'board):', 'return', 'self.win(board,', "key='O')"] | 916,618 |
rfeinman/tictactoe-reinforcement-learning | teacher.py | Teacher.fork | fork | Create a fork opportunity such that we have 2 threats to win. | [
"Create",
"a",
"fork",
"opportunity",
"such",
"that",
"we",
"have",
"2",
"threats",
"to",
"win."
] | def fork(self, board):
if board[1][0] == 'X' and board[0][1] == 'X':
if board[0][0] == '-' and board[2][0] == '-' and (board[0][2] == '-'):
return (0, 0)
elif board[1][1] == '-' and board[2][1] == '-' and (board[1][2] == '-'):
return (1, 1)
elif board[1][0] == 'X' and boa... | ['def', 'fork(self,', 'board):', 'if', 'board[1][0]', '==', "'X'", 'and', 'board[0][1]', '==', "'X':", 'if', 'board[0][0]', '==', "'-'", 'and', 'board[2][0]', '==', "'-'", 'and', '(board[0][2]', '==', "'-'):", 'return', '(0,', '0)', 'elif', 'board[1][1]', '==', "'-'", 'and', 'board[2][1]', '==', "'-'", 'and', '(board[1... | 916,619 |
rfeinman/tictactoe-reinforcement-learning | teacher.py | Teacher.blockFork | blockFork | Block the opponents fork if she has one available. | [
"Block",
"the",
"opponents",
"fork",
"if",
"she",
"has",
"one",
"available."
] | def blockFork(self, board):
corners = [board[0][0], board[2][0], board[0][2], board[2][2]]
if board[1][0] == 'O' and board[0][1] == 'O':
if board[0][0] == '-' and board[2][0] == '-' and (board[0][2] == '-'):
return (0, 0)
elif board[1][1] == '-' and board[2][1] == '-' and (board[1][2... | ['def', 'blockFork(self,', 'board):', 'corners', '=', '[board[0][0],', 'board[2][0],', 'board[0][2],', 'board[2][2]]', 'if', 'board[1][0]', '==', "'O'", 'and', 'board[0][1]', '==', "'O':", 'if', 'board[0][0]', '==', "'-'", 'and', 'board[2][0]', '==', "'-'", 'and', '(board[0][2]', '==', "'-'):", 'return', '(0,', '0)', '... | 916,620 |
rfeinman/tictactoe-reinforcement-learning | teacher.py | Teacher.center | center | Pick the center if it is available. | [
"Pick",
"the",
"center",
"if",
"it",
"is",
"available."
] | def center(self, board):
if board[1][1] == '-':
return (1, 1)
return None | ['def', 'center(self,', 'board):', 'if', 'board[1][1]', '==', "'-':", 'return', '(1,', '1)', 'return', 'None'] | 916,621 |
rfeinman/tictactoe-reinforcement-learning | teacher.py | Teacher.randomMove | randomMove | Chose a random move from the available options. | [
"Chose",
"a",
"random",
"move",
"from",
"the",
"available",
"options."
] | def randomMove(self, board):
possibles = []
for i in range(3):
for j in range(3):
if board[i][j] == '-':
possibles += [(i, j)]
return possibles[random.randint(0, len(possibles) - 1)] | ['def', 'randomMove(self,', 'board):', 'possibles', '=', '[]', 'for', 'i', 'in', 'range(3):', 'for', 'j', 'in', 'range(3):', 'if', 'board[i][j]', '==', "'-':", 'possibles', '+=', '[(i,', 'j)]', 'return', 'possibles[random.randint(0,', 'len(possibles)', '-', '1)]'] | 916,624 |
ltbringer/tic_tac_toe | agent.py | Agent.get_serious | get_serious | Quit exploring states and start exploiting Use this if you want to play with the agent. | [
"Quit",
"exploring",
"states",
"and",
"start",
"exploiting",
"Use",
"this",
"if",
"you",
"want",
"to",
"play",
"with",
"the",
"agent."
] | def get_serious(self):
self.exploration_rate = 0 | ['def', 'get_serious(self):', 'self.exploration_rate', '=', '0'] | 916,627 |
dbolya/tide | functions.py | find_first | find_first | Finds the index of the first instance of true in a vector or None if not found. | [
"Finds",
"the",
"index",
"of",
"the",
"first",
"instance",
"of",
"true",
"in",
"a",
"vector",
"or",
"None",
"if",
"not",
"found."
] | def find_first(arr: np.array) -> int:
if len(arr) == 0:
return None
idx = arr.argmax()
if idx == 0 and (not arr[0]):
return None
return idx | ['def', 'find_first(arr:', 'np.array)', '->', 'int:', 'if', 'len(arr)', '==', '0:', 'return', 'None', 'idx', '=', 'arr.argmax()', 'if', 'idx', '==', '0', 'and', '(not', 'arr[0]):', 'return', 'None', 'return', 'idx'] | 916,656 |
dbolya/tide | functions.py | polyToBox | polyToBox | Converts a polygon in COCO lists of lists format to a bounding box in [x, y, w, h]. | [
"Converts",
"a",
"polygon",
"in",
"COCO",
"lists",
"of",
"lists",
"format",
"to",
"a",
"bounding",
"box",
"in",
"[x,",
"y,",
"w,",
"h]."
] | def polyToBox(poly: list):
xmin = 10000000000.0
xmax = -10000000000.0
ymin = 10000000000.0
ymax = -10000000000.0
for poly_comp in poly:
for i in range(len(poly_comp) // 2):
x = poly_comp[2 * i + 0]
y = poly_comp[2 * i + 1]
xmin = min(x, xmin)
x... | ['def', 'polyToBox(poly:', 'list):', 'xmin', '=', '10000000000.0', 'xmax', '=', '-10000000000.0', 'ymin', '=', '10000000000.0', 'ymax', '=', '-10000000000.0', 'for', 'poly_comp', 'in', 'poly:', 'for', 'i', 'in', 'range(len(poly_comp)', '//', '2):', 'x', '=', 'poly_comp[2', '*', 'i', '+', '0]', 'y', '=', 'poly_comp[2', ... | 916,658 |
ADLab3Ds/TiG-BEV | loading.py | PointToMultiViewDepthWithGTIndex.points2map | points2map | Use points to calculate the depth value and the foreground target index of the input image. | [
"Use",
"points",
"to",
"calculate",
"the",
"depth",
"value",
"and",
"the",
"foreground",
"target",
"index",
"of",
"the",
"input",
"image."
] | def points2map(self, points_label, points, height, width):
(height, width) = (height // self.downsample, width // self.downsample)
depth_map = torch.zeros((height, width), dtype=torch.float32)
coor = torch.round(points[:, :2] / self.downsample)
depth = points[:, 2]
kept1 = (coor[:, 0] >= 0) & (coor[... | ['def', 'points2map(self,', 'points_label,', 'points,', 'height,', 'width):', '(height,', 'width)', '=', '(height', '//', 'self.downsample,', 'width', '//', 'self.downsample)', 'depth_map', '=', 'torch.zeros((height,', 'width),', 'dtype=torch.float32)', 'coor', '=', 'torch.round(points[:,', ':2]', '/', 'self.downsample... | 916,973 |
Obs01ete/tiled_segmentation | train.py | InferenceDataset.compose | compose | Gathers tiles back together into one big image. | [
"Gathers",
"tiles",
"back",
"together",
"into",
"one",
"big",
"image."
] | def compose(self, tile_list):
big_img = np.zeros(self._padded_img.shape[:2], dtype=np.uint8)
for (index, tile_img) in enumerate(tile_list):
ih = index // self._tile_reso_hw[1]
iw = index % self._tile_reso_hw[1]
off_h = ih * self._strides_hw[0]
off_w = iw * self._strides_hw[1]
... | ['def', 'compose(self,', 'tile_list):', 'big_img', '=', 'np.zeros(self._padded_img.shape[:2],', 'dtype=np.uint8)', 'for', '(index,', 'tile_img)', 'in', 'enumerate(tile_list):', 'ih', '=', 'index', '//', 'self._tile_reso_hw[1]', 'iw', '=', 'index', '%', 'self._tile_reso_hw[1]', 'off_h', '=', 'ih', '*', 'self._strides_hw... | 917,215 |
flaviagiammarino/time-gan-tensorflow | losses.py | mean_squared_error | mean_squared_error | Mean squared error, used for calculating the supervised loss and the reconstruction loss. | [
"Mean",
"squared",
"error,",
"used",
"for",
"calculating",
"the",
"supervised",
"loss",
"and",
"the",
"reconstruction",
"loss."
] | def mean_squared_error(y_true, y_pred):
loss = tf.keras.losses.mean_squared_error(y_true=tf.expand_dims(y_true, axis=-1), y_pred=tf.expand_dims(y_pred, axis=-1))
return tf.reduce_mean(tf.reduce_sum(loss, axis=-1)) | ['def', 'mean_squared_error(y_true,', 'y_pred):', 'loss', '=', 'tf.keras.losses.mean_squared_error(y_true=tf.expand_dims(y_true,', 'axis=-1),', 'y_pred=tf.expand_dims(y_pred,', 'axis=-1))', 'return', 'tf.reduce_mean(tf.reduce_sum(loss,', 'axis=-1))'] | 917,223 |
flaviagiammarino/time-gan-tensorflow | model.py | TimeGAN.simulate | simulate | Simulate the time series. | [
"Simulate",
"the",
"time",
"series."
] | def simulate(self, samples):
z = simulator(samples=samples // self.timesteps, timesteps=self.timesteps, features=self.features)
x_sim = self.autoencoder_model.get_layer('decoder')(self.generator_model(z))
x_sim = sequences_to_time_series(x_sim.numpy())
x_sim = self.mu + self.sigma * x_sim
return x_s... | ['def', 'simulate(self,', 'samples):', 'z', '=', 'simulator(samples=samples', '//', 'self.timesteps,', 'timesteps=self.timesteps,', 'features=self.features)', 'x_sim', '=', "self.autoencoder_model.get_layer('decoder')(self.generator_model(z))", 'x_sim', '=', 'sequences_to_time_series(x_sim.numpy())', 'x_sim', '=', 'sel... | 917,226 |
flaviagiammarino/time-gan-tensorflow | modules.py | encoder_embedder | encoder_embedder | Encoder embedder, takes as input the actual sequences and returns the actual embeddings. | [
"Encoder",
"embedder,",
"takes",
"as",
"input",
"the",
"actual",
"sequences",
"and",
"returns",
"the",
"actual",
"embeddings."
] | def encoder_embedder(timesteps, features, hidden_dim, num_layers):
x = tf.keras.layers.Input(shape=(timesteps, features))
for _ in range(num_layers):
e = tf.keras.layers.GRU(units=hidden_dim, return_sequences=True)(x if _ == 0 else e)
return tf.keras.models.Model(x, e, name='encoder_embedder') | ['def', 'encoder_embedder(timesteps,', 'features,', 'hidden_dim,', 'num_layers):', 'x', '=', 'tf.keras.layers.Input(shape=(timesteps,', 'features))', 'for', '_', 'in', 'range(num_layers):', 'e', '=', 'tf.keras.layers.GRU(units=hidden_dim,', 'return_sequences=True)(x', 'if', '_', '==', '0', 'else', 'e)', 'return', 'tf.k... | 917,227 |
flaviagiammarino/time-gan-tensorflow | modules.py | encoder | encoder | Encoder, takes as input the actual embeddings and returns the actual latent vector. | [
"Encoder,",
"takes",
"as",
"input",
"the",
"actual",
"embeddings",
"and",
"returns",
"the",
"actual",
"latent",
"vector."
] | def encoder(timesteps, hidden_dim, num_layers):
e = tf.keras.layers.Input(shape=(timesteps, hidden_dim))
for _ in range(num_layers):
h = tf.keras.layers.GRU(units=hidden_dim, return_sequences=True)(e if _ == 0 else h)
h = tf.keras.layers.Dense(units=hidden_dim)(h)
return tf.keras.models.Model(e,... | ['def', 'encoder(timesteps,', 'hidden_dim,', 'num_layers):', 'e', '=', 'tf.keras.layers.Input(shape=(timesteps,', 'hidden_dim))', 'for', '_', 'in', 'range(num_layers):', 'h', '=', 'tf.keras.layers.GRU(units=hidden_dim,', 'return_sequences=True)(e', 'if', '_', '==', '0', 'else', 'h)', 'h', '=', 'tf.keras.layers.Dense(un... | 917,228 |
flaviagiammarino/time-gan-tensorflow | modules.py | decoder | decoder | Decoder, takes as input the actual or synthetic latent vector and returns the reconstructed or synthetic sequences. | [
"Decoder,",
"takes",
"as",
"input",
"the",
"actual",
"or",
"synthetic",
"latent",
"vector",
"and",
"returns",
"the",
"reconstructed",
"or",
"synthetic",
"sequences."
] | def decoder(timesteps, features, hidden_dim, num_layers):
h = tf.keras.layers.Input(shape=(timesteps, hidden_dim))
for _ in range(num_layers):
y = tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(units=hidden_dim, activation='relu'))(h if _ == 0 else y)
y = tf.keras.layers.Dense(units=features)... | ['def', 'decoder(timesteps,', 'features,', 'hidden_dim,', 'num_layers):', 'h', '=', 'tf.keras.layers.Input(shape=(timesteps,', 'hidden_dim))', 'for', '_', 'in', 'range(num_layers):', 'y', '=', 'tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(units=hidden_dim,', "activation='relu'))(h", 'if', '_', '==', '0', 'else... | 917,229 |
flaviagiammarino/time-gan-tensorflow | modules.py | generator_embedder | generator_embedder | Generator embedder, takes as input the synthetic sequences and returns the synthetic embeddings. | [
"Generator",
"embedder,",
"takes",
"as",
"input",
"the",
"synthetic",
"sequences",
"and",
"returns",
"the",
"synthetic",
"embeddings."
] | def generator_embedder(timesteps, features, hidden_dim, num_layers):
z = tf.keras.layers.Input(shape=(timesteps, features))
for _ in range(num_layers):
e = tf.keras.layers.GRU(units=hidden_dim, return_sequences=True)(z if _ == 0 else e)
return tf.keras.models.Model(z, e, name='generator_embedder') | ['def', 'generator_embedder(timesteps,', 'features,', 'hidden_dim,', 'num_layers):', 'z', '=', 'tf.keras.layers.Input(shape=(timesteps,', 'features))', 'for', '_', 'in', 'range(num_layers):', 'e', '=', 'tf.keras.layers.GRU(units=hidden_dim,', 'return_sequences=True)(z', 'if', '_', '==', '0', 'else', 'e)', 'return', 'tf... | 917,230 |
flaviagiammarino/time-gan-tensorflow | modules.py | generator | generator | Generator, takes as input the synthetic embeddings and returns the synthetic latent vector. | [
"Generator,",
"takes",
"as",
"input",
"the",
"synthetic",
"embeddings",
"and",
"returns",
"the",
"synthetic",
"latent",
"vector."
] | def generator(timesteps, hidden_dim, num_layers):
e = tf.keras.layers.Input(shape=(timesteps, hidden_dim))
for _ in range(num_layers):
h = tf.keras.layers.GRU(units=hidden_dim, return_sequences=True)(e if _ == 0 else h)
h = tf.keras.layers.Dense(units=hidden_dim)(h)
return tf.keras.models.Model(... | ['def', 'generator(timesteps,', 'hidden_dim,', 'num_layers):', 'e', '=', 'tf.keras.layers.Input(shape=(timesteps,', 'hidden_dim))', 'for', '_', 'in', 'range(num_layers):', 'h', '=', 'tf.keras.layers.GRU(units=hidden_dim,', 'return_sequences=True)(e', 'if', '_', '==', '0', 'else', 'h)', 'h', '=', 'tf.keras.layers.Dense(... | 917,231 |
flaviagiammarino/time-gan-tensorflow | modules.py | discriminator | discriminator | Discriminator, takes as input the actual or synthetic embedding or latent vector and returns the log-odds. | [
"Discriminator,",
"takes",
"as",
"input",
"the",
"actual",
"or",
"synthetic",
"embedding",
"or",
"latent",
"vector",
"and",
"returns",
"the",
"log-odds."
] | def discriminator(timesteps, hidden_dim, num_layers):
h = tf.keras.layers.Input(shape=(timesteps, hidden_dim))
for _ in range(num_layers):
p = tf.keras.layers.Bidirectional(tf.keras.layers.GRU(units=hidden_dim, return_sequences=True if _ < num_layers - 1 else False))(h if _ == 0 else p)
p = tf.keras... | ['def', 'discriminator(timesteps,', 'hidden_dim,', 'num_layers):', 'h', '=', 'tf.keras.layers.Input(shape=(timesteps,', 'hidden_dim))', 'for', '_', 'in', 'range(num_layers):', 'p', '=', 'tf.keras.layers.Bidirectional(tf.keras.layers.GRU(units=hidden_dim,', 'return_sequences=True', 'if', '_', '<', 'num_layers', '-', '1'... | 917,232 |
flaviagiammarino/time-gan-tensorflow | modules.py | simulator | simulator | Simulator, generates synthetic sequences from a Wiener process. | [
"Simulator,",
"generates",
"synthetic",
"sequences",
"from",
"a",
"Wiener",
"process."
] | def simulator(samples, timesteps, features):
z = tf.random.normal(mean=0, stddev=1, shape=(samples * timesteps, features), dtype=tf.float32)
z = tf.cumsum(z, axis=0) / tf.sqrt(tf.cast(samples * timesteps, dtype=tf.float32))
z = (z - tf.reduce_mean(z, axis=0)) / tf.math.reduce_std(z, axis=0)
z = tf.resha... | ['def', 'simulator(samples,', 'timesteps,', 'features):', 'z', '=', 'tf.random.normal(mean=0,', 'stddev=1,', 'shape=(samples', '*', 'timesteps,', 'features),', 'dtype=tf.float32)', 'z', '=', 'tf.cumsum(z,', 'axis=0)', '/', 'tf.sqrt(tf.cast(samples', '*', 'timesteps,', 'dtype=tf.float32))', 'z', '=', '(z', '-', 'tf.redu... | 917,233 |
flaviagiammarino/time-gan-tensorflow | plots.py | plot | plot | Plot the actual, reconstructed and synthetic time series. | [
"Plot",
"the",
"actual,",
"reconstructed",
"and",
"synthetic",
"time",
"series."
] | def plot(actual, reconstructed, synthetic):
fig = make_subplots(subplot_titles=['Actual', 'Reconstructed', 'Synthetic'], vertical_spacing=0.15, rows=3, cols=1)
fig.update_layout(plot_bgcolor='white', paper_bgcolor='white', margin=dict(t=60, b=60, l=30, r=30), font=dict(color='#1b1f24', size=8), legend=dict(trac... | ['def', 'plot(actual,', 'reconstructed,', 'synthetic):', 'fig', '=', "make_subplots(subplot_titles=['Actual',", "'Reconstructed',", "'Synthetic'],", 'vertical_spacing=0.15,', 'rows=3,', 'cols=1)', "fig.update_layout(plot_bgcolor='white',", "paper_bgcolor='white',", 'margin=dict(t=60,', 'b=60,', 'l=30,', 'r=30),', "font... | 917,234 |
flaviagiammarino/time-gan-tensorflow | utils.py | sequences_to_time_series | sequences_to_time_series | Reshape the sequences as time series. | [
"Reshape",
"the",
"sequences",
"as",
"time",
"series."
] | def sequences_to_time_series(sequences):
time_series = np.concatenate([sequence for sequence in sequences], axis=0)
return time_series | ['def', 'sequences_to_time_series(sequences):', 'time_series', '=', 'np.concatenate([sequence', 'for', 'sequence', 'in', 'sequences],', 'axis=0)', 'return', 'time_series'] | 917,236 |
ChefLiutao/Time-series-forecasting-via-deep-reinforcement- | DDPG_agent.py | DDPG.build_Actor1 | build_Actor1 | Building Current Actor network. | [
"Building",
"Current",
"Actor",
"network."
] | def build_Actor1(self):
with tf.variable_scope('Actor/Current'):
w_init = tf.random_normal_initializer(0, 0.1)
b_init = tf.constant_initializer(0.1)
w1 = tf.get_variable(name='w1', shape=[self.n_features, self.n_actor_hidden], dtype=tf.float32, initializer=w_init, trainable=True)
b1 ... | ['def', 'build_Actor1(self):', 'with', "tf.variable_scope('Actor/Current'):", 'w_init', '=', 'tf.random_normal_initializer(0,', '0.1)', 'b_init', '=', 'tf.constant_initializer(0.1)', 'w1', '=', "tf.get_variable(name='w1',", 'shape=[self.n_features,', 'self.n_actor_hidden],', 'dtype=tf.float32,', 'initializer=w_init,', ... | 917,361 |
ChefLiutao/Time-series-forecasting-via-deep-reinforcement- | DDPG_agent.py | DDPG.build_Actor2 | build_Actor2 | Building Target Actor network. | [
"Building",
"Target",
"Actor",
"network."
] | def build_Actor2(self):
with tf.variable_scope('Actor/Target'):
w_init = tf.random_normal_initializer(0, 0.1)
b_init = tf.constant_initializer(0.1)
w1 = tf.get_variable('w1', shape=[self.n_features, self.n_actor_hidden], dtype=tf.float32, initializer=w_init, trainable=False)
b1 = tf.... | ['def', 'build_Actor2(self):', 'with', "tf.variable_scope('Actor/Target'):", 'w_init', '=', 'tf.random_normal_initializer(0,', '0.1)', 'b_init', '=', 'tf.constant_initializer(0.1)', 'w1', '=', "tf.get_variable('w1',", 'shape=[self.n_features,', 'self.n_actor_hidden],', 'dtype=tf.float32,', 'initializer=w_init,', 'train... | 917,362 |
ChefLiutao/Time-series-forecasting-via-deep-reinforcement- | DDPG_agent.py | DDPG.build_Critic1 | build_Critic1 | Building Current Critic network. | [
"Building",
"Current",
"Critic",
"network."
] | def build_Critic1(self):
with tf.variable_scope('Critic/Current'):
w_init = tf.random_normal_initializer(0, 0.1)
b_init = tf.constant_initializer(0.1)
w1_s = tf.get_variable('w1_s', shape=[self.n_features, self.n_critic_hidden], dtype=tf.float32, initializer=w_init, trainable=True)
w... | ['def', 'build_Critic1(self):', 'with', "tf.variable_scope('Critic/Current'):", 'w_init', '=', 'tf.random_normal_initializer(0,', '0.1)', 'b_init', '=', 'tf.constant_initializer(0.1)', 'w1_s', '=', "tf.get_variable('w1_s',", 'shape=[self.n_features,', 'self.n_critic_hidden],', 'dtype=tf.float32,', 'initializer=w_init,'... | 917,363 |
ChefLiutao/Time-series-forecasting-via-deep-reinforcement- | DDPG_agent.py | DDPG.build_Critic2 | build_Critic2 | Building Target Critic network. | [
"Building",
"Target",
"Critic",
"network."
] | def build_Critic2(self):
with tf.variable_scope('Critic/Target'):
w_init = tf.random_normal_initializer(0, 0.1)
b_init = tf.constant_initializer(0.1)
w1_s = tf.get_variable('w1_s', shape=[self.n_features, self.n_critic_hidden], dtype=tf.float32, initializer=w_init, trainable=False)
w... | ['def', 'build_Critic2(self):', 'with', "tf.variable_scope('Critic/Target'):", 'w_init', '=', 'tf.random_normal_initializer(0,', '0.1)', 'b_init', '=', 'tf.constant_initializer(0.1)', 'w1_s', '=', "tf.get_variable('w1_s',", 'shape=[self.n_features,', 'self.n_critic_hidden],', 'dtype=tf.float32,', 'initializer=w_init,',... | 917,364 |
zzw-zwzhang/TimeGAN-pytorch | data.py | real_data_loading | real_data_loading | Load and preprocess real-world datasets. | [
"Load",
"and",
"preprocess",
"real-world",
"datasets."
] | def real_data_loading(data_name, seq_len):
assert data_name in ['stock', 'energy']
if data_name == 'stock':
ori_data = np.loadtxt(dirname(dirname(abspath(__file__))) + '/data/stock_data.csv', delimiter=',', skiprows=1)
elif data_name == 'energy':
ori_data = np.loadtxt(dirname(dirname(abspath... | ['def', 'real_data_loading(data_name,', 'seq_len):', 'assert', 'data_name', 'in', "['stock',", "'energy']", 'if', 'data_name', '==', "'stock':", 'ori_data', '=', 'np.loadtxt(dirname(dirname(abspath(__file__)))', '+', "'/data/stock_data.csv',", "delimiter=',',", 'skiprows=1)', 'elif', 'data_name', '==', "'energy':", 'or... | 917,372 |
zzw-zwzhang/TimeGAN-pytorch | timegan.py | BaseModel.save_weights | save_weights | Save net weights for the current epoch. | [
"Save",
"net",
"weights",
"for",
"the",
"current",
"epoch."
] | def save_weights(self, epoch):
weight_dir = os.path.join(self.opt.outf, self.opt.name, 'train', 'weights')
if not os.path.exists(weight_dir):
os.makedirs(weight_dir)
torch.save({'epoch': epoch + 1, 'state_dict': self.nete.state_dict()}, '%s/netE.pth' % weight_dir)
torch.save({'epoch': epoch + 1,... | ['def', 'save_weights(self,', 'epoch):', 'weight_dir', '=', 'os.path.join(self.opt.outf,', 'self.opt.name,', "'train',", "'weights')", 'if', 'not', 'os.path.exists(weight_dir):', 'os.makedirs(weight_dir)', "torch.save({'epoch':", 'epoch', '+', '1,', "'state_dict':", 'self.nete.state_dict()},', "'%s/netE.pth'", '%', 'we... | 917,374 |
zzw-zwzhang/TimeGAN-pytorch | timegan.py | TimeGAN.optimize_params_er | optimize_params_er | Forwardpass, Loss Computation and Backwardpass. | [
"Forwardpass,",
"Loss",
"Computation",
"and",
"Backwardpass."
] | def optimize_params_er(self):
self.forward_er()
self.optimizer_e.zero_grad()
self.optimizer_r.zero_grad()
self.backward_er()
self.optimizer_e.step()
self.optimizer_r.step() | ['def', 'optimize_params_er(self):', 'self.forward_er()', 'self.optimizer_e.zero_grad()', 'self.optimizer_r.zero_grad()', 'self.backward_er()', 'self.optimizer_e.step()', 'self.optimizer_r.step()'] | 917,388 |
zzw-zwzhang/TimeGAN-pytorch | predictive_metrics.py | predictive_score_metrics | predictive_score_metrics | Report the performance of Post-hoc RNN one-step ahead prediction. | [
"Report",
"the",
"performance",
"of",
"Post-hoc",
"RNN",
"one-step",
"ahead",
"prediction."
] | def predictive_score_metrics(ori_data, generated_data):
tf1.reset_default_graph()
(no, seq_len, dim) = np.asarray(ori_data).shape
(ori_time, ori_max_seq_len) = extract_time(ori_data)
(generated_time, generated_max_seq_len) = extract_time(ori_data)
max_seq_len = max([ori_max_seq_len, generated_max_se... | ['def', 'predictive_score_metrics(ori_data,', 'generated_data):', 'tf1.reset_default_graph()', '(no,', 'seq_len,', 'dim)', '=', 'np.asarray(ori_data).shape', '(ori_time,', 'ori_max_seq_len)', '=', 'extract_time(ori_data)', '(generated_time,', 'generated_max_seq_len)', '=', 'extract_time(ori_data)', 'max_seq_len', '=', ... | 917,394 |
zzw-zwzhang/TimeGAN-pytorch | visualization_metrics.py | visualization | visualization | Using PCA or tSNE for generated and original data visualization. | [
"Using",
"PCA",
"or",
"tSNE",
"for",
"generated",
"and",
"original",
"data",
"visualization."
] | def visualization(ori_data, generated_data, analysis):
anal_sample_no = min([1000, len(ori_data)])
idx = np.random.permutation(len(ori_data))[:anal_sample_no]
ori_data = np.asarray(ori_data)
generated_data = np.asarray(generated_data)
ori_data = ori_data[idx]
generated_data = generated_data[idx]... | ['def', 'visualization(ori_data,', 'generated_data,', 'analysis):', 'anal_sample_no', '=', 'min([1000,', 'len(ori_data)])', 'idx', '=', 'np.random.permutation(len(ori_data))[:anal_sample_no]', 'ori_data', '=', 'np.asarray(ori_data)', 'generated_data', '=', 'np.asarray(generated_data)', 'ori_data', '=', 'ori_data[idx]',... | 917,395 |
Feaxure-fresh/TL-Bearing-Fault-Diagnosis | CWRU.py | data_load | data_load | This function is mainly used to generate test data and training data. | [
"This",
"function",
"is",
"mainly",
"used",
"to",
"generate",
"test",
"data",
"and",
"training",
"data."
] | def data_load(item_path, label, data, lab):
datanumber = os.path.basename(item_path).split('.')[0]
if eval(datanumber) < 100:
realaxis = 'X0' + datanumber + axis[0]
else:
realaxis = 'X' + datanumber + axis[0]
fl = loadmat(item_path)[realaxis]
(start, end) = (0, signal_size)
while... | ['def', 'data_load(item_path,', 'label,', 'data,', 'lab):', 'datanumber', '=', "os.path.basename(item_path).split('.')[0]", 'if', 'eval(datanumber)', '<', '100:', 'realaxis', '=', "'X0'", '+', 'datanumber', '+', 'axis[0]', 'else:', 'realaxis', '=', "'X'", '+', 'datanumber', '+', 'axis[0]', 'fl', '=', 'loadmat(item_path... | 917,466 |
alon-albalak/TLiDB | metrics.py | StringMetric.unanswerable_phrases | unanswerable_phrases | List of phrases to ignore when computing the metric. | [
"List",
"of",
"phrases",
"to",
"ignore",
"when",
"computing",
"the",
"metric."
] | def unanswerable_phrases(self):
return self._unanswerable_phrases | ['def', 'unanswerable_phrases(self):', 'return', 'self._unanswerable_phrases'] | 917,569 |
openvinotoolkit/training_extensions | cls_utils.py | get_multihead_class_info | get_multihead_class_info | Get multihead info by label schema. | [
"Get",
"multihead",
"info",
"by",
"label",
"schema."
] | def get_multihead_class_info(label_schema: LabelSchemaEntity):
all_groups = label_schema.get_groups(include_empty=False)
all_groups_str = []
for g in all_groups:
group_labels_str = [lbl.name for lbl in g.labels]
all_groups_str.append(group_labels_str)
single_label_groups = [g for g in al... | ['def', 'get_multihead_class_info(label_schema:', 'LabelSchemaEntity):', 'all_groups', '=', 'label_schema.get_groups(include_empty=False)', 'all_groups_str', '=', '[]', 'for', 'g', 'in', 'all_groups:', 'group_labels_str', '=', '[lbl.name', 'for', 'lbl', 'in', 'g.labels]', 'all_groups_str.append(group_labels_str)', 'sin... | 917,757 |
openvinotoolkit/training_extensions | cls_utils.py | get_cls_inferencer_configuration | get_cls_inferencer_configuration | Get classification inferencer config by label schema. | [
"Get",
"classification",
"inferencer",
"config",
"by",
"label",
"schema."
] | def get_cls_inferencer_configuration(label_schema: LabelSchemaEntity):
multilabel = len(label_schema.get_groups(False)) > 1 and len(label_schema.get_groups(False)) == len(label_schema.get_labels(include_empty=False))
hierarchical = not multilabel and len(label_schema.get_groups(False)) > 1
multihead_class_i... | ['def', 'get_cls_inferencer_configuration(label_schema:', 'LabelSchemaEntity):', 'multilabel', '=', 'len(label_schema.get_groups(False))', '>', '1', 'and', 'len(label_schema.get_groups(False))', '==', 'len(label_schema.get_labels(include_empty=False))', 'hierarchical', '=', 'not', 'multilabel', 'and', 'len(label_schema... | 917,758 |
openvinotoolkit/training_extensions | cls_utils.py | get_hierarchical_label_list | get_hierarchical_label_list | Return hierarchical labels list which is adjusted to model outputs classes. | [
"Return",
"hierarchical",
"labels",
"list",
"which",
"is",
"adjusted",
"to",
"model",
"outputs",
"classes."
] | def get_hierarchical_label_list(hierarchical_info, labels):
hierarchical_labels = []
for head_idx in range(hierarchical_info['num_multiclass_heads']):
(logits_begin, logits_end) = hierarchical_info['head_idx_to_logits_range'][str(head_idx)]
for logit in range(0, logits_end - logits_begin):
... | ['def', 'get_hierarchical_label_list(hierarchical_info,', 'labels):', 'hierarchical_labels', '=', '[]', 'for', 'head_idx', 'in', "range(hierarchical_info['num_multiclass_heads']):", '(logits_begin,', 'logits_end)', '=', "hierarchical_info['head_idx_to_logits_range'][str(head_idx)]", 'for', 'logit', 'in', 'range(0,', 'l... | 917,760 |
openvinotoolkit/training_extensions | convert_coco_to_multilabel.py | coco_to_datumaro_multilabel | coco_to_datumaro_multilabel | Convert coco dataset to datumaro multi-label format. | [
"Convert",
"coco",
"dataset",
"to",
"datumaro",
"multi-label",
"format."
] | def coco_to_datumaro_multilabel(ann_file_path: str, data_root_dir: str, output: str, test_mode: bool=False):
coco_dataset = CocoDataset(ann_file=ann_file_path, data_root=data_root_dir, classes=None, test_mode=test_mode, with_mask=False)
overall_classes: List = coco_dataset.get_classes()
for class_name in ov... | ['def', 'coco_to_datumaro_multilabel(ann_file_path:', 'str,', 'data_root_dir:', 'str,', 'output:', 'str,', 'test_mode:', 'bool=False):', 'coco_dataset', '=', 'CocoDataset(ann_file=ann_file_path,', 'data_root=data_root_dir,', 'classes=None,', 'test_mode=test_mode,', 'with_mask=False)', 'overall_classes:', 'List', '=', '... | 917,761 |
openvinotoolkit/training_extensions | clsincr_mixin.py | IncrConfigurerMixin.configure_task_adapt_hook | configure_task_adapt_hook | Add TaskAdaptHook for sampler. | [
"Add",
"TaskAdaptHook",
"for",
"sampler."
] | def configure_task_adapt_hook(self, cfg):
sampler_flag = self.is_incremental()
update_or_add_custom_hook(cfg, ConfigDict(type='TaskAdaptHook', src_classes=self.org_model_classes, dst_classes=self.model_classes, model_type=cfg.model.type, sampler_flag=sampler_flag, sampler_type=self.get_sampler_type(cfg), effici... | ['def', 'configure_task_adapt_hook(self,', 'cfg):', 'sampler_flag', '=', 'self.is_incremental()', 'update_or_add_custom_hook(cfg,', "ConfigDict(type='TaskAdaptHook',", 'src_classes=self.org_model_classes,', 'dst_classes=self.model_classes,', 'model_type=cfg.model.type,', 'sampler_flag=sampler_flag,', 'sampler_type=self... | 917,764 |
openvinotoolkit/training_extensions | clsincr_mixin.py | IncrConfigurerMixin.is_incremental | is_incremental | Return whether current model classes is increased from original model classes. | [
"Return",
"whether",
"current",
"model",
"classes",
"is",
"increased",
"from",
"original",
"model",
"classes."
] | def is_incremental(self) -> bool:
return len(set(self.org_model_classes) & set(self.model_classes)) > 0 and set(self.org_model_classes) != set(self.model_classes) | ['def', 'is_incremental(self)', '->', 'bool:', 'return', 'len(set(self.org_model_classes)', '&', 'set(self.model_classes))', '>', '0', 'and', 'set(self.org_model_classes)', '!=', 'set(self.model_classes)'] | 917,765 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure | configure | Create MMCV-consumable config from given inputs. | [
"Create",
"MMCV-consumable",
"config",
"from",
"given",
"inputs."
] | def configure(self, cfg: Config, data_pipeline_path: str, hyperparams_from_otx: ConfigDict, model_ckpt_path: str, data_cfg: Config, ir_options: Optional[Config]=None, data_classes: Optional[List[str]]=None, model_classes: Optional[List[str]]=None, input_size: InputSizePreset=InputSizePreset.DEFAULT, **kwargs: Dict[Any,... | ['def', 'configure(self,', 'cfg:', 'Config,', 'data_pipeline_path:', 'str,', 'hyperparams_from_otx:', 'ConfigDict,', 'model_ckpt_path:', 'str,', 'data_cfg:', 'Config,', 'ir_options:', 'Optional[Config]=None,', 'data_classes:', 'Optional[List[str]]=None,', 'model_classes:', 'Optional[List[str]]=None,', 'input_size:', 'I... | 917,766 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.merge_configs | merge_configs | Merge model cfg, data_pipeline cfg, data_cfg, and hyperparams from otx cli. | [
"Merge",
"model",
"cfg,",
"data_pipeline",
"cfg,",
"data_cfg,",
"and",
"hyperparams",
"from",
"otx",
"cli."
] | def merge_configs(self, cfg, data_cfg, data_pipeline_path, hyperparams_from_otx, **kwargs):
logger.debug('merge_configs()')
if os.path.isfile(data_pipeline_path):
data_pipeline_cfg = Config.fromfile(data_pipeline_path)
cfg.merge_from_dict(data_pipeline_cfg)
else:
raise FileNotFoundEr... | ['def', 'merge_configs(self,', 'cfg,', 'data_cfg,', 'data_pipeline_path,', 'hyperparams_from_otx,', '**kwargs):', "logger.debug('merge_configs()')", 'if', 'os.path.isfile(data_pipeline_path):', 'data_pipeline_cfg', '=', 'Config.fromfile(data_pipeline_path)', 'cfg.merge_from_dict(data_pipeline_cfg)', 'else:', 'raise', "... | 917,767 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_device | configure_device | Setting device for training and inference. | [
"Setting",
"device",
"for",
"training",
"and",
"inference."
] | def configure_device(self, cfg):
cfg.distributed = False
if torch.distributed.is_initialized():
cfg.gpu_ids = [int(os.environ['LOCAL_RANK'])]
if self.training:
cfg.distributed = True
self.configure_distributed(cfg)
elif 'gpu_ids' not in cfg:
cfg.gpu_ids = rang... | ['def', 'configure_device(self,', 'cfg):', 'cfg.distributed', '=', 'False', 'if', 'torch.distributed.is_initialized():', 'cfg.gpu_ids', '=', "[int(os.environ['LOCAL_RANK'])]", 'if', 'self.training:', 'cfg.distributed', '=', 'True', 'self.configure_distributed(cfg)', 'elif', "'gpu_ids'", 'not', 'in', 'cfg:', 'cfg.gpu_id... | 917,772 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_recipe | configure_recipe | Configuration training recipe settings. | [
"Configuration",
"training",
"recipe",
"settings."
] | def configure_recipe(self, cfg, **kwargs):
patch_adaptive_interval_training(cfg)
patch_early_stopping(cfg)
self.configure_fp16(cfg) | ['def', 'configure_recipe(self,', 'cfg,', '**kwargs):', 'patch_adaptive_interval_training(cfg)', 'patch_early_stopping(cfg)', 'self.configure_fp16(cfg)'] | 917,776 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_fp16 | configure_fp16 | Configure Fp16OptimizerHook and Fp16SAMOptimizerHook. | [
"Configure",
"Fp16OptimizerHook",
"and",
"Fp16SAMOptimizerHook."
] | def configure_fp16(cfg: Config):
fp16_config = cfg.pop('fp16', None)
if fp16_config is not None:
if torch.cuda.is_available():
optim_type = cfg.optimizer_config.get('type', 'OptimizerHook')
opts: Dict[str, Any] = dict(distributed=getattr(cfg, 'distributed', False), **fp16_config)... | ['def', 'configure_fp16(cfg:', 'Config):', 'fp16_config', '=', "cfg.pop('fp16',", 'None)', 'if', 'fp16_config', 'is', 'not', 'None:', 'if', 'torch.cuda.is_available():', 'optim_type', '=', "cfg.optimizer_config.get('type',", "'OptimizerHook')", 'opts:', 'Dict[str,', 'Any]', '=', 'dict(distributed=getattr(cfg,', "'distr... | 917,777 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_model | configure_model | Configuration model config settings. | [
"Configuration",
"model",
"config",
"settings."
] | def configure_model(self, cfg, data_classes, model_classes, ir_options, **kwargs):
self.model_classes = model_classes
self.data_classes = data_classes
if data_classes is not None:
train_data_cfg = self.get_subset_data_cfg(cfg, 'train')
train_data_cfg['data_classes'] = data_classes
ne... | ['def', 'configure_model(self,', 'cfg,', 'data_classes,', 'model_classes,', 'ir_options,', '**kwargs):', 'self.model_classes', '=', 'model_classes', 'self.data_classes', '=', 'data_classes', 'if', 'data_classes', 'is', 'not', 'None:', 'train_data_cfg', '=', 'self.get_subset_data_cfg(cfg,', "'train')", "train_data_cfg['... | 917,778 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_classes | configure_classes | Patch classes for model and dataset. | [
"Patch",
"classes",
"for",
"model",
"and",
"dataset."
] | def configure_classes(self, cfg):
org_model_classes = self.get_model_classes(cfg)
data_classes = self.get_data_classes(cfg)
if self.task_adapt_op == 'REPLACE':
if len(data_classes) == 0:
model_classes = org_model_classes.copy()
else:
model_classes = data_classes.copy(... | ['def', 'configure_classes(self,', 'cfg):', 'org_model_classes', '=', 'self.get_model_classes(cfg)', 'data_classes', '=', 'self.get_data_classes(cfg)', 'if', 'self.task_adapt_op', '==', "'REPLACE':", 'if', 'len(data_classes)', '==', '0:', 'model_classes', '=', 'org_model_classes.copy()', 'else:', 'model_classes', '=', ... | 917,781 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_compat_cfg | configure_compat_cfg | Modify config to keep the compatibility. | [
"Modify",
"config",
"to",
"keep",
"the",
"compatibility."
] | def configure_compat_cfg(cfg: Config):
global_dataloader_cfg: Dict[str, str] = {}
global_dataloader_cfg.update({k: cfg.data.pop(k) for k in list(cfg.data.keys()) if k not in ['train', 'val', 'test', 'unlabeled', 'train_dataloader', 'val_dataloader', 'test_dataloader', 'unlabeled_dataloader']})
for subset in... | ['def', 'configure_compat_cfg(cfg:', 'Config):', 'global_dataloader_cfg:', 'Dict[str,', 'str]', '=', '{}', 'global_dataloader_cfg.update({k:', 'cfg.data.pop(k)', 'for', 'k', 'in', 'list(cfg.data.keys())', 'if', 'k', 'not', 'in', "['train',", "'val',", "'test',", "'unlabeled',", "'train_dataloader',", "'val_dataloader',... | 917,782 |
openvinotoolkit/training_extensions | configurer.py | BaseConfigurer.configure_hooks | configure_hooks | Add or update hooks. | [
"Add",
"or",
"update",
"hooks."
] | def configure_hooks(self, cfg):
if 'custom_hooks' in self.override_configs:
override_custom_hooks = self.override_configs.pop('custom_hooks')
for override_custom_hook in override_custom_hooks:
update_or_add_custom_hook(cfg, ConfigDict(override_custom_hook))
if len(self.override_confi... | ['def', 'configure_hooks(self,', 'cfg):', 'if', "'custom_hooks'", 'in', 'self.override_configs:', 'override_custom_hooks', '=', "self.override_configs.pop('custom_hooks')", 'for', 'override_custom_hook', 'in', 'override_custom_hooks:', 'update_or_add_custom_hook(cfg,', 'ConfigDict(override_custom_hook))', 'if', 'len(se... | 917,783 |
openvinotoolkit/training_extensions | runner.py | IterBasedRunnerWithCancel.main_loop | main_loop | Main loop function in IterBasedRunnerWithCancel. | [
"Main",
"loop",
"function",
"in",
"IterBasedRunnerWithCancel."
] | def main_loop(self, workflow: List[tuple], iter_loaders: Sequence[IterLoader], **kwargs):
while self.iter < self._max_iters:
for (i, flow) in enumerate(workflow):
self._inner_iter = 0
(mode, iters) = flow
if not isinstance(mode, str) or not hasattr(self, mode):
... | ['def', 'main_loop(self,', 'workflow:', 'List[tuple],', 'iter_loaders:', 'Sequence[IterLoader],', '**kwargs):', 'while', 'self.iter', '<', 'self._max_iters:', 'for', '(i,', 'flow)', 'in', 'enumerate(workflow):', 'self._inner_iter', '=', '0', '(mode,', 'iters)', '=', 'flow', 'if', 'not', 'isinstance(mode,', 'str)', 'or'... | 917,789 |
openvinotoolkit/training_extensions | runner.py | IterBasedRunnerWithCancel.run | run | Function of main run. | [
"Function",
"of",
"main",
"run."
] | def run(self, data_loaders: Sequence[DataLoader], workflow: List[tuple], max_iters: Optional[int]=None, **kwargs):
assert isinstance(data_loaders, list)
assert mmcv.is_list_of(workflow, tuple)
assert len(data_loaders) == len(workflow)
if max_iters is not None:
warnings.warn('setting max_iters in... | ['def', 'run(self,', 'data_loaders:', 'Sequence[DataLoader],', 'workflow:', 'List[tuple],', 'max_iters:', 'Optional[int]=None,', '**kwargs):', 'assert', 'isinstance(data_loaders,', 'list)', 'assert', 'mmcv.is_list_of(workflow,', 'tuple)', 'assert', 'len(data_loaders)', '==', 'len(workflow)', 'if', 'max_iters', 'is', 'n... | 917,790 |
openvinotoolkit/training_extensions | semisl_mixin.py | SemiSLConfigurerMixin.configure_unlabeled_dataloader | configure_unlabeled_dataloader | Patch for unlabled dataloader. | [
"Patch",
"for",
"unlabled",
"dataloader."
] | def configure_unlabeled_dataloader(cfg: Config):
model_task = {'classification': 'mmcls', 'detection': 'mmdet', 'segmentation': 'mmseg'}
if 'unlabeled' in cfg.data:
task_lib_module = importlib.import_module(f'{model_task[cfg.model_task]}.datasets')
dataset_builder = getattr(task_lib_module, 'bui... | ['def', 'configure_unlabeled_dataloader(cfg:', 'Config):', 'model_task', '=', "{'classification':", "'mmcls',", "'detection':", "'mmdet',", "'segmentation':", "'mmseg'}", 'if', "'unlabeled'", 'in', 'cfg.data:', 'task_lib_module', '=', "importlib.import_module(f'{model_task[cfg.model_task]}.datasets')", 'dataset_builder... | 917,791 |
openvinotoolkit/training_extensions | adaptive_repeat_data_hook.py | AdaptiveRepeatDataHook.before_epoch | before_epoch | Convert to OTX Sampler. | [
"Convert",
"to",
"OTX",
"Sampler."
] | def before_epoch(self, runner):
dataset = runner.data_loader.dataset
num_workers = runner.data_loader.num_workers
collate_fn = runner.data_loader.collate_fn
worker_init_fn = runner.data_loader.worker_init_fn
sampler = OTXSampler(dataset=dataset, samples_per_gpu=self.train_batch_size, num_replicas=se... | ['def', 'before_epoch(self,', 'runner):', 'dataset', '=', 'runner.data_loader.dataset', 'num_workers', '=', 'runner.data_loader.num_workers', 'collate_fn', '=', 'runner.data_loader.collate_fn', 'worker_init_fn', '=', 'runner.data_loader.worker_init_fn', 'sampler', '=', 'OTXSampler(dataset=dataset,', 'samples_per_gpu=se... | 917,793 |
openvinotoolkit/training_extensions | checkpoint_hook.py | CheckpointHookWithValResults.before_run | before_run | Set output directopy if not set. | [
"Set",
"output",
"directopy",
"if",
"not",
"set."
] | def before_run(self, runner):
if not self.out_dir:
self.out_dir = runner.work_dir | ['def', 'before_run(self,', 'runner):', 'if', 'not', 'self.out_dir:', 'self.out_dir', '=', 'runner.work_dir'] | 917,795 |
openvinotoolkit/training_extensions | checkpoint_hook.py | EnsureCorrectBestCheckpointHook.after_run | after_run | Called after train epoch hooks. | [
"Called",
"after",
"train",
"epoch",
"hooks."
] | def after_run(self, runner: BaseRunner):
runner.call_hook('after_train_epoch') | ['def', 'after_run(self,', 'runner:', 'BaseRunner):', "runner.call_hook('after_train_epoch')"] | 917,798 |
openvinotoolkit/training_extensions | composed_dataloaders_hook.py | ComposedDataLoadersHook.before_epoch | before_epoch | Create composedDL before running epoch. | [
"Create",
"composedDL",
"before",
"running",
"epoch."
] | def before_epoch(self, runner):
if self.composed_loader is None:
logger.info(f"Creating ComposedDL (runner's -> {runner.data_loader}, hook's -> {self.data_loaders})")
self.composed_loader = ComposedDL([runner.data_loader, *self.data_loaders])
runner.data_loader = self.composed_loader | ['def', 'before_epoch(self,', 'runner):', 'if', 'self.composed_loader', 'is', 'None:', 'logger.info(f"Creating', 'ComposedDL', "(runner's", '->', '{runner.data_loader},', "hook's", '->', '{self.data_loaders})")', 'self.composed_loader', '=', 'ComposedDL([runner.data_loader,', '*self.data_loaders])', 'runner.data_loader... | 917,801 |
openvinotoolkit/training_extensions | custom_model_ema_hook.py | EMAMomentumUpdateHook.before_train_epoch | before_train_epoch | Called before_train_epoch in EMAMomentumUpdateHook. | [
"Called",
"before_train_epoch",
"in",
"EMAMomentumUpdateHook."
] | def before_train_epoch(self, runner: BaseRunner):
if not self.by_epoch:
return
if is_module_wrapper(runner.model):
model = runner.model.module
else:
model = runner.model
if not hasattr(model, 'momentum'):
raise AttributeError('The model must have attribute "momentum".')
... | ['def', 'before_train_epoch(self,', 'runner:', 'BaseRunner):', 'if', 'not', 'self.by_epoch:', 'return', 'if', 'is_module_wrapper(runner.model):', 'model', '=', 'runner.model.module', 'else:', 'model', '=', 'runner.model', 'if', 'not', 'hasattr(model,', "'momentum'):", 'raise', "AttributeError('The", 'model', 'must', 'h... | 917,803 |
openvinotoolkit/training_extensions | custom_model_ema_hook.py | EMAMomentumUpdateHook.after_train_iter | after_train_iter | Called after_train_iter in EMAMomentumUpdateHook. | [
"Called",
"after_train_iter",
"in",
"EMAMomentumUpdateHook."
] | def after_train_iter(self, runner: BaseRunner):
if self.every_n_iters(runner, self.update_interval):
if is_module_wrapper(runner.model):
runner.model.module.momentum_update()
else:
runner.model.momentum_update() | ['def', 'after_train_iter(self,', 'runner:', 'BaseRunner):', 'if', 'self.every_n_iters(runner,', 'self.update_interval):', 'if', 'is_module_wrapper(runner.model):', 'runner.model.module.momentum_update()', 'else:', 'runner.model.momentum_update()'] | 917,805 |
openvinotoolkit/training_extensions | early_stopping_hook.py | EarlyStoppingHook.before_run | before_run | Called before_run in EarlyStoppingHook. | [
"Called",
"before_run",
"in",
"EarlyStoppingHook."
] | def before_run(self, runner: BaseRunner):
if runner.max_epochs is None:
self.by_epoch = False
for hook in runner.hooks:
if isinstance(hook, LrUpdaterHook):
self.warmup_iters = hook.warmup_iters
break
if getattr(self, 'warmup_iters', None) is None:
raise ValueE... | ['def', 'before_run(self,', 'runner:', 'BaseRunner):', 'if', 'runner.max_epochs', 'is', 'None:', 'self.by_epoch', '=', 'False', 'for', 'hook', 'in', 'runner.hooks:', 'if', 'isinstance(hook,', 'LrUpdaterHook):', 'self.warmup_iters', '=', 'hook.warmup_iters', 'break', 'if', 'getattr(self,', "'warmup_iters',", 'None)', 'i... | 917,809 |
openvinotoolkit/training_extensions | early_stopping_hook.py | ReduceLROnPlateauLrUpdaterHook.after_each_n_epochs | after_each_n_epochs | Check whether current epoch is a next epoch after multiples of interval. | [
"Check",
"whether",
"current",
"epoch",
"is",
"a",
"next",
"epoch",
"after",
"multiples",
"of",
"interval."
] | def after_each_n_epochs(self, runner: BaseRunner, interval: int) -> bool:
return runner.epoch % interval == 0 if interval > 0 and runner.epoch != 0 else False | ['def', 'after_each_n_epochs(self,', 'runner:', 'BaseRunner,', 'interval:', 'int)', '->', 'bool:', 'return', 'runner.epoch', '%', 'interval', '==', '0', 'if', 'interval', '>', '0', 'and', 'runner.epoch', '!=', '0', 'else', 'False'] | 917,812 |
openvinotoolkit/training_extensions | early_stopping_hook.py | ReduceLROnPlateauLrUpdaterHook.after_each_n_iters | after_each_n_iters | Check whether current iter is a next iter after multiples of interval. | [
"Check",
"whether",
"current",
"iter",
"is",
"a",
"next",
"iter",
"after",
"multiples",
"of",
"interval."
] | def after_each_n_iters(self, runner: BaseRunner, interval: int) -> bool:
return runner.iter % interval == 0 if interval > 0 and runner.iter != 0 else False | ['def', 'after_each_n_iters(self,', 'runner:', 'BaseRunner,', 'interval:', 'int)', '->', 'bool:', 'return', 'runner.iter', '%', 'interval', '==', '0', 'if', 'interval', '>', '0', 'and', 'runner.iter', '!=', '0', 'else', 'False'] | 917,813 |
openvinotoolkit/training_extensions | early_stopping_hook.py | ReduceLROnPlateauLrUpdaterHook.get_lr | get_lr | Called get_lr in ReduceLROnPlateauLrUpdaterHook. | [
"Called",
"get_lr",
"in",
"ReduceLROnPlateauLrUpdaterHook."
] | def get_lr(self, runner: BaseRunner, base_lr: float):
if self.current_lr < 0:
self.current_lr = base_lr
if not self._is_check_timing(runner) or self.current_lr == self.min_lr or self.bad_count_iter == runner.iter:
return self.current_lr
if hasattr(runner, 'all_metrics'):
score = runn... | ['def', 'get_lr(self,', 'runner:', 'BaseRunner,', 'base_lr:', 'float):', 'if', 'self.current_lr', '<', '0:', 'self.current_lr', '=', 'base_lr', 'if', 'not', 'self._is_check_timing(runner)', 'or', 'self.current_lr', '==', 'self.min_lr', 'or', 'self.bad_count_iter', '==', 'runner.iter:', 'return', 'self.current_lr', 'if'... | 917,814 |
openvinotoolkit/training_extensions | early_stopping_hook.py | ReduceLROnPlateauLrUpdaterHook.before_run | before_run | Called before_run in ReduceLROnPlateauLrUpdaterHook. | [
"Called",
"before_run",
"in",
"ReduceLROnPlateauLrUpdaterHook."
] | def before_run(self, runner: BaseRunner):
for group in runner.optimizer.param_groups:
group.setdefault('initial_lr', group['lr'])
self.base_lr = [group['initial_lr'] for group in runner.optimizer.param_groups]
self.bad_count = 0
self.last_iter = 0
self.current_lr = -1.0
self.best_score =... | ['def', 'before_run(self,', 'runner:', 'BaseRunner):', 'for', 'group', 'in', 'runner.optimizer.param_groups:', "group.setdefault('initial_lr',", "group['lr'])", 'self.base_lr', '=', "[group['initial_lr']", 'for', 'group', 'in', 'runner.optimizer.param_groups]', 'self.bad_count', '=', '0', 'self.last_iter', '=', '0', 's... | 917,815 |
openvinotoolkit/training_extensions | early_stopping_hook.py | StopLossNanTrainingHook.after_train_iter | after_train_iter | Called after_train_iter in StopLossNanTrainingHook. | [
"Called",
"after_train_iter",
"in",
"StopLossNanTrainingHook."
] | def after_train_iter(self, runner: BaseRunner):
if isnan(runner.outputs['loss'].item()):
logger.warning('Early Stopping since loss is NaN')
runner.should_stop = True | ['def', 'after_train_iter(self,', 'runner:', 'BaseRunner):', 'if', "isnan(runner.outputs['loss'].item()):", "logger.warning('Early", 'Stopping', 'since', 'loss', 'is', "NaN')", 'runner.should_stop', '=', 'True'] | 917,816 |
openvinotoolkit/training_extensions | eval_hook.py | CustomEvalHook.after_train_iter | after_train_iter | Check whether current iteration is to be evaluated or not. | [
"Check",
"whether",
"current",
"iteration",
"is",
"to",
"be",
"evaluated",
"or",
"not."
] | def after_train_iter(self, runner):
if self.by_epoch or not self.every_n_iters(runner, self.interval):
return
runner.log_buffer.clear()
self._do_evaluate(runner) | ['def', 'after_train_iter(self,', 'runner):', 'if', 'self.by_epoch', 'or', 'not', 'self.every_n_iters(runner,', 'self.interval):', 'return', 'runner.log_buffer.clear()', 'self._do_evaluate(runner)'] | 917,819 |
openvinotoolkit/training_extensions | loss_dynamics_tracking_hook.py | LossDynamicsTrackingHook.before_run | before_run | Before run, check the type of model for safe running. | [
"Before",
"run,",
"check",
"the",
"type",
"of",
"model",
"for",
"safe",
"running."
] | def before_run(self, runner):
if not isinstance(runner.model, MMDataParallel):
raise NotImplementedError(f'Except MMDataParallel, runner.model={type(runner.model)} is not supported now.') | ['def', 'before_run(self,', 'runner):', 'if', 'not', 'isinstance(runner.model,', 'MMDataParallel):', 'raise', "NotImplementedError(f'Except", 'MMDataParallel,', 'runner.model={type(runner.model)}', 'is', 'not', 'supported', "now.')"] | 917,829 |
openvinotoolkit/training_extensions | loss_dynamics_tracking_hook.py | LossDynamicsTrackingHook.configure_recipe | configure_recipe | Configure recipe to enable loss dynamics tracking. | [
"Configure",
"recipe",
"to",
"enable",
"loss",
"dynamics",
"tracking."
] | def configure_recipe(cls, recipe_cfg: Config, output_path: str) -> None:
recipe_cfg.model['track_loss_dynamics'] = True
update_or_add_custom_hook(recipe_cfg, ConfigDict(type='LossDynamicsTrackingHook', priority='LOWEST', output_path=output_path)) | ['def', 'configure_recipe(cls,', 'recipe_cfg:', 'Config,', 'output_path:', 'str)', '->', 'None:', "recipe_cfg.model['track_loss_dynamics']", '=', 'True', 'update_or_add_custom_hook(recipe_cfg,', "ConfigDict(type='LossDynamicsTrackingHook',", "priority='LOWEST',", 'output_path=output_path))'] | 917,833 |
openvinotoolkit/training_extensions | mean_teacher_hook.py | MeanTeacherHook.before_train_epoch | before_train_epoch | Enable unlabeled loss if over start epoch. | [
"Enable",
"unlabeled",
"loss",
"if",
"over",
"start",
"epoch."
] | def before_train_epoch(self, runner):
if runner.epoch + 1 < self.start_epoch:
return
if self.unlabeled_loss_enabled:
return
super().before_train_epoch(runner)
average_pseudo_label_ratio = self._get_average_pseudo_label_ratio(runner)
logger.info(f'avr_ps_ratio: {average_pseudo_label_r... | ['def', 'before_train_epoch(self,', 'runner):', 'if', 'runner.epoch', '+', '1', '<', 'self.start_epoch:', 'return', 'if', 'self.unlabeled_loss_enabled:', 'return', 'super().before_train_epoch(runner)', 'average_pseudo_label_ratio', '=', 'self._get_average_pseudo_label_ratio(runner)', "logger.info(f'avr_ps_ratio:", "{av... | 917,834 |
openvinotoolkit/training_extensions | model_ema_v2_hook.py | ModelEmaV2Hook.before_train_epoch | before_train_epoch | Make emav2 model before run epoch. | [
"Make",
"emav2",
"model",
"before",
"run",
"epoch."
] | def before_train_epoch(self, runner):
if not hasattr(self, 'use_ema'):
self.use_ema = len(runner.data_loader.dataset) > self.dataset_len_thr
if self.use_ema and (not hasattr(runner, 'ema_model')):
model = runner.model
ema_model = ModelEmaV2(model, decay=self.ema_decay, dataset_len_thr=se... | ['def', 'before_train_epoch(self,', 'runner):', 'if', 'not', 'hasattr(self,', "'use_ema'):", 'self.use_ema', '=', 'len(runner.data_loader.dataset)', '>', 'self.dataset_len_thr', 'if', 'self.use_ema', 'and', '(not', 'hasattr(runner,', "'ema_model')):", 'model', '=', 'runner.model', 'ema_model', '=', 'ModelEmaV2(model,',... | 917,838 |
openvinotoolkit/training_extensions | no_bias_decay_hook.py | NoBiasDecayHook.before_train_epoch | before_train_epoch | Split weights into decay/no-decay groups. | [
"Split",
"weights",
"into",
"decay/no-decay",
"groups."
] | def before_train_epoch(self, runner):
(weight_decay, bias_no_decay, weight_no_decay) = ([], [], [])
for module in runner.model.modules():
if isinstance(module, (nn.Conv2d, nn.Linear)):
weight_decay.append(module.weight)
if module.bias is not None:
bias_no_decay.ap... | ['def', 'before_train_epoch(self,', 'runner):', '(weight_decay,', 'bias_no_decay,', 'weight_no_decay)', '=', '([],', '[],', '[])', 'for', 'module', 'in', 'runner.model.modules():', 'if', 'isinstance(module,', '(nn.Conv2d,', 'nn.Linear)):', 'weight_decay.append(module.weight)', 'if', 'module.bias', 'is', 'not', 'None:',... | 917,840 |
jaywalnut310/Vector-Quantized-Autoencoders | transformer_vq.py | vq_discrete_unbottleneck | vq_discrete_unbottleneck | Simple undiscretization from vector quantized representation. | [
"Simple",
"undiscretization",
"from",
"vector",
"quantized",
"representation."
] | def vq_discrete_unbottleneck(x, hparams):
x_shape = commons.shape_list(x)
bottleneck_size = 2 ** hparams.bottleneck_bits
means = hparams.means
x_flat = tf.reshape(x, [-1, bottleneck_size])
result = tf.matmul(x_flat, means)
result = tf.reshape(result, x_shape[:-1] + [hparams.hidden_size])
ret... | ['def', 'vq_discrete_unbottleneck(x,', 'hparams):', 'x_shape', '=', 'commons.shape_list(x)', 'bottleneck_size', '=', '2', '**', 'hparams.bottleneck_bits', 'means', '=', 'hparams.means', 'x_flat', '=', 'tf.reshape(x,', '[-1,', 'bottleneck_size])', 'result', '=', 'tf.matmul(x_flat,', 'means)', 'result', '=', 'tf.reshape(... | 931,052 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.