partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
XueQiuTrader.get_entrust
获取委托单(目前返回20次调仓的结果) 操作数量都按1手模拟换算的 :return:
easytrader/xqtrader.py
def get_entrust(self): """ 获取委托单(目前返回20次调仓的结果) 操作数量都按1手模拟换算的 :return: """ xq_entrust_list = self._get_xq_history() entrust_list = [] replace_none = lambda s: s or 0 for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调...
def get_entrust(self): """ 获取委托单(目前返回20次调仓的结果) 操作数量都按1手模拟换算的 :return: """ xq_entrust_list = self._get_xq_history() entrust_list = [] replace_none = lambda s: s or 0 for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调...
[ "获取委托单", "(", "目前返回20次调仓的结果", ")", "操作数量都按1手模拟换算的", ":", "return", ":" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L233-L271
[ "def", "get_entrust", "(", "self", ")", ":", "xq_entrust_list", "=", "self", ".", "_get_xq_history", "(", ")", "entrust_list", "=", "[", "]", "replace_none", "=", "lambda", "s", ":", "s", "or", "0", "for", "xq_entrusts", "in", "xq_entrust_list", ":", "stat...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
XueQiuTrader.cancel_entrust
对未成交的调仓进行伪撤单 :param entrust_no: :return:
easytrader/xqtrader.py
def cancel_entrust(self, entrust_no): """ 对未成交的调仓进行伪撤单 :param entrust_no: :return: """ xq_entrust_list = self._get_xq_history() is_have = False for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调仓状态 for entrust i...
def cancel_entrust(self, entrust_no): """ 对未成交的调仓进行伪撤单 :param entrust_no: :return: """ xq_entrust_list = self._get_xq_history() is_have = False for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调仓状态 for entrust i...
[ "对未成交的调仓进行伪撤单", ":", "param", "entrust_no", ":", ":", "return", ":" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L273-L313
[ "def", "cancel_entrust", "(", "self", ",", "entrust_no", ")", ":", "xq_entrust_list", "=", "self", ".", "_get_xq_history", "(", ")", "is_have", "=", "False", "for", "xq_entrusts", "in", "xq_entrust_list", ":", "status", "=", "xq_entrusts", "[", "\"status\"", "...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
XueQiuTrader.adjust_weight
雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数
easytrader/xqtrader.py
def adjust_weight(self, stock_code, weight): """ 雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数 """ stock = self._search_stock_info(stock_code) if stock is None: raise exceptions.TradeError(u"没有查询要...
def adjust_weight(self, stock_code, weight): """ 雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数 """ stock = self._search_stock_info(stock_code) if stock is None: raise exceptions.TradeError(u"没有查询要...
[ "雪球组合调仓", "weight", "为调整后的仓位比例", ":", "param", "stock_code", ":", "str", "股票代码", ":", "param", "weight", ":", "float", "调整之后的持仓百分比,", "0", "-", "100", "之间的浮点数" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L315-L394
[ "def", "adjust_weight", "(", "self", ",", "stock_code", ",", "weight", ")", ":", "stock", "=", "self", ".", "_search_stock_info", "(", "stock_code", ")", "if", "stock", "is", "None", ":", "raise", "exceptions", ".", "TradeError", "(", "u\"没有查询要操作的股票信息\")", "...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
XueQiuTrader._trade
调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return:
easytrader/xqtrader.py
def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"): """ 调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return: """ stock = self._search_stock_info(security) balance = self....
def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"): """ 调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return: """ stock = self._search_stock_info(security) balance = self....
[ "调仓", ":", "param", "security", ":", ":", "param", "price", ":", ":", "param", "amount", ":", ":", "param", "volume", ":", ":", "param", "entrust_bs", ":", ":", "return", ":" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L396-L528
[ "def", "_trade", "(", "self", ",", "security", ",", "price", "=", "0", ",", "amount", "=", "0", ",", "volume", "=", "0", ",", "entrust_bs", "=", "\"buy\"", ")", ":", "stock", "=", "self", ".", "_search_stock_info", "(", "security", ")", "balance", "=...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
XueQiuTrader.buy
买入卖出股票 :param security: 股票代码 :param price: 买入价格 :param amount: 买入股数 :param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop:
easytrader/xqtrader.py
def buy(self, security, price=0, amount=0, volume=0, entrust_prop=0): """买入卖出股票 :param security: 股票代码 :param price: 买入价格 :param amount: 买入股数 :param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: """ return self._trade(security, pr...
def buy(self, security, price=0, amount=0, volume=0, entrust_prop=0): """买入卖出股票 :param security: 股票代码 :param price: 买入价格 :param amount: 买入股数 :param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: """ return self._trade(security, pr...
[ "买入卖出股票", ":", "param", "security", ":", "股票代码", ":", "param", "price", ":", "买入价格", ":", "param", "amount", ":", "买入股数", ":", "param", "volume", ":", "买入总金额", "由", "volume", "/", "price", "取整,", "若指定", "price", "则此参数无效", ":", "param", "entrust_prop", ...
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L530-L538
[ "def", "buy", "(", "self", ",", "security", ",", "price", "=", "0", ",", "amount", "=", "0", ",", "volume", "=", "0", ",", "entrust_prop", "=", "0", ")", ":", "return", "self", ".", "_trade", "(", "security", ",", "price", ",", "amount", ",", "vo...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
XueQiuTrader.sell
卖出股票 :param security: 股票代码 :param price: 卖出价格 :param amount: 卖出股数 :param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop:
easytrader/xqtrader.py
def sell(self, security, price=0, amount=0, volume=0, entrust_prop=0): """卖出股票 :param security: 股票代码 :param price: 卖出价格 :param amount: 卖出股数 :param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: """ return self._trade(security, pri...
def sell(self, security, price=0, amount=0, volume=0, entrust_prop=0): """卖出股票 :param security: 股票代码 :param price: 卖出价格 :param amount: 卖出股数 :param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: """ return self._trade(security, pri...
[ "卖出股票", ":", "param", "security", ":", "股票代码", ":", "param", "price", ":", "卖出价格", ":", "param", "amount", ":", "卖出股数", ":", "param", "volume", ":", "卖出总金额", "由", "volume", "/", "price", "取整,", "若指定", "price", "则此参数无效", ":", "param", "entrust_prop", ":...
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L540-L548
[ "def", "sell", "(", "self", ",", "security", ",", "price", "=", "0", ",", "amount", "=", "0", ",", "volume", "=", "0", ",", "entrust_prop", "=", "0", ")", ":", "return", "self", ".", "_trade", "(", "security", ",", "price", ",", "amount", ",", "v...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
JoinQuantFollower.follow
跟踪joinquant对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param strategies: joinquant 的模拟交易地址,支持使用 [] 指定多个模拟交易, 地址类似 https://www.joinquant.com/algorithm/live/index?backtestId=xxx :param track_interval: 轮训模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间,...
easytrader/joinquant_follower.py
def follow( self, users, strategies, track_interval=1, trade_cmd_expire_seconds=120, cmd_cache=True, entrust_prop="limit", send_interval=0, ): """跟踪joinquant对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param ...
def follow( self, users, strategies, track_interval=1, trade_cmd_expire_seconds=120, cmd_cache=True, entrust_prop="limit", send_interval=0, ): """跟踪joinquant对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param ...
[ "跟踪joinquant对应的模拟交易,支持多用户多策略", ":", "param", "users", ":", "支持easytrader的用户对象,支持使用", "[]", "指定多个用户", ":", "param", "strategies", ":", "joinquant", "的模拟交易地址,支持使用", "[]", "指定多个模拟交易", "地址类似", "https", ":", "//", "www", ".", "joinquant", ".", "com", "/", "algorithm", ...
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/joinquant_follower.py#L34-L81
[ "def", "follow", "(", "self", ",", "users", ",", "strategies", ",", "track_interval", "=", "1", ",", "trade_cmd_expire_seconds", "=", "120", ",", "cmd_cache", "=", "True", ",", "entrust_prop", "=", "\"limit\"", ",", "send_interval", "=", "0", ",", ")", ":"...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
ClientTrader.connect
直接连接登陆后的客户端 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :return:
easytrader/clienttrader.py
def connect(self, exe_path=None, **kwargs): """ 直接连接登陆后的客户端 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :return: """ connect_path = exe_path or self._config.DEFAULT_EXE_PATH if connect_path is None: raise ValueE...
def connect(self, exe_path=None, **kwargs): """ 直接连接登陆后的客户端 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :return: """ connect_path = exe_path or self._config.DEFAULT_EXE_PATH if connect_path is None: raise ValueE...
[ "直接连接登陆后的客户端", ":", "param", "exe_path", ":", "客户端路径类似", "r", "C", ":", "\\\\", "htzqzyb2", "\\\\", "xiadan", ".", "exe", "默认", "r", "C", ":", "\\\\", "htzqzyb2", "\\\\", "xiadan", ".", "exe", ":", "return", ":" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L70-L86
[ "def", "connect", "(", "self", ",", "exe_path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "connect_path", "=", "exe_path", "or", "self", ".", "_config", ".", "DEFAULT_EXE_PATH", "if", "connect_path", "is", "None", ":", "raise", "ValueError", "(", "...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
ClientTrader.market_buy
市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'}
easytrader/clienttrader.py
def market_buy(self, security, amount, ttype=None, **kwargs): """ 市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余...
def market_buy(self, security, amount, ttype=None, **kwargs): """ 市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余...
[ "市价买入", ":", "param", "security", ":", "六位证券代码", ":", "param", "amount", ":", "交易数量", ":", "param", "ttype", ":", "市价委托类型,默认客户端默认选择,", "深市可选", "[", "对手方最优价格", "本方最优价格", "即时成交剩余撤销", "最优五档即时成交剩余", "全额成交或撤销", "]", "沪市可选", "[", "最优五档成交剩余撤销", "最优五档成交剩余转限价", "]" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L154-L167
[ "def", "market_buy", "(", "self", ",", "security", ",", "amount", ",", "ttype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_switch_left_menus", "(", "[", "\"市价委托\", \"买入\"])", "", "", "", "", "return", "self", ".", "market_trade", "(...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
ClientTrader.market_sell
市价卖出 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'}
easytrader/clienttrader.py
def market_sell(self, security, amount, ttype=None, **kwargs): """ 市价卖出 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩...
def market_sell(self, security, amount, ttype=None, **kwargs): """ 市价卖出 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩...
[ "市价卖出", ":", "param", "security", ":", "六位证券代码", ":", "param", "amount", ":", "交易数量", ":", "param", "ttype", ":", "市价委托类型,默认客户端默认选择,", "深市可选", "[", "对手方最优价格", "本方最优价格", "即时成交剩余撤销", "最优五档即时成交剩余", "全额成交或撤销", "]", "沪市可选", "[", "最优五档成交剩余撤销", "最优五档成交剩余转限价", "]" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L169-L182
[ "def", "market_sell", "(", "self", ",", "security", ",", "amount", ",", "ttype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_switch_left_menus", "(", "[", "\"市价委托\", \"卖出\"])", "", "", "", "", "return", "self", ".", "market_trade", "...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
ClientTrader.market_trade
市价交易 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'}
easytrader/clienttrader.py
def market_trade(self, security, amount, ttype=None, **kwargs): """ 市价交易 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交...
def market_trade(self, security, amount, ttype=None, **kwargs): """ 市价交易 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交...
[ "市价交易", ":", "param", "security", ":", "六位证券代码", ":", "param", "amount", ":", "交易数量", ":", "param", "ttype", ":", "市价委托类型,默认客户端默认选择,", "深市可选", "[", "对手方最优价格", "本方最优价格", "即时成交剩余撤销", "最优五档即时成交剩余", "全额成交或撤销", "]", "沪市可选", "[", "最优五档成交剩余撤销", "最优五档成交剩余转限价", "]" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L184-L202
[ "def", "market_trade", "(", "self", ",", "security", ",", "amount", ",", "ttype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_set_market_trade_params", "(", "security", ",", "amount", ")", "if", "ttype", "is", "not", "None", ":", "se...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
ClientTrader._set_market_trade_type
根据选择的市价交易类型选择对应的下拉选项
easytrader/clienttrader.py
def _set_market_trade_type(self, ttype): """根据选择的市价交易类型选择对应的下拉选项""" selects = self._main.child_window( control_id=self._config.TRADE_MARKET_TYPE_CONTROL_ID, class_name="ComboBox", ) for i, text in selects.texts(): # skip 0 index, because 0 index is cur...
def _set_market_trade_type(self, ttype): """根据选择的市价交易类型选择对应的下拉选项""" selects = self._main.child_window( control_id=self._config.TRADE_MARKET_TYPE_CONTROL_ID, class_name="ComboBox", ) for i, text in selects.texts(): # skip 0 index, because 0 index is cur...
[ "根据选择的市价交易类型选择对应的下拉选项" ]
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L204-L218
[ "def", "_set_market_trade_type", "(", "self", ",", "ttype", ")", ":", "selects", "=", "self", ".", "_main", ".", "child_window", "(", "control_id", "=", "self", ".", "_config", ".", "TRADE_MARKET_TYPE_CONTROL_ID", ",", "class_name", "=", "\"ComboBox\"", ",", "...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
BaseLoginClientTrader.prepare
登陆客户端 :param config_path: 登陆配置文件,跟参数登陆方式二选一 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :param comm_password: 通讯密码 :return:
easytrader/clienttrader.py
def prepare( self, config_path=None, user=None, password=None, exe_path=None, comm_password=None, **kwargs ): """ 登陆客户端 :param config_path: 登陆配置文件,跟参数登陆方式二选一 :param user: 账号 :param password: 明文密码 :param exe_path:...
def prepare( self, config_path=None, user=None, password=None, exe_path=None, comm_password=None, **kwargs ): """ 登陆客户端 :param config_path: 登陆配置文件,跟参数登陆方式二选一 :param user: 账号 :param password: 明文密码 :param exe_path:...
[ "登陆客户端", ":", "param", "config_path", ":", "登陆配置文件,跟参数登陆方式二选一", ":", "param", "user", ":", "账号", ":", "param", "password", ":", "明文密码", ":", "param", "exe_path", ":", "客户端路径类似", "r", "C", ":", "\\\\", "htzqzyb2", "\\\\", "xiadan", ".", "exe", "默认", "r", ...
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L396-L426
[ "def", "prepare", "(", "self", ",", "config_path", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "exe_path", "=", "None", ",", "comm_password", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "config_path", "is", "no...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
YHClientTrader.login
登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 :return:
easytrader/yh_clienttrader.py
def login(self, user, password, exe_path, comm_password=None, **kwargs): """ 登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 ...
def login(self, user, password, exe_path, comm_password=None, **kwargs): """ 登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 ...
[ "登陆客户端", ":", "param", "user", ":", "账号", ":", "param", "password", ":", "明文密码", ":", "param", "exe_path", ":", "客户端路径类似", "C", ":", "\\\\", "中国银河证券双子星3", ".", "2", "\\\\", "Binarystar", ".", "exe", "默认", "C", ":", "\\\\", "中国银河证券双子星3", ".", "2", "\\...
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/yh_clienttrader.py#L25-L80
[ "def", "login", "(", "self", ",", "user", ",", "password", ",", "exe_path", ",", "comm_password", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "_app", "=", "pywinauto", ".", "Application", "(", ")", ".", "connect", "(", ...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
use
用于生成特定的券商对象 :param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端'] :param debug: 控制 debug 日志的显示, 默认为 True :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万 :return the class of trader Usage:: >>> import easytrader >>> user = easytrader.use('xq') >>> user.prepare('xq....
easytrader/api.py
def use(broker, debug=True, **kwargs): """用于生成特定的券商对象 :param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端'] :param debug: 控制 debug 日志的显示, 默认为 True :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万 :return the class of trader Usage:: >>> import easytrader >>> user = easy...
def use(broker, debug=True, **kwargs): """用于生成特定的券商对象 :param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端'] :param debug: 控制 debug 日志的显示, 默认为 True :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万 :return the class of trader Usage:: >>> import easytrader >>> user = easy...
[ "用于生成特定的券商对象", ":", "param", "broker", ":", "券商名支持", "[", "yh_client", "银河客户端", "]", "[", "ht_client", "华泰客户端", "]", ":", "param", "debug", ":", "控制", "debug", "日志的显示", "默认为", "True", ":", "param", "initial_assets", ":", "[", "雪球参数", "]", "控制雪球初始资金,默认为一百万"...
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/api.py#L16-L50
[ "def", "use", "(", "broker", ",", "debug", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "not", "debug", ":", "log", ".", "setLevel", "(", "logging", ".", "INFO", ")", "if", "broker", ".", "lower", "(", ")", "in", "[", "\"xq\"", ",", "\...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
follower
用于生成特定的券商对象 :param platform:平台支持 ['jq', 'joinquant', '聚宽’] :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万, 总资金由 initial_assets * 组合当前净值 得出 :param total_assets: [雪球参数] 控制雪球总资金,无默认值, 若设置则覆盖 initial_assets :return the class of follower Usage:: >>> import easytrader >>> u...
easytrader/api.py
def follower(platform, **kwargs): """用于生成特定的券商对象 :param platform:平台支持 ['jq', 'joinquant', '聚宽’] :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万, 总资金由 initial_assets * 组合当前净值 得出 :param total_assets: [雪球参数] 控制雪球总资金,无默认值, 若设置则覆盖 initial_assets :return the class of follower Usage:: ...
def follower(platform, **kwargs): """用于生成特定的券商对象 :param platform:平台支持 ['jq', 'joinquant', '聚宽’] :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万, 总资金由 initial_assets * 组合当前净值 得出 :param total_assets: [雪球参数] 控制雪球总资金,无默认值, 若设置则覆盖 initial_assets :return the class of follower Usage:: ...
[ "用于生成特定的券商对象", ":", "param", "platform", ":", "平台支持", "[", "jq", "joinquant", "聚宽’", "]", ":", "param", "initial_assets", ":", "[", "雪球参数", "]", "控制雪球初始资金,默认为一万", "总资金由", "initial_assets", "*", "组合当前净值", "得出", ":", "param", "total_assets", ":", "[", "雪球参数", ...
shidenggui/easytrader
python
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/api.py#L53-L77
[ "def", "follower", "(", "platform", ",", "*", "*", "kwargs", ")", ":", "if", "platform", ".", "lower", "(", ")", "in", "[", "\"rq\"", ",", "\"ricequant\"", ",", "\"米筐\"]:", "", "", "return", "RiceQuantFollower", "(", ")", "if", "platform", ".", "lower"...
e5ae4daeda4ea125763a95b280dd694c7f68257d
train
CaffeLMDB
Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf. Produces datapoints of the format: [HWC image, label]. Note that Caffe LMDB format is not efficient: it stores serialized raw arrays rather than JPEG images. Args: lmdb_path, shuffle, keys: same as :class:`LMDBData`. ...
tensorpack/dataflow/format.py
def CaffeLMDB(lmdb_path, shuffle=True, keys=None): """ Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf. Produces datapoints of the format: [HWC image, label]. Note that Caffe LMDB format is not efficient: it stores serialized raw arrays rather than JPEG images. Args...
def CaffeLMDB(lmdb_path, shuffle=True, keys=None): """ Read a Caffe LMDB file where each value contains a ``caffe.Datum`` protobuf. Produces datapoints of the format: [HWC image, label]. Note that Caffe LMDB format is not efficient: it stores serialized raw arrays rather than JPEG images. Args...
[ "Read", "a", "Caffe", "LMDB", "file", "where", "each", "value", "contains", "a", "caffe", ".", "Datum", "protobuf", ".", "Produces", "datapoints", "of", "the", "format", ":", "[", "HWC", "image", "label", "]", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/format.py#L167-L202
[ "def", "CaffeLMDB", "(", "lmdb_path", ",", "shuffle", "=", "True", ",", "keys", "=", "None", ")", ":", "cpb", "=", "get_caffe_pb", "(", ")", "lmdb_data", "=", "LMDBData", "(", "lmdb_path", ",", "shuffle", ",", "keys", ")", "def", "decoder", "(", "k", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
NvidiaDevice.memory
Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes
tensorpack/utils/nvml.py
def memory(self): """Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes """ class GpuMemoryInfo(Structure): ...
def memory(self): """Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes """ class GpuMemoryInfo(Structure): ...
[ "Memory", "information", "in", "bytes" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L92-L113
[ "def", "memory", "(", "self", ")", ":", "class", "GpuMemoryInfo", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "'total'", ",", "c_ulonglong", ")", ",", "(", "'free'", ",", "c_ulonglong", ")", ",", "(", "'used'", ",", "c_ulonglong", ")", ",", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
NvidiaDevice.utilization
Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written Example: >>>...
tensorpack/utils/nvml.py
def utilization(self): """Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written ...
def utilization(self): """Percent of time over the past second was utilized. Details: Percent of time over the past second during which one or more kernels was executing on the GPU. Percent of time over the past second during which global (device) memory was being read or written ...
[ "Percent", "of", "time", "over", "the", "past", "second", "was", "utilized", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L115-L138
[ "def", "utilization", "(", "self", ")", ":", "class", "GpuUtilizationInfo", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "'gpu'", ",", "c_uint", ")", ",", "(", "'memory'", ",", "c_uint", ")", ",", "]", "c_util", "=", "GpuUtilizationInfo", "(", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
NVMLContext.num_devices
Get number of devices
tensorpack/utils/nvml.py
def num_devices(self): """Get number of devices """ c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
def num_devices(self): """Get number of devices """ c_count = c_uint() _check_return(_NVML.get_function( "nvmlDeviceGetCount_v2")(byref(c_count))) return c_count.value
[ "Get", "number", "of", "devices" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L171-L176
[ "def", "num_devices", "(", "self", ")", ":", "c_count", "=", "c_uint", "(", ")", "_check_return", "(", "_NVML", ".", "get_function", "(", "\"nvmlDeviceGetCount_v2\"", ")", "(", "byref", "(", "c_count", ")", ")", ")", "return", "c_count", ".", "value" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
NVMLContext.device
Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device
tensorpack/utils/nvml.py
def device(self, idx): """Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device """ class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) ...
def device(self, idx): """Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device """ class GpuDevice(Structure): pass c_nvmlDevice_t = POINTER(GpuDevice) c_index = c_uint(idx) ...
[ "Get", "a", "specific", "GPU", "device" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L185-L204
[ "def", "device", "(", "self", ",", "idx", ")", ":", "class", "GpuDevice", "(", "Structure", ")", ":", "pass", "c_nvmlDevice_t", "=", "POINTER", "(", "GpuDevice", ")", "c_index", "=", "c_uint", "(", "idx", ")", "device", "=", "c_nvmlDevice_t", "(", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
maybe_download_and_extract
Download and extract the tarball from Alex's website. Copied from tensorflow example
tensorpack/dataflow/dataset/cifar.py
def maybe_download_and_extract(dest_directory, cifar_classnum): """Download and extract the tarball from Alex's website. Copied from tensorflow example """ assert cifar_classnum == 10 or cifar_classnum == 100 if cifar_classnum == 10: cifar_foldername = 'cifar-10-batches-py' else: cifar_f...
def maybe_download_and_extract(dest_directory, cifar_classnum): """Download and extract the tarball from Alex's website. Copied from tensorflow example """ assert cifar_classnum == 10 or cifar_classnum == 100 if cifar_classnum == 10: cifar_foldername = 'cifar-10-batches-py' else: cifar_f...
[ "Download", "and", "extract", "the", "tarball", "from", "Alex", "s", "website", ".", "Copied", "from", "tensorflow", "example" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L24-L39
[ "def", "maybe_download_and_extract", "(", "dest_directory", ",", "cifar_classnum", ")", ":", "assert", "cifar_classnum", "==", "10", "or", "cifar_classnum", "==", "100", "if", "cifar_classnum", "==", "10", ":", "cifar_foldername", "=", "'cifar-10-batches-py'", "else",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
CifarBase.get_per_pixel_mean
Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: a mean image of all images in the given datasets, with size 32x32x3
tensorpack/dataflow/dataset/cifar.py
def get_per_pixel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: a mean image of all images in the given datasets, with size 32x32x3 """ for name in names: assert name ...
def get_per_pixel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: a mean image of all images in the given datasets, with size 32x32x3 """ for name in names: assert name ...
[ "Args", ":", "names", "(", "tuple", "[", "str", "]", ")", ":", "the", "names", "(", "train", "or", "test", ")", "of", "the", "datasets" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L135-L154
[ "def", "get_per_pixel_mean", "(", "self", ",", "names", "=", "(", "'train'", ",", "'test'", ")", ")", ":", "for", "name", "in", "names", ":", "assert", "name", "in", "[", "'train'", ",", "'test'", "]", ",", "name", "train_files", ",", "test_files", ","...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
CifarBase.get_per_channel_mean
Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: An array of three values as mean of each channel, for all images in the given datasets.
tensorpack/dataflow/dataset/cifar.py
def get_per_channel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: An array of three values as mean of each channel, for all images in the given datasets. """ mean = self.get_per_p...
def get_per_channel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): the names ('train' or 'test') of the datasets Returns: An array of three values as mean of each channel, for all images in the given datasets. """ mean = self.get_per_p...
[ "Args", ":", "names", "(", "tuple", "[", "str", "]", ")", ":", "the", "names", "(", "train", "or", "test", ")", "of", "the", "datasets" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L163-L172
[ "def", "get_per_channel_mean", "(", "self", ",", "names", "=", "(", "'train'", ",", "'test'", ")", ")", ":", "mean", "=", "self", ".", "get_per_pixel_mean", "(", "names", ")", "return", "np", ".", "mean", "(", "mean", ",", "axis", "=", "(", "0", ",",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
maskrcnn_loss
Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32
examples/FasterRCNN/model_mrcnn.py
def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks): """ Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 """ num_fg = tf.size(fg_labels, out_type=tf.int64) indices = tf.stack([tf.range(num_fg), fg_labels - 1]...
def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks): """ Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 """ num_fg = tf.size(fg_labels, out_type=tf.int64) indices = tf.stack([tf.range(num_fg), fg_labels - 1]...
[ "Args", ":", "mask_logits", ":", "#fg", "x", "#category", "xhxw", "fg_labels", ":", "#fg", "in", "1~#class", "int64", "fg_target_masks", ":", "#fgxhxw", "float32" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_mrcnn.py#L16-L51
[ "def", "maskrcnn_loss", "(", "mask_logits", ",", "fg_labels", ",", "fg_target_masks", ")", ":", "num_fg", "=", "tf", ".", "size", "(", "fg_labels", ",", "out_type", "=", "tf", ".", "int64", ")", "indices", "=", "tf", ".", "stack", "(", "[", "tf", ".", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
maskrcnn_upXconv_head
Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask_logits (N x num_category x 2s x 2s):
examples/FasterRCNN/model_mrcnn.py
def maskrcnn_upXconv_head(feature, num_category, num_convs, norm=None): """ Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask...
def maskrcnn_upXconv_head(feature, num_category, num_convs, norm=None): """ Args: feature (NxCx s x s): size is 7 in C4 models and 14 in FPN models. num_category(int): num_convs (int): number of convolution layers norm (str or None): either None or 'GN' Returns: mask...
[ "Args", ":", "feature", "(", "NxCx", "s", "x", "s", ")", ":", "size", "is", "7", "in", "C4", "models", "and", "14", "in", "FPN", "models", ".", "num_category", "(", "int", ")", ":", "num_convs", "(", "int", ")", ":", "number", "of", "convolution", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_mrcnn.py#L55-L79
[ "def", "maskrcnn_upXconv_head", "(", "feature", ",", "num_category", ",", "num_convs", ",", "norm", "=", "None", ")", ":", "assert", "norm", "in", "[", "None", ",", "'GN'", "]", ",", "norm", "l", "=", "feature", "with", "argscope", "(", "[", "Conv2D", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SVHNDigit.get_per_pixel_mean
Args: names (tuple[str]): names of the dataset split Returns: a 32x32x3 image, the mean of all images in the given datasets
tensorpack/dataflow/dataset/svhn.py
def get_per_pixel_mean(names=('train', 'test', 'extra')): """ Args: names (tuple[str]): names of the dataset split Returns: a 32x32x3 image, the mean of all images in the given datasets """ for name in names: assert name in ['train', 'test', '...
def get_per_pixel_mean(names=('train', 'test', 'extra')): """ Args: names (tuple[str]): names of the dataset split Returns: a 32x32x3 image, the mean of all images in the given datasets """ for name in names: assert name in ['train', 'test', '...
[ "Args", ":", "names", "(", "tuple", "[", "str", "]", ")", ":", "names", "of", "the", "dataset", "split" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/svhn.py#L65-L76
[ "def", "get_per_pixel_mean", "(", "names", "=", "(", "'train'", ",", "'test'", ",", "'extra'", ")", ")", ":", "for", "name", "in", "names", ":", "assert", "name", "in", "[", "'train'", ",", "'test'", ",", "'extra'", "]", ",", "name", "images", "=", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
build_or_reuse_placeholder
Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor:
tensorpack/graph_builder/model_desc.py
def build_or_reuse_placeholder(tensor_spec): """ Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor: """ g = tfv1.get_default_graph() name = tensor_spec.name try: te...
def build_or_reuse_placeholder(tensor_spec): """ Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one. Args: tensor_spec (tf.TensorSpec): Returns: tf.Tensor: """ g = tfv1.get_default_graph() name = tensor_spec.name try: te...
[ "Build", "a", "tf", ".", "placeholder", "from", "the", "metadata", "in", "the", "given", "tensor", "spec", "or", "return", "an", "existing", "one", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/model_desc.py#L19-L41
[ "def", "build_or_reuse_placeholder", "(", "tensor_spec", ")", ":", "g", "=", "tfv1", ".", "get_default_graph", "(", ")", "name", "=", "tensor_spec", ".", "name", "try", ":", "tensor", "=", "g", ".", "get_tensor_by_name", "(", "name", "+", "':0'", ")", "ass...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ModelDescBase.get_input_signature
Returns: A list of :class:`tf.TensorSpec`, which describes the inputs of this model. The result is cached for each instance of :class:`ModelDescBase`.
tensorpack/graph_builder/model_desc.py
def get_input_signature(self): """ Returns: A list of :class:`tf.TensorSpec`, which describes the inputs of this model. The result is cached for each instance of :class:`ModelDescBase`. """ with tf.Graph().as_default() as G: # create these placeholder in a tempo...
def get_input_signature(self): """ Returns: A list of :class:`tf.TensorSpec`, which describes the inputs of this model. The result is cached for each instance of :class:`ModelDescBase`. """ with tf.Graph().as_default() as G: # create these placeholder in a tempo...
[ "Returns", ":", "A", "list", "of", ":", "class", ":", "tf", ".", "TensorSpec", "which", "describes", "the", "inputs", "of", "this", "model", ".", "The", "result", "is", "cached", "for", "each", "instance", "of", ":", "class", ":", "ModelDescBase", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/model_desc.py#L79-L92
[ "def", "get_input_signature", "(", "self", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", "as", "G", ":", "# create these placeholder in a temporary graph", "inputs", "=", "self", ".", "inputs", "(", ")", "if", "isinstance", "("...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
dependency_of_targets
Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find dependencies of. op (tf.Operation or tf.Tensor...
tensorpack/tfutils/dependency.py
def dependency_of_targets(targets, op): """ Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find de...
def dependency_of_targets(targets, op): """ Check that op is in the subgraph induced by the dependencies of targets. The result is memoized. This is useful if some SessionRunHooks should be run only together with certain ops. Args: targets: a tuple of ops or tensors. The targets to find de...
[ "Check", "that", "op", "is", "in", "the", "subgraph", "induced", "by", "the", "dependencies", "of", "targets", ".", "The", "result", "is", "memoized", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L16-L38
[ "def", "dependency_of_targets", "(", "targets", ",", "op", ")", ":", "# TODO tensorarray? sparsetensor?", "if", "isinstance", "(", "op", ",", "tf", ".", "Tensor", ")", ":", "op", "=", "op", ".", "op", "assert", "isinstance", "(", "op", ",", "tf", ".", "O...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
dependency_of_fetches
Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns: bool: True if any of `fetches` depend on `o...
tensorpack/tfutils/dependency.py
def dependency_of_fetches(fetches, op): """ Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns:...
def dependency_of_fetches(fetches, op): """ Check that op is in the subgraph induced by the dependencies of fetches. fetches may have more general structure. Args: fetches: An argument to `sess.run`. Nested structure will affect performance. op (tf.Operation or tf.Tensor): Returns:...
[ "Check", "that", "op", "is", "in", "the", "subgraph", "induced", "by", "the", "dependencies", "of", "fetches", ".", "fetches", "may", "have", "more", "general", "structure", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L41-L66
[ "def", "dependency_of_fetches", "(", "fetches", ",", "op", ")", ":", "try", ":", "from", "tensorflow", ".", "python", ".", "client", ".", "session", "import", "_FetchHandler", "as", "FetchHandler", "# use the graph of the op, so that this function can be called without be...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
create_scalar_summary
Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v.
tensorpack/tfutils/summary.py
def create_scalar_summary(name, v): """ Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v. """ assert isinstance(name, six.string_types), type(name) v = float(v) s = tf.Summary() s.value.add(tag=...
def create_scalar_summary(name, v): """ Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v. """ assert isinstance(name, six.string_types), type(name) v = float(v) s = tf.Summary() s.value.add(tag=...
[ "Args", ":", "name", "(", "str", ")", ":", "v", "(", "float", ")", ":", "scalar", "value", "Returns", ":", "tf", ".", "Summary", ":", "a", "tf", ".", "Summary", "object", "with", "name", "and", "simple", "scalar", "value", "v", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L41-L53
[ "def", "create_scalar_summary", "(", "name", ",", "v", ")", ":", "assert", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", ",", "type", "(", "name", ")", "v", "=", "float", "(", "v", ")", "s", "=", "tf", ".", "Summary", "(", ")", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
create_image_summary
Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary:
tensorpack/tfutils/summary.py
def create_image_summary(name, val): """ Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary: """ assert isinstance(name, six.string_types), type(name) n, h, w, c ...
def create_image_summary(name, val): """ Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB if C==3. Can be either float or uint8. Range has to be [0,255]. Returns: tf.Summary: """ assert isinstance(name, six.string_types), type(name) n, h, w, c ...
[ "Args", ":", "name", "(", "str", ")", ":", "val", "(", "np", ".", "ndarray", ")", ":", "4D", "tensor", "of", "NHWC", ".", "assume", "RGB", "if", "C", "==", "3", ".", "Can", "be", "either", "float", "or", "uint8", ".", "Range", "has", "to", "be"...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L56-L92
[ "def", "create_image_summary", "(", "name", ",", "val", ")", ":", "assert", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", ",", "type", "(", "name", ")", "n", ",", "h", ",", "w", ",", "c", "=", "val", ".", "shape", "val", "=", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
add_tensor_summary
Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str): summary name. Defaults to be the op name. collections (list[str]): collections of the summary ops. main...
tensorpack/tfutils/summary.py
def add_tensor_summary(x, types, name=None, collections=None, main_tower_only=True): """ Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str):...
def add_tensor_summary(x, types, name=None, collections=None, main_tower_only=True): """ Summarize a tensor by different methods. Args: x (tf.Tensor): a tensor to summarize types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms name (str):...
[ "Summarize", "a", "tensor", "by", "different", "methods", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L95-L137
[ "def", "add_tensor_summary", "(", "x", ",", "types", ",", "name", "=", "None", ",", "collections", "=", "None", ",", "main_tower_only", "=", "True", ")", ":", "types", "=", "set", "(", "types", ")", "if", "name", "is", "None", ":", "name", "=", "x", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
add_activation_summary
Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``. name (str): i...
tensorpack/tfutils/summary.py
def add_activation_summary(x, types=None, name=None, collections=None): """ Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): su...
def add_activation_summary(x, types=None, name=None, collections=None): """ Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope. This function is a no-op if not calling from main training tower. Args: x (tf.Tensor): the tensor to summary. types (list[str]): su...
[ "Call", ":", "func", ":", "add_tensor_summary", "under", "a", "reused", "activation", "-", "summary", "name", "scope", ".", "This", "function", "is", "a", "no", "-", "op", "if", "not", "calling", "from", "main", "training", "tower", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L140-L158
[ "def", "add_activation_summary", "(", "x", ",", "types", "=", "None", ",", "name", "=", "None", ",", "collections", "=", "None", ")", ":", "ndim", "=", "x", ".", "get_shape", "(", ")", ".", "ndims", "if", "ndim", "<", "2", ":", "logger", ".", "warn...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
add_param_summary
Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type]). Summary type is defined in :func:`add_tensor_...
tensorpack/tfutils/summary.py
def add_param_summary(*summary_lists, **kwargs): """ Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type...
def add_param_summary(*summary_lists, **kwargs): """ Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type...
[ "Add", "summary", "ops", "for", "all", "trainable", "variables", "matching", "the", "regex", "under", "a", "reused", "param", "-", "summary", "name", "scope", ".", "This", "function", "is", "a", "no", "-", "op", "if", "not", "calling", "from", "main", "t...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L161-L195
[ "def", "add_param_summary", "(", "*", "summary_lists", ",", "*", "*", "kwargs", ")", ":", "collections", "=", "kwargs", ".", "pop", "(", "'collections'", ",", "None", ")", "assert", "len", "(", "kwargs", ")", "==", "0", ",", "\"Unknown kwargs: \"", "+", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
add_moving_summary
Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the name of the collection to add EMA-maintaining ops. ...
tensorpack/tfutils/summary.py
def add_moving_summary(*args, **kwargs): """ Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the ...
def add_moving_summary(*args, **kwargs): """ Summarize the moving average for scalar tensors. This function is a no-op if not calling from main training tower. Args: args: scalar tensors to summarize decay (float): the decay rate. Defaults to 0.95. collection (str or None): the ...
[ "Summarize", "the", "moving", "average", "for", "scalar", "tensors", ".", "This", "function", "is", "a", "no", "-", "op", "if", "not", "calling", "from", "main", "training", "tower", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L198-L270
[ "def", "add_moving_summary", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "decay", "=", "kwargs", ".", "pop", "(", "'decay'", ",", "0.95", ")", "coll", "=", "kwargs", ".", "pop", "(", "'collection'", ",", "MOVING_SUMMARY_OPS_KEY", ")", "summ_coll...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
CascadeRCNNHead.run_head
Args: proposals: BoxProposals stage: 0, 1, 2 Returns: FastRCNNHead Nx4, updated boxes
examples/FasterRCNN/model_cascade.py
def run_head(self, proposals, stage): """ Args: proposals: BoxProposals stage: 0, 1, 2 Returns: FastRCNNHead Nx4, updated boxes """ reg_weights = tf.constant(cfg.CASCADE.BBOX_REG_WEIGHTS[stage], dtype=tf.float32) pooled_fea...
def run_head(self, proposals, stage): """ Args: proposals: BoxProposals stage: 0, 1, 2 Returns: FastRCNNHead Nx4, updated boxes """ reg_weights = tf.constant(cfg.CASCADE.BBOX_REG_WEIGHTS[stage], dtype=tf.float32) pooled_fea...
[ "Args", ":", "proposals", ":", "BoxProposals", "stage", ":", "0", "1", "2" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L54-L74
[ "def", "run_head", "(", "self", ",", "proposals", ",", "stage", ")", ":", "reg_weights", "=", "tf", ".", "constant", "(", "cfg", ".", "CASCADE", ".", "BBOX_REG_WEIGHTS", "[", "stage", "]", ",", "dtype", "=", "tf", ".", "float32", ")", "pooled_feature", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
CascadeRCNNHead.match_box_with_gt
Args: boxes: Nx4 Returns: BoxProposals
examples/FasterRCNN/model_cascade.py
def match_box_with_gt(self, boxes, iou_threshold): """ Args: boxes: Nx4 Returns: BoxProposals """ if self.is_training: with tf.name_scope('match_box_with_gt_{}'.format(iou_threshold)): iou = pairwise_iou(boxes, self.gt_boxes) #...
def match_box_with_gt(self, boxes, iou_threshold): """ Args: boxes: Nx4 Returns: BoxProposals """ if self.is_training: with tf.name_scope('match_box_with_gt_{}'.format(iou_threshold)): iou = pairwise_iou(boxes, self.gt_boxes) #...
[ "Args", ":", "boxes", ":", "Nx4", "Returns", ":", "BoxProposals" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L76-L94
[ "def", "match_box_with_gt", "(", "self", ",", "boxes", ",", "iou_threshold", ")", ":", "if", "self", ".", "is_training", ":", "with", "tf", ".", "name_scope", "(", "'match_box_with_gt_{}'", ".", "format", "(", "iou_threshold", ")", ")", ":", "iou", "=", "p...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
CascadeRCNNHead.decoded_output_boxes
Returns: Nx#classx4
examples/FasterRCNN/model_cascade.py
def decoded_output_boxes(self): """ Returns: Nx#classx4 """ ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
def decoded_output_boxes(self): """ Returns: Nx#classx4 """ ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
[ "Returns", ":", "Nx#classx4" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L103-L110
[ "def", "decoded_output_boxes", "(", "self", ")", ":", "ret", "=", "self", ".", "_cascade_boxes", "[", "-", "1", "]", "ret", "=", "tf", ".", "expand_dims", "(", "ret", ",", "1", ")", "# class-agnostic", "return", "tf", ".", "tile", "(", "ret", ",", "[...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
CascadeRCNNHead.output_scores
Returns: Nx#class
examples/FasterRCNN/model_cascade.py
def output_scores(self, name=None): """ Returns: Nx#class """ scores = [head.output_scores('cascade_scores_stage{}'.format(idx + 1)) for idx, head in enumerate(self._heads)] return tf.multiply(tf.add_n(scores), (1.0 / self.num_cascade_stages), name=n...
def output_scores(self, name=None): """ Returns: Nx#class """ scores = [head.output_scores('cascade_scores_stage{}'.format(idx + 1)) for idx, head in enumerate(self._heads)] return tf.multiply(tf.add_n(scores), (1.0 / self.num_cascade_stages), name=n...
[ "Returns", ":", "Nx#class" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L112-L119
[ "def", "output_scores", "(", "self", ",", "name", "=", "None", ")", ":", "scores", "=", "[", "head", ".", "output_scores", "(", "'cascade_scores_stage{}'", ".", "format", "(", "idx", "+", "1", ")", ")", "for", "idx", ",", "head", "in", "enumerate", "("...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
do_visualize
Visualize some intermediate results (proposals, raw predictions) inside the pipeline.
examples/FasterRCNN/train.py
def do_visualize(model, model_path, nr_visualize=100, output_dir='output'): """ Visualize some intermediate results (proposals, raw predictions) inside the pipeline. """ df = get_train_dataflow() # we don't visualize mask stuff df.reset_state() pred = OfflinePredictor(PredictConfig( m...
def do_visualize(model, model_path, nr_visualize=100, output_dir='output'): """ Visualize some intermediate results (proposals, raw predictions) inside the pipeline. """ df = get_train_dataflow() # we don't visualize mask stuff df.reset_state() pred = OfflinePredictor(PredictConfig( m...
[ "Visualize", "some", "intermediate", "results", "(", "proposals", "raw", "predictions", ")", "inside", "the", "pipeline", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/train.py#L34-L83
[ "def", "do_visualize", "(", "model", ",", "model_path", ",", "nr_visualize", "=", "100", ",", "output_dir", "=", "'output'", ")", ":", "df", "=", "get_train_dataflow", "(", ")", "# we don't visualize mask stuff", "df", ".", "reset_state", "(", ")", "pred", "="...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
get_registered_layer
Args: name (str): the name of the layer, e.g. 'Conv2D' Returns: the wrapped layer function, or None if not registered.
tensorpack/models/registry.py
def get_registered_layer(name): """ Args: name (str): the name of the layer, e.g. 'Conv2D' Returns: the wrapped layer function, or None if not registered. """ ret = _LAYER_REGISTRY.get(name, None) if ret == _NameConflict: raise KeyError("Layer named '{}' is registered wit...
def get_registered_layer(name): """ Args: name (str): the name of the layer, e.g. 'Conv2D' Returns: the wrapped layer function, or None if not registered. """ ret = _LAYER_REGISTRY.get(name, None) if ret == _NameConflict: raise KeyError("Layer named '{}' is registered wit...
[ "Args", ":", "name", "(", "str", ")", ":", "the", "name", "of", "the", "layer", "e", ".", "g", ".", "Conv2D", "Returns", ":", "the", "wrapped", "layer", "function", "or", "None", "if", "not", "registered", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/registry.py#L39-L49
[ "def", "get_registered_layer", "(", "name", ")", ":", "ret", "=", "_LAYER_REGISTRY", ".", "get", "(", "name", ",", "None", ")", "if", "ret", "==", "_NameConflict", ":", "raise", "KeyError", "(", "\"Layer named '{}' is registered with `@layer_register` more than once!\...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
layer_register
Args: log_shape (bool): log input/output shape of this layer use_scope (bool or None): Whether to call this layer with an extra first argument as variable scope. When set to None, it can be called either with or without the scope name argument, depend on whether the f...
tensorpack/models/registry.py
def layer_register( log_shape=False, use_scope=True): """ Args: log_shape (bool): log input/output shape of this layer use_scope (bool or None): Whether to call this layer with an extra first argument as variable scope. When set to None, it can be called e...
def layer_register( log_shape=False, use_scope=True): """ Args: log_shape (bool): log input/output shape of this layer use_scope (bool or None): Whether to call this layer with an extra first argument as variable scope. When set to None, it can be called e...
[ "Args", ":", "log_shape", "(", "bool", ")", ":", "log", "input", "/", "output", "shape", "of", "this", "layer", "use_scope", "(", "bool", "or", "None", ")", ":", "Whether", "to", "call", "this", "layer", "with", "an", "extra", "first", "argument", "as"...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/registry.py#L64-L155
[ "def", "layer_register", "(", "log_shape", "=", "False", ",", "use_scope", "=", "True", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
TowerTrainer.get_predictor
This method will build the trainer's tower function under ``TowerContext(is_training=False)``, and returns a callable predictor with input placeholders & output tensors in this tower. This method handles the common case of inference with the same tower function. If you want to do inference with...
tensorpack/train/tower.py
def get_predictor(self, input_names, output_names, device=0): """ This method will build the trainer's tower function under ``TowerContext(is_training=False)``, and returns a callable predictor with input placeholders & output tensors in this tower. This method handles the common case o...
def get_predictor(self, input_names, output_names, device=0): """ This method will build the trainer's tower function under ``TowerContext(is_training=False)``, and returns a callable predictor with input placeholders & output tensors in this tower. This method handles the common case o...
[ "This", "method", "will", "build", "the", "trainer", "s", "tower", "function", "under", "TowerContext", "(", "is_training", "=", "False", ")", "and", "returns", "a", "callable", "predictor", "with", "input", "placeholders", "&", "output", "tensors", "in", "thi...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/tower.py#L89-L147
[ "def", "get_predictor", "(", "self", ",", "input_names", ",", "output_names", ",", "device", "=", "0", ")", ":", "assert", "self", ".", "tower_func", "is", "not", "None", ",", "\"Must set tower_func on the trainer to use get_predictor()!\"", "tower_name", "=", "'tow...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
export_serving
Export trained model to use it in TensorFlow Serving or cloudML.
examples/basics/export-model.py
def export_serving(model_path): """Export trained model to use it in TensorFlow Serving or cloudML. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) ...
def export_serving(model_path): """Export trained model to use it in TensorFlow Serving or cloudML. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['prediction_img_bytes']) ...
[ "Export", "trained", "model", "to", "use", "it", "in", "TensorFlow", "Serving", "or", "cloudML", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L106-L113
[ "def", "export_serving", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "InferenceOnlyModel", "(", ")", ",", "input_names", "=", "[", "'input_img_bytes'", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
export_compact
Export trained model to use it as a frozen and pruned inference graph in mobile applications.
examples/basics/export-model.py
def export_compact(model_path): """Export trained model to use it as a frozen and pruned inference graph in mobile applications. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_...
def export_compact(model_path): """Export trained model to use it as a frozen and pruned inference graph in mobile applications. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_...
[ "Export", "trained", "model", "to", "use", "it", "as", "a", "frozen", "and", "pruned", "inference", "graph", "in", "mobile", "applications", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L116-L124
[ "def", "export_compact", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "Model", "(", ")", ",", "input_names", "=", "[", "'input_img'", "]", ",", "out...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
apply
Run inference from a training model checkpoint.
examples/basics/export-model.py
def apply(model_path): """Run inference from a training model checkpoint. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) pred = OfflinePredictor(pred_config) img = cv2...
def apply(model_path): """Run inference from a training model checkpoint. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=Model(), input_names=['input_img'], output_names=['prediction_img']) pred = OfflinePredictor(pred_config) img = cv2...
[ "Run", "inference", "from", "a", "training", "model", "checkpoint", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L127-L138
[ "def", "apply", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "Model", "(", ")", ",", "input_names", "=", "[", "'input_img'", "]", ",", "output_names...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
apply_inference_graph
Run inference from a different graph, which receives encoded images buffers.
examples/basics/export-model.py
def apply_inference_graph(model_path): """Run inference from a different graph, which receives encoded images buffers. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['predictio...
def apply_inference_graph(model_path): """Run inference from a different graph, which receives encoded images buffers. """ pred_config = PredictConfig( session_init=get_model_loader(model_path), model=InferenceOnlyModel(), input_names=['input_img_bytes'], output_names=['predictio...
[ "Run", "inference", "from", "a", "different", "graph", "which", "receives", "encoded", "images", "buffers", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L141-L153
[ "def", "apply_inference_graph", "(", "model_path", ")", ":", "pred_config", "=", "PredictConfig", "(", "session_init", "=", "get_model_loader", "(", "model_path", ")", ",", "model", "=", "InferenceOnlyModel", "(", ")", ",", "input_names", "=", "[", "'input_img_byt...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
apply_compact
Run the pruned and frozen inference graph.
examples/basics/export-model.py
def apply_compact(graph_path): """Run the pruned and frozen inference graph. """ with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def =...
def apply_compact(graph_path): """Run the pruned and frozen inference graph. """ with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: # Note, we just load the graph and do *not* need to initialize anything. with tf.gfile.GFile(graph_path, "rb") as f: graph_def =...
[ "Run", "the", "pruned", "and", "frozen", "inference", "graph", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L156-L169
[ "def", "apply_compact", "(", "graph_path", ")", ":", "with", "tf", ".", "Session", "(", "config", "=", "tf", ".", "ConfigProto", "(", "allow_soft_placement", "=", "True", ")", ")", "as", "sess", ":", "# Note, we just load the graph and do *not* need to initialize an...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
BatchNorm
Mostly equivalent to `tf.layers.batch_normalization`, but difference in the following: 1. Accepts `data_format` rather than `axis`. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `training` is automatically obtained from `Tow...
tensorpack/models/_old_batch_norm.py
def BatchNorm(inputs, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=tf.ones_initializer(), data_format='channels_last', internal_update=False): """ Mostly equivalent to `tf.layers.batch_normalization`, but difference...
def BatchNorm(inputs, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=tf.ones_initializer(), data_format='channels_last', internal_update=False): """ Mostly equivalent to `tf.layers.batch_normalization`, but difference...
[ "Mostly", "equivalent", "to", "tf", ".", "layers", ".", "batch_normalization", "but", "difference", "in", "the", "following", ":", "1", ".", "Accepts", "data_format", "rather", "than", "axis", ".", "For", "2D", "input", "this", "argument", "will", "be", "ign...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/_old_batch_norm.py#L67-L169
[ "def", "BatchNorm", "(", "inputs", ",", "training", "=", "None", ",", "momentum", "=", "0.9", ",", "epsilon", "=", "1e-5", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "gamma_initializer", "=", "tf", ".", "ones_initializer", "(", ")", ",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
SelectComponent
Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,1] this df: [c3, c2]
tensorpack/dataflow/common.py
def SelectComponent(ds, idxs): """ Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,1] this df: [c3, c...
def SelectComponent(ds, idxs): """ Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none original df produces: [c1, c2, c3] idxs: [2,1] this df: [c3, c...
[ "Select", "/", "reorder", "components", "from", "datapoints", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/common.py#L570-L586
[ "def", "SelectComponent", "(", "ds", ",", "idxs", ")", ":", "return", "MapData", "(", "ds", ",", "lambda", "dp", ":", "[", "dp", "[", "i", "]", "for", "i", "in", "idxs", "]", ")" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
PrintData._analyze_input_data
Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth max_depth, max_list: same as in :meth:`__init__`. Returns: str...
tensorpack/dataflow/common.py
def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3): """ Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth ...
def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3): """ Gather useful debug information from a datapoint. Args: entry: the datapoint component k (int): index of this component in current datapoint depth (int, optional): recursion depth ...
[ "Gather", "useful", "debug", "information", "from", "a", "datapoint", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/common.py#L745-L804
[ "def", "_analyze_input_data", "(", "self", ",", "entry", ",", "k", ",", "depth", "=", "1", ",", "max_depth", "=", "3", ",", "max_list", "=", "3", ")", ":", "class", "_elementInfo", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "el", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
RatioCounter.feed
Args: cnt(int): the count of some event of interest. tot(int): the total number of events.
tensorpack/utils/stats.py
def feed(self, count, total=1): """ Args: cnt(int): the count of some event of interest. tot(int): the total number of events. """ self._tot += total self._cnt += count
def feed(self, count, total=1): """ Args: cnt(int): the count of some event of interest. tot(int): the total number of events. """ self._tot += total self._cnt += count
[ "Args", ":", "cnt", "(", "int", ")", ":", "the", "count", "of", "some", "event", "of", "interest", ".", "tot", "(", "int", ")", ":", "the", "total", "number", "of", "events", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/stats.py#L67-L74
[ "def", "feed", "(", "self", ",", "count", ",", "total", "=", "1", ")", ":", "self", ".", "_tot", "+=", "total", "self", ".", "_cnt", "+=", "count" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
BinaryStatistics.feed
Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size.
tensorpack/utils/stats.py
def feed(self, pred, label): """ Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size. """ assert pred.shape == label.shape, "{} != {}".format(pred.shape, label.shape) self.nr_pos += (label == 1).sum() self.nr_ne...
def feed(self, pred, label): """ Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size. """ assert pred.shape == label.shape, "{} != {}".format(pred.shape, label.shape) self.nr_pos += (label == 1).sum() self.nr_ne...
[ "Args", ":", "pred", "(", "np", ".", "ndarray", ")", ":", "binary", "array", ".", "label", "(", "np", ".", "ndarray", ")", ":", "binary", "array", "of", "the", "same", "size", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/stats.py#L123-L135
[ "def", "feed", "(", "self", ",", "pred", ",", "label", ")", ":", "assert", "pred", ".", "shape", "==", "label", ".", "shape", ",", "\"{} != {}\"", ".", "format", "(", "pred", ".", "shape", ",", "label", ".", "shape", ")", "self", ".", "nr_pos", "+=...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
OnlineMoments.feed
Args: x (float or np.ndarray): must have the same shape.
tensorpack/utils/stats.py
def feed(self, x): """ Args: x (float or np.ndarray): must have the same shape. """ self._n += 1 delta = x - self._mean self._mean += delta * (1.0 / self._n) delta2 = x - self._mean self._M2 += delta * delta2
def feed(self, x): """ Args: x (float or np.ndarray): must have the same shape. """ self._n += 1 delta = x - self._mean self._mean += delta * (1.0 / self._n) delta2 = x - self._mean self._M2 += delta * delta2
[ "Args", ":", "x", "(", "float", "or", "np", ".", "ndarray", ")", ":", "must", "have", "the", "same", "shape", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/stats.py#L173-L182
[ "def", "feed", "(", "self", ",", "x", ")", ":", "self", ".", "_n", "+=", "1", "delta", "=", "x", "-", "self", ".", "_mean", "self", ".", "_mean", "+=", "delta", "*", "(", "1.0", "/", "self", ".", "_n", ")", "delta2", "=", "x", "-", "self", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
apply_grad_processors
Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updati...
tensorpack/tfutils/optimizer.py
def apply_grad_processors(opt, gradprocs): """ Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance w...
def apply_grad_processors(opt, gradprocs): """ Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance w...
[ "Wrapper", "around", "optimizers", "to", "apply", "gradient", "processors", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/optimizer.py#L44-L76
[ "def", "apply_grad_processors", "(", "opt", ",", "gradprocs", ")", ":", "assert", "isinstance", "(", "gradprocs", ",", "(", "list", ",", "tuple", ")", ")", ",", "gradprocs", "for", "gp", "in", "gradprocs", ":", "assert", "isinstance", "(", "gp", ",", "Gr...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
_paste_mask
Args: box: 4 float mask: MxM floats shape: h,w Returns: A uint8 binary image of hxw.
examples/FasterRCNN/eval.py
def _paste_mask(box, mask, shape): """ Args: box: 4 float mask: MxM floats shape: h,w Returns: A uint8 binary image of hxw. """ # int() is floor # box fpcoor=0.0 -> intcoor=0.0 x0, y0 = list(map(int, box[:2] + 0.5)) # box fpcoor=h -> intcoor=h-1, inclusive...
def _paste_mask(box, mask, shape): """ Args: box: 4 float mask: MxM floats shape: h,w Returns: A uint8 binary image of hxw. """ # int() is floor # box fpcoor=0.0 -> intcoor=0.0 x0, y0 = list(map(int, box[:2] + 0.5)) # box fpcoor=h -> intcoor=h-1, inclusive...
[ "Args", ":", "box", ":", "4", "float", "mask", ":", "MxM", "floats", "shape", ":", "h", "w", "Returns", ":", "A", "uint8", "binary", "image", "of", "hxw", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L44-L69
[ "def", "_paste_mask", "(", "box", ",", "mask", ",", "shape", ")", ":", "# int() is floor", "# box fpcoor=0.0 -> intcoor=0.0", "x0", ",", "y0", "=", "list", "(", "map", "(", "int", ",", "box", "[", ":", "2", "]", "+", "0.5", ")", ")", "# box fpcoor=h -> i...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
predict_image
Run detection on one image, using the TF callable. This function should handle the preprocessing internally. Args: img: an image model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) Returns: [DetectionResult]
examples/FasterRCNN/eval.py
def predict_image(img, model_func): """ Run detection on one image, using the TF callable. This function should handle the preprocessing internally. Args: img: an image model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) ...
def predict_image(img, model_func): """ Run detection on one image, using the TF callable. This function should handle the preprocessing internally. Args: img: an image model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) ...
[ "Run", "detection", "on", "one", "image", "using", "the", "TF", "callable", ".", "This", "function", "should", "handle", "the", "preprocessing", "internally", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L72-L105
[ "def", "predict_image", "(", "img", ",", "model_func", ")", ":", "orig_shape", "=", "img", ".", "shape", "[", ":", "2", "]", "resizer", "=", "CustomResize", "(", "cfg", ".", "PREPROC", ".", "TEST_SHORT_EDGE_SIZE", ",", "cfg", ".", "PREPROC", ".", "MAX_SI...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
predict_dataflow
Args: df: a DataFlow which produces (image, image_id) model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) tqdm_bar: a tqdm object to be shared among multiple evaluation instances. If None, will create a new one. Return...
examples/FasterRCNN/eval.py
def predict_dataflow(df, model_func, tqdm_bar=None): """ Args: df: a DataFlow which produces (image, image_id) model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) tqdm_bar: a tqdm object to be shared among multiple evaluation i...
def predict_dataflow(df, model_func, tqdm_bar=None): """ Args: df: a DataFlow which produces (image, image_id) model_func: a callable from the TF model. It takes image and returns (boxes, probs, labels, [masks]) tqdm_bar: a tqdm object to be shared among multiple evaluation i...
[ "Args", ":", "df", ":", "a", "DataFlow", "which", "produces", "(", "image", "image_id", ")", "model_func", ":", "a", "callable", "from", "the", "TF", "model", ".", "It", "takes", "image", "and", "returns", "(", "boxes", "probs", "labels", "[", "masks", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L108-L146
[ "def", "predict_dataflow", "(", "df", ",", "model_func", ",", "tqdm_bar", "=", "None", ")", ":", "df", ".", "reset_state", "(", ")", "all_results", "=", "[", "]", "with", "ExitStack", "(", ")", "as", "stack", ":", "# tqdm is not quite thread-safe: https://gith...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
multithread_predict_dataflow
Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow` Returns: list of dict, in the format used by `De...
examples/FasterRCNN/eval.py
def multithread_predict_dataflow(dataflows, model_funcs): """ Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow`...
def multithread_predict_dataflow(dataflows, model_funcs): """ Running multiple `predict_dataflow` in multiple threads, and aggregate the results. Args: dataflows: a list of DataFlow to be used in :func:`predict_dataflow` model_funcs: a list of callable to be used in :func:`predict_dataflow`...
[ "Running", "multiple", "predict_dataflow", "in", "multiple", "threads", "and", "aggregate", "the", "results", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L149-L172
[ "def", "multithread_predict_dataflow", "(", "dataflows", ",", "model_funcs", ")", ":", "num_worker", "=", "len", "(", "model_funcs", ")", "assert", "len", "(", "dataflows", ")", "==", "num_worker", "if", "num_worker", "==", "1", ":", "return", "predict_dataflow"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
batch_flatten
Flatten the tensor except the first dimension.
tensorpack/models/fc.py
def batch_flatten(x): """ Flatten the tensor except the first dimension. """ shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, int(np.prod(shape))]) return tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
def batch_flatten(x): """ Flatten the tensor except the first dimension. """ shape = x.get_shape().as_list()[1:] if None not in shape: return tf.reshape(x, [-1, int(np.prod(shape))]) return tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
[ "Flatten", "the", "tensor", "except", "the", "first", "dimension", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/fc.py#L15-L22
[ "def", "batch_flatten", "(", "x", ")", ":", "shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", "if", "None", "not", "in", "shape", ":", "return", "tf", ".", "reshape", "(", "x", ",", "[", "-", "1", ",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
FullyConnected
A wrapper around `tf.layers.Dense`. One difference to maintain backward-compatibility: Default weight initializer is variance_scaling_initializer(2.0). Variable Names: * ``W``: weights of shape [in_dim, out_dim] * ``b``: bias
tensorpack/models/fc.py
def FullyConnected( inputs, units, activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None): """ A wrapper around `tf.layers...
def FullyConnected( inputs, units, activation=None, use_bias=True, kernel_initializer=None, bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None): """ A wrapper around `tf.layers...
[ "A", "wrapper", "around", "tf", ".", "layers", ".", "Dense", ".", "One", "difference", "to", "maintain", "backward", "-", "compatibility", ":", "Default", "weight", "initializer", "is", "variance_scaling_initializer", "(", "2", ".", "0", ")", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/fc.py#L29-L73
[ "def", "FullyConnected", "(", "inputs", ",", "units", ",", "activation", "=", "None", ",", "use_bias", "=", "True", ",", "kernel_initializer", "=", "None", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "kernel_regularizer", "=", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
MultiProcessPredictWorker._init_runtime
Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs
tensorpack/predict/concurrency.py
def _init_runtime(self): """ Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs """ if self.idx != 0: from tensorpack.models.registry import disable_layer_logging disable_layer_logging() self.predictor = ...
def _init_runtime(self): """ Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs """ if self.idx != 0: from tensorpack.models.registry import disable_layer_logging disable_layer_logging() self.predictor = ...
[ "Call", "_init_runtime", "under", "different", "CUDA_VISIBLE_DEVICES", "you", "ll", "have", "workers", "that", "run", "on", "multiGPUs" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L35-L45
[ "def", "_init_runtime", "(", "self", ")", ":", "if", "self", ".", "idx", "!=", "0", ":", "from", "tensorpack", ".", "models", ".", "registry", "import", "disable_layer_logging", "disable_layer_logging", "(", ")", "self", ".", "predictor", "=", "OfflinePredicto...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
PredictorWorkerThread.fetch_batch
Fetch a batch of data without waiting
tensorpack/predict/concurrency.py
def fetch_batch(self): """ Fetch a batch of data without waiting""" inp, f = self.queue.get() nr_input_var = len(inp) batched, futures = [[] for _ in range(nr_input_var)], [] for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) whi...
def fetch_batch(self): """ Fetch a batch of data without waiting""" inp, f = self.queue.get() nr_input_var = len(inp) batched, futures = [[] for _ in range(nr_input_var)], [] for k in range(nr_input_var): batched[k].append(inp[k]) futures.append(f) whi...
[ "Fetch", "a", "batch", "of", "data", "without", "waiting" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L110-L129
[ "def", "fetch_batch", "(", "self", ")", ":", "inp", ",", "f", "=", "self", ".", "queue", ".", "get", "(", ")", "nr_input_var", "=", "len", "(", "inp", ")", "batched", ",", "futures", "=", "[", "[", "]", "for", "_", "in", "range", "(", "nr_input_v...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
MultiThreadAsyncPredictor.put_task
Same as in :meth:`AsyncPredictorBase.put_task`.
tensorpack/predict/concurrency.py
def put_task(self, dp, callback=None): """ Same as in :meth:`AsyncPredictorBase.put_task`. """ f = Future() if callback is not None: f.add_done_callback(callback) self.input_queue.put((dp, f)) return f
def put_task(self, dp, callback=None): """ Same as in :meth:`AsyncPredictorBase.put_task`. """ f = Future() if callback is not None: f.add_done_callback(callback) self.input_queue.put((dp, f)) return f
[ "Same", "as", "in", ":", "meth", ":", "AsyncPredictorBase", ".", "put_task", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L172-L180
[ "def", "put_task", "(", "self", ",", "dp", ",", "callback", "=", "None", ")", ":", "f", "=", "Future", "(", ")", "if", "callback", "is", "not", "None", ":", "f", ".", "add_done_callback", "(", "callback", ")", "self", ".", "input_queue", ".", "put", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
loads_msgpack
Args: buf: the output of `dumps`.
tensorpack/utils/serialize.py
def loads_msgpack(buf): """ Args: buf: the output of `dumps`. """ # Since 0.6, the default max size was set to 1MB. # We change it to approximately 1G. return msgpack.loads(buf, raw=False, max_bin_len=MAX_MSGPACK_LEN, max_array_len=MAX_MS...
def loads_msgpack(buf): """ Args: buf: the output of `dumps`. """ # Since 0.6, the default max size was set to 1MB. # We change it to approximately 1G. return msgpack.loads(buf, raw=False, max_bin_len=MAX_MSGPACK_LEN, max_array_len=MAX_MS...
[ "Args", ":", "buf", ":", "the", "output", "of", "dumps", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/serialize.py#L32-L43
[ "def", "loads_msgpack", "(", "buf", ")", ":", "# Since 0.6, the default max size was set to 1MB.", "# We change it to approximately 1G.", "return", "msgpack", ".", "loads", "(", "buf", ",", "raw", "=", "False", ",", "max_bin_len", "=", "MAX_MSGPACK_LEN", ",", "max_array...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
BatchNorm
Almost equivalent to `tf.layers.batch_normalization`, but different (and more powerful) in the following: 1. Accepts an alternative `data_format` option when `axis` is None. For 2D input, this argument will be ignored. 2. Default value for `momentum` and `epsilon` is different. 3. Default value for `tr...
tensorpack/models/batch_norm.py
def BatchNorm(inputs, axis=None, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, beta_initializer=tf.zeros_initializer(), gamma_initializer=tf.ones_initializer(), virtual_batch_size=None, data_format='channels_last', ...
def BatchNorm(inputs, axis=None, training=None, momentum=0.9, epsilon=1e-5, center=True, scale=True, beta_initializer=tf.zeros_initializer(), gamma_initializer=tf.ones_initializer(), virtual_batch_size=None, data_format='channels_last', ...
[ "Almost", "equivalent", "to", "tf", ".", "layers", ".", "batch_normalization", "but", "different", "(", "and", "more", "powerful", ")", "in", "the", "following", ":" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/batch_norm.py#L68-L319
[ "def", "BatchNorm", "(", "inputs", ",", "axis", "=", "None", ",", "training", "=", "None", ",", "momentum", "=", "0.9", ",", "epsilon", "=", "1e-5", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "beta_initializer", "=", "tf", ".", "zero...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
BatchRenorm
Batch Renormalization layer, as described in the paper: `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normalized Models <https://arxiv.org/abs/1702.03275>`_. This implementation is a wrapper around `tf.layers.batch_normalization`. Args: x (tf.Tensor): a NHWC or NC tenso...
tensorpack/models/batch_norm.py
def BatchRenorm(x, rmax, dmax, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=None, data_format='channels_last'): """ Batch Renormalization layer, as described in the paper: `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normali...
def BatchRenorm(x, rmax, dmax, momentum=0.9, epsilon=1e-5, center=True, scale=True, gamma_initializer=None, data_format='channels_last'): """ Batch Renormalization layer, as described in the paper: `Batch Renormalization: Towards Reducing Minibatch Dependence in Batch-Normali...
[ "Batch", "Renormalization", "layer", "as", "described", "in", "the", "paper", ":", "Batch", "Renormalization", ":", "Towards", "Reducing", "Minibatch", "Dependence", "in", "Batch", "-", "Normalized", "Models", "<https", ":", "//", "arxiv", ".", "org", "/", "ab...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/batch_norm.py#L331-L399
[ "def", "BatchRenorm", "(", "x", ",", "rmax", ",", "dmax", ",", "momentum", "=", "0.9", ",", "epsilon", "=", "1e-5", ",", "center", "=", "True", ",", "scale", "=", "True", ",", "gamma_initializer", "=", "None", ",", "data_format", "=", "'channels_last'", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Model.generator
return an image generated from z
examples/GAN/DCGAN.py
def generator(self, z): """ return an image generated from z""" nf = 64 l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity) l = tf.reshape(l, [-1, 4, 4, nf * 8]) l = BNReLU(l) with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2): ...
def generator(self, z): """ return an image generated from z""" nf = 64 l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity) l = tf.reshape(l, [-1, 4, 4, nf * 8]) l = BNReLU(l) with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2): ...
[ "return", "an", "image", "generated", "from", "z" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/DCGAN.py#L46-L58
[ "def", "generator", "(", "self", ",", "z", ")", ":", "nf", "=", "64", "l", "=", "FullyConnected", "(", "'fc0'", ",", "z", ",", "nf", "*", "8", "*", "4", "*", "4", ",", "activation", "=", "tf", ".", "identity", ")", "l", "=", "tf", ".", "resha...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Model.discriminator
return a (b, 1) logits
examples/GAN/DCGAN.py
def discriminator(self, imgs): """ return a (b, 1) logits""" nf = 64 with argscope(Conv2D, kernel_size=4, strides=2): l = (LinearWrap(imgs) .Conv2D('conv0', nf, activation=tf.nn.leaky_relu) .Conv2D('conv1', nf * 2) .BatchNorm('bn1') ...
def discriminator(self, imgs): """ return a (b, 1) logits""" nf = 64 with argscope(Conv2D, kernel_size=4, strides=2): l = (LinearWrap(imgs) .Conv2D('conv0', nf, activation=tf.nn.leaky_relu) .Conv2D('conv1', nf * 2) .BatchNorm('bn1') ...
[ "return", "a", "(", "b", "1", ")", "logits" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/DCGAN.py#L61-L77
[ "def", "discriminator", "(", "self", ",", "imgs", ")", ":", "nf", "=", "64", "with", "argscope", "(", "Conv2D", ",", "kernel_size", "=", "4", ",", "strides", "=", "2", ")", ":", "l", "=", "(", "LinearWrap", "(", "imgs", ")", ".", "Conv2D", "(", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
area
Args: boxes: nx4 floatbox Returns: n
examples/FasterRCNN/utils/box_ops.py
def area(boxes): """ Args: boxes: nx4 floatbox Returns: n """ x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1) return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
def area(boxes): """ Args: boxes: nx4 floatbox Returns: n """ x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1) return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
[ "Args", ":", "boxes", ":", "nx4", "floatbox" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/box_ops.py#L16-L25
[ "def", "area", "(", "boxes", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "tf", ".", "split", "(", "boxes", ",", "4", ",", "axis", "=", "1", ")", "return", "tf", ".", "squeeze", "(", "(", "y_max", "-", "y_min", ")", "*", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
pairwise_intersection
Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections
examples/FasterRCNN/utils/box_ops.py
def pairwise_intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections """ x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=...
def pairwise_intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections """ x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=...
[ "Compute", "pairwise", "intersection", "areas", "between", "boxes", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/box_ops.py#L29-L47
[ "def", "pairwise_intersection", "(", "boxlist1", ",", "boxlist2", ")", ":", "x_min1", ",", "y_min1", ",", "x_max1", ",", "y_max1", "=", "tf", ".", "split", "(", "boxlist1", ",", "4", ",", "axis", "=", "1", ")", "x_min2", ",", "y_min2", ",", "x_max2", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
pairwise_iou
Computes pairwise intersection-over-union between box collections. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise iou scores.
examples/FasterRCNN/utils/box_ops.py
def pairwise_iou(boxlist1, boxlist2): """Computes pairwise intersection-over-union between box collections. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = pairwise_intersection(boxlist1, boxlist...
def pairwise_iou(boxlist1, boxlist2): """Computes pairwise intersection-over-union between box collections. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = pairwise_intersection(boxlist1, boxlist...
[ "Computes", "pairwise", "intersection", "-", "over", "-", "union", "between", "box", "collections", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/box_ops.py#L51-L68
[ "def", "pairwise_iou", "(", "boxlist1", ",", "boxlist2", ")", ":", "intersections", "=", "pairwise_intersection", "(", "boxlist1", ",", "boxlist2", ")", "areas1", "=", "area", "(", "boxlist1", ")", "areas2", "=", "area", "(", "boxlist2", ")", "unions", "=", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
sample
:param path: path to the model :param start: a `str`. the starting characters :param length: a `int`. the length of text to generate
examples/Char-RNN/char-rnn.py
def sample(path, start, length): """ :param path: path to the model :param start: a `str`. the starting characters :param length: a `int`. the length of text to generate """ # initialize vocabulary and sequence length param.seq_len = 1 ds = CharRNNData(param.corpus, 100000) pred = O...
def sample(path, start, length): """ :param path: path to the model :param start: a `str`. the starting characters :param length: a `int`. the length of text to generate """ # initialize vocabulary and sequence length param.seq_len = 1 ds = CharRNNData(param.corpus, 100000) pred = O...
[ ":", "param", "path", ":", "path", "to", "the", "model", ":", "param", "start", ":", "a", "str", ".", "the", "starting", "characters", ":", "param", "length", ":", "a", "int", ".", "the", "length", "of", "text", "to", "generate" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Char-RNN/char-rnn.py#L132-L167
[ "def", "sample", "(", "path", ",", "start", ",", "length", ")", ":", "# initialize vocabulary and sequence length", "param", ".", "seq_len", "=", "1", "ds", "=", "CharRNNData", "(", "param", ".", "corpus", ",", "100000", ")", "pred", "=", "OfflinePredictor", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
Maxout
Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_. Args: x (tf.Tensor): a NHWC or NC tensor. Channel has to be known. num_unit (int): a int. Must be divisible by C. Returns: tf.Tensor: of shape NHW(C/num_unit) named ``output``.
tensorpack/models/nonlin.py
def Maxout(x, num_unit): """ Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_. Args: x (tf.Tensor): a NHWC or NC tensor. Channel has to be known. num_unit (int): a int. Must be divisible by C. Returns: tf.Tensor: of shape NHW(C/num_unit) named ``output...
def Maxout(x, num_unit): """ Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_. Args: x (tf.Tensor): a NHWC or NC tensor. Channel has to be known. num_unit (int): a int. Must be divisible by C. Returns: tf.Tensor: of shape NHW(C/num_unit) named ``output...
[ "Maxout", "as", "in", "the", "paper", "Maxout", "Networks", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1302", ".", "4389", ">", "_", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L15-L35
[ "def", "Maxout", "(", "x", ",", "num_unit", ")", ":", "input_shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "ndim", "=", "len", "(", "input_shape", ")", "assert", "ndim", "==", "4", "or", "ndim", "==", "2", "ch", "=", "in...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
PReLU
Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable slope. name (str): name of the output. V...
tensorpack/models/nonlin.py
def PReLU(x, init=0.001, name='output'): """ Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable ...
def PReLU(x, init=0.001, name='output'): """ Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable ...
[ "Parameterized", "ReLU", "as", "in", "the", "paper", "Delving", "Deep", "into", "Rectifiers", ":", "Surpassing", "Human", "-", "Level", "Performance", "on", "ImageNet", "Classification", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1502", ".", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L39-L60
[ "def", "PReLU", "(", "x", ",", "init", "=", "0.001", ",", "name", "=", "'output'", ")", ":", "init", "=", "tfv1", ".", "constant_initializer", "(", "init", ")", "alpha", "=", "tfv1", ".", "get_variable", "(", "'alpha'", ",", "[", "]", ",", "initializ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
BNReLU
A shorthand of BatchNormalization + ReLU.
tensorpack/models/nonlin.py
def BNReLU(x, name=None): """ A shorthand of BatchNormalization + ReLU. """ x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
def BNReLU(x, name=None): """ A shorthand of BatchNormalization + ReLU. """ x = BatchNorm('bn', x) x = tf.nn.relu(x, name=name) return x
[ "A", "shorthand", "of", "BatchNormalization", "+", "ReLU", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L64-L70
[ "def", "BNReLU", "(", "x", ",", "name", "=", "None", ")", ":", "x", "=", "BatchNorm", "(", "'bn'", ",", "x", ")", "x", "=", "tf", ".", "nn", ".", "relu", "(", "x", ",", "name", "=", "name", ")", "return", "x" ]
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
GroupNorm
More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/.
examples/FasterRCNN/backbone.py
def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): """ More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan...
def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): """ More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan...
[ "More", "code", "that", "reproduces", "the", "paper", "can", "be", "found", "at", "https", ":", "//", "github", ".", "com", "/", "ppwwyyxx", "/", "GroupNorm", "-", "reproduce", "/", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/backbone.py#L17-L44
[ "def", "GroupNorm", "(", "x", ",", "group", "=", "32", ",", "gamma_initializer", "=", "tf", ".", "constant_initializer", "(", "1.", ")", ")", ":", "shape", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "ndims", "=", "len", "(", "s...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
backbone_scope
Args: freeze (bool): whether to freeze all the variables under the scope
examples/FasterRCNN/backbone.py
def backbone_scope(freeze): """ Args: freeze (bool): whether to freeze all the variables under the scope """ def nonlin(x): x = get_norm()(x) return tf.nn.relu(x) with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \ argscope(Conv2D, use...
def backbone_scope(freeze): """ Args: freeze (bool): whether to freeze all the variables under the scope """ def nonlin(x): x = get_norm()(x) return tf.nn.relu(x) with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \ argscope(Conv2D, use...
[ "Args", ":", "freeze", "(", "bool", ")", ":", "whether", "to", "freeze", "all", "the", "variables", "under", "the", "scope" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/backbone.py#L66-L93
[ "def", "backbone_scope", "(", "freeze", ")", ":", "def", "nonlin", "(", "x", ")", ":", "x", "=", "get_norm", "(", ")", "(", "x", ")", "return", "tf", ".", "nn", ".", "relu", "(", "x", ")", "with", "argscope", "(", "[", "Conv2D", ",", "MaxPooling"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
extract_images
Extract the images into a 4D uint8 numpy array [index, y, x, depth].
tensorpack/dataflow/dataset/mnist.py
def extract_images(filename): """Extract the images into a 4D uint8 numpy array [index, y, x, depth].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % ...
def extract_images(filename): """Extract the images into a 4D uint8 numpy array [index, y, x, depth].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % ...
[ "Extract", "the", "images", "into", "a", "4D", "uint8", "numpy", "array", "[", "index", "y", "x", "depth", "]", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/mnist.py#L32-L47
[ "def", "extract_images", "(", "filename", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "magic", "=", "_read32", "(", "bytestream", ")", "if", "magic", "!=", "2051", ":", "raise", "ValueError", "(", "'Invalid magic n...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
extract_labels
Extract the labels into a 1D uint8 numpy array [index].
tensorpack/dataflow/dataset/mnist.py
def extract_labels(filename): """Extract the labels into a 1D uint8 numpy array [index].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (mag...
def extract_labels(filename): """Extract the labels into a 1D uint8 numpy array [index].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (mag...
[ "Extract", "the", "labels", "into", "a", "1D", "uint8", "numpy", "array", "[", "index", "]", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/mnist.py#L50-L61
[ "def", "extract_labels", "(", "filename", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "magic", "=", "_read32", "(", "bytestream", ")", "if", "magic", "!=", "2049", ":", "raise", "ValueError", "(", "'Invalid magic n...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
create_dummy_class
When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object
tensorpack/utils/develop.py
def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ asse...
def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ asse...
[ "When", "a", "dependency", "of", "a", "class", "is", "not", "available", "create", "a", "dummy", "class", "which", "throws", "ImportError", "when", "used", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L21-L45
[ "def", "create_dummy_class", "(", "klass", ",", "dependency", ")", ":", "assert", "not", "building_rtfd", "(", ")", "class", "_DummyMetaClass", "(", "type", ")", ":", "# throw error on class attribute access", "def", "__getattr__", "(", "_", ",", "__", ")", ":",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
create_dummy_func
When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object
tensorpack/utils/develop.py
def create_dummy_func(func, dependency): """ When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a func...
def create_dummy_func(func, dependency): """ When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a func...
[ "When", "a", "dependency", "of", "a", "function", "is", "not", "available", "create", "a", "dummy", "function", "which", "throws", "ImportError", "when", "used", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L48-L66
[ "def", "create_dummy_func", "(", "func", ",", "dependency", ")", ":", "assert", "not", "building_rtfd", "(", ")", "if", "isinstance", "(", "dependency", ",", "(", "list", ",", "tuple", ")", ")", ":", "dependency", "=", "','", ".", "join", "(", "dependenc...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
log_deprecated
Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD".
tensorpack/utils/develop.py
def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eo...
def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eo...
[ "Log", "deprecation", "warning", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L78-L99
[ "def", "log_deprecated", "(", "name", "=", "\"\"", ",", "text", "=", "\"\"", ",", "eos", "=", "\"\"", ")", ":", "assert", "name", "or", "text", "if", "eos", ":", "eos", "=", "\"after \"", "+", "datetime", "(", "*", "map", "(", "int", ",", "eos", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
deprecated
Args: text, eos: same as :func:`log_deprecated`. Returns: a decorator which deprecates the function. Example: .. code-block:: python @deprecated("Explanation of what to do instead.", "2017-11-4") def foo(...): pass
tensorpack/utils/develop.py
def deprecated(text="", eos=""): """ Args: text, eos: same as :func:`log_deprecated`. Returns: a decorator which deprecates the function. Example: .. code-block:: python @deprecated("Explanation of what to do instead.", "2017-11-4") def foo(...): ...
def deprecated(text="", eos=""): """ Args: text, eos: same as :func:`log_deprecated`. Returns: a decorator which deprecates the function. Example: .. code-block:: python @deprecated("Explanation of what to do instead.", "2017-11-4") def foo(...): ...
[ "Args", ":", "text", "eos", ":", "same", "as", ":", "func", ":", "log_deprecated", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L102-L136
[ "def", "deprecated", "(", "text", "=", "\"\"", ",", "eos", "=", "\"\"", ")", ":", "def", "get_location", "(", ")", ":", "import", "inspect", "frame", "=", "inspect", ".", "currentframe", "(", ")", "if", "frame", ":", "callstack", "=", "inspect", ".", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
QueueInput.refill_queue
Clear the queue, then call dataflow.__iter__() again and fill into the queue.
tensorpack/input_source/input_source.py
def refill_queue(self): """ Clear the queue, then call dataflow.__iter__() again and fill into the queue. """ self.thread.pause() # pause enqueue opt = tfv1.RunOptions() opt.timeout_in_ms = 2000 # 2s sess = tfv1.get_default_session() # dequeue until...
def refill_queue(self): """ Clear the queue, then call dataflow.__iter__() again and fill into the queue. """ self.thread.pause() # pause enqueue opt = tfv1.RunOptions() opt.timeout_in_ms = 2000 # 2s sess = tfv1.get_default_session() # dequeue until...
[ "Clear", "the", "queue", "then", "call", "dataflow", ".", "__iter__", "()", "again", "and", "fill", "into", "the", "queue", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L228-L246
[ "def", "refill_queue", "(", "self", ")", ":", "self", ".", "thread", ".", "pause", "(", ")", "# pause enqueue", "opt", "=", "tfv1", ".", "RunOptions", "(", ")", "opt", ".", "timeout_in_ms", "=", "2000", "# 2s", "sess", "=", "tfv1", ".", "get_default_sess...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
QueueInput._create_ema_callback
Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA.
tensorpack/input_source/input_source.py
def _create_ema_callback(self): """ Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA. """ with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = t...
def _create_ema_callback(self): """ Create a hook-only callback which maintain EMA of the queue size. Also tf.summary.scalar the EMA. """ with self.cached_name_scope(): # in TF there is no API to get queue capacity, so we can only summary the size size = t...
[ "Create", "a", "hook", "-", "only", "callback", "which", "maintain", "EMA", "of", "the", "queue", "size", ".", "Also", "tf", ".", "summary", ".", "scalar", "the", "EMA", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L248-L263
[ "def", "_create_ema_callback", "(", "self", ")", ":", "with", "self", ".", "cached_name_scope", "(", ")", ":", "# in TF there is no API to get queue capacity, so we can only summary the size", "size", "=", "tf", ".", "cast", "(", "self", ".", "queue", ".", "size", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
BatchQueueInput._setup
shapes except for the batch dimension
tensorpack/input_source/input_source.py
def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some input signature!" # prepare placehol...
def _setup(self, inputs): logger.info("Setting up the queue for CPU prefetching ...") self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs] assert len(self.input_placehdrs) > 0, \ "BatchQueueInput has to be used with some input signature!" # prepare placehol...
[ "shapes", "except", "for", "the", "batch", "dimension" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L301-L331
[ "def", "_setup", "(", "self", ",", "inputs", ")", ":", "logger", ".", "info", "(", "\"Setting up the queue for CPU prefetching ...\"", ")", "self", ".", "input_placehdrs", "=", "[", "build_or_reuse_placeholder", "(", "v", ")", "for", "v", "in", "inputs", "]", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
TFDatasetInput.dataflow_to_dataset
Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned dataset. Args: df (DataFlow): a dat...
tensorpack/input_source/input_source.py
def dataflow_to_dataset(df, types): """ Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned ...
def dataflow_to_dataset(df, types): """ Wrap a dataflow to tf.data.Dataset. This function will also reset the dataflow. If the dataflow itself is finite, the returned dataset is also finite. Therefore, if used for training, you'll need to add `.repeat()` on the returned ...
[ "Wrap", "a", "dataflow", "to", "tf", ".", "data", ".", "Dataset", ".", "This", "function", "will", "also", "reset", "the", "dataflow", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L496-L519
[ "def", "dataflow_to_dataset", "(", "df", ",", "types", ")", ":", "# TODO theoretically it can support dict", "assert", "isinstance", "(", "df", ",", "DataFlow", ")", ",", "df", "assert", "isinstance", "(", "types", ",", "(", "list", ",", "tuple", ")", ")", "...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
MultiTowerOfflinePredictor.get_predictor
Returns: OnlinePredictor: the nth predictor on the nth tower.
tensorpack/predict/multigpu.py
def get_predictor(self, n): """ Returns: OnlinePredictor: the nth predictor on the nth tower. """ l = len(self.predictors) if n >= l: logger.warn("n > #towers, will assign predictor to GPU by round-robin") return [self.predictors[k % l] for k in ra...
def get_predictor(self, n): """ Returns: OnlinePredictor: the nth predictor on the nth tower. """ l = len(self.predictors) if n >= l: logger.warn("n > #towers, will assign predictor to GPU by round-robin") return [self.predictors[k % l] for k in ra...
[ "Returns", ":", "OnlinePredictor", ":", "the", "nth", "predictor", "on", "the", "nth", "tower", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/multigpu.py#L62-L70
[ "def", "get_predictor", "(", "self", ",", "n", ")", ":", "l", "=", "len", "(", "self", ".", "predictors", ")", "if", "n", ">=", "l", ":", "logger", ".", "warn", "(", "\"n > #towers, will assign predictor to GPU by round-robin\"", ")", "return", "[", "self", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
intersection
Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
examples/FasterRCNN/utils/np_box_ops.py
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [y_min...
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [y_min...
[ "Compute", "pairwise", "intersection", "areas", "between", "boxes", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L37-L60
[ "def", "intersection", "(", "boxes1", ",", "boxes2", ")", ":", "[", "y_min1", ",", "x_min1", ",", "y_max1", ",", "x_max1", "]", "=", "np", ".", "split", "(", "boxes1", ",", "4", ",", "axis", "=", "1", ")", "[", "y_min2", ",", "x_min2", ",", "y_ma...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
iou
Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding M boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores.
examples/FasterRCNN/utils/np_box_ops.py
def iou(boxes1, boxes2): """Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding M boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ in...
def iou(boxes1, boxes2): """Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding M boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ in...
[ "Computes", "pairwise", "intersection", "-", "over", "-", "union", "between", "box", "collections", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L63-L78
[ "def", "iou", "(", "boxes1", ",", "boxes2", ")", ":", "intersect", "=", "intersection", "(", "boxes1", ",", "boxes2", ")", "area1", "=", "area", "(", "boxes1", ")", "area2", "=", "area", "(", "boxes2", ")", "union", "=", "np", ".", "expand_dims", "("...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ioa
Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a numpy array with shape [N, 4] ...
examples/FasterRCNN/utils/np_box_ops.py
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a ...
def ioa(boxes1, boxes2): """Computes pairwise intersection-over-area between box collections. Intersection-over-area (ioa) between two boxes box1 and box2 is defined as their intersection area over box2's area. Note that ioa is not symmetric, that is, IOA(box1, box2) != IOA(box2, box1). Args: boxes1: a ...
[ "Computes", "pairwise", "intersection", "-", "over", "-", "area", "between", "box", "collections", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L81-L97
[ "def", "ioa", "(", "boxes1", ",", "boxes2", ")", ":", "intersect", "=", "intersection", "(", "boxes1", ",", "boxes2", ")", "inv_areas", "=", "np", ".", "expand_dims", "(", "1.0", "/", "area", "(", "boxes2", ")", ",", "axis", "=", "0", ")", "return", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
maybe_download
Download the data from Marlin's website, unless it's already here.
tensorpack/dataflow/dataset/caltech101.py
def maybe_download(url, work_directory): """Download the data from Marlin's website, unless it's already here.""" filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download...
def maybe_download(url, work_directory): """Download the data from Marlin's website, unless it's already here.""" filename = url.split("/")[-1] filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): logger.info("Downloading to {}...".format(filepath)) download...
[ "Download", "the", "data", "from", "Marlin", "s", "website", "unless", "it", "s", "already", "here", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/caltech101.py#L15-L22
[ "def", "maybe_download", "(", "url", ",", "work_directory", ")", ":", "filename", "=", "url", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "filepath", "=", "os", ".", "path", ".", "join", "(", "work_directory", ",", "filename", ")", "if", "no...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ILSVRCMeta.get_synset_1000
Returns: dict: {cls_number: synset_id}
tensorpack/dataflow/dataset/ilsvrc.py
def get_synset_1000(self): """ Returns: dict: {cls_number: synset_id} """ fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
def get_synset_1000(self): """ Returns: dict: {cls_number: synset_id} """ fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
[ "Returns", ":", "dict", ":", "{", "cls_number", ":", "synset_id", "}" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L45-L53
[ "def", "get_synset_1000", "(", "self", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "'synsets.txt'", ")", "assert", "os", ".", "path", ".", "isfile", "(", "fname", ")", "lines", "=", "[", "x", ".", "strip", ...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ILSVRCMeta.get_image_list
Args: name (str): 'train' or 'val' or 'test' dir_structure (str): same as in :meth:`ILSVRC12.__init__()`. Returns: list: list of (image filename, label)
tensorpack/dataflow/dataset/ilsvrc.py
def get_image_list(self, name, dir_structure='original'): """ Args: name (str): 'train' or 'val' or 'test' dir_structure (str): same as in :meth:`ILSVRC12.__init__()`. Returns: list: list of (image filename, label) """ assert name in ['train', ...
def get_image_list(self, name, dir_structure='original'): """ Args: name (str): 'train' or 'val' or 'test' dir_structure (str): same as in :meth:`ILSVRC12.__init__()`. Returns: list: list of (image filename, label) """ assert name in ['train', ...
[ "Args", ":", "name", "(", "str", ")", ":", "train", "or", "val", "or", "test", "dir_structure", "(", "str", ")", ":", "same", "as", "in", ":", "meth", ":", "ILSVRC12", ".", "__init__", "()", ".", "Returns", ":", "list", ":", "list", "of", "(", "i...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L59-L86
[ "def", "get_image_list", "(", "self", ",", "name", ",", "dir_structure", "=", "'original'", ")", ":", "assert", "name", "in", "[", "'train'", ",", "'val'", ",", "'test'", "]", "assert", "dir_structure", "in", "[", "'original'", ",", "'train'", "]", "add_la...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ILSVRCMeta.get_per_pixel_mean
Args: size (tuple): image size in (h, w). Defaults to (256, 256). Returns: np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255].
tensorpack/dataflow/dataset/ilsvrc.py
def get_per_pixel_mean(self, size=None): """ Args: size (tuple): image size in (h, w). Defaults to (256, 256). Returns: np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255]. """ if self.caffepb is None: self.caffepb = get_caffe...
def get_per_pixel_mean(self, size=None): """ Args: size (tuple): image size in (h, w). Defaults to (256, 256). Returns: np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255]. """ if self.caffepb is None: self.caffepb = get_caffe...
[ "Args", ":", "size", "(", "tuple", ")", ":", "image", "size", "in", "(", "h", "w", ")", ".", "Defaults", "to", "(", "256", "256", ")", ".", "Returns", ":", "np", ".", "ndarray", ":", "per", "-", "pixel", "mean", "of", "shape", "(", "h", "w", ...
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L88-L106
[ "def", "get_per_pixel_mean", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "caffepb", "is", "None", ":", "self", ".", "caffepb", "=", "get_caffe_pb", "(", ")", "obj", "=", "self", ".", "caffepb", ".", "BlobProto", "(", ")", "mea...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
ILSVRCMeta.guess_dir_structure
Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original'
tensorpack/dataflow/dataset/ilsvrc.py
def guess_dir_structure(dir): """ Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original' """ subdir = os.listdir(dir)[0] # find a subdir starting with 'n' ...
def guess_dir_structure(dir): """ Return the directory structure of "dir". Args: dir(str): something like '/path/to/imagenet/val' Returns: either 'train' or 'original' """ subdir = os.listdir(dir)[0] # find a subdir starting with 'n' ...
[ "Return", "the", "directory", "structure", "of", "dir", "." ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L109-L129
[ "def", "guess_dir_structure", "(", "dir", ")", ":", "subdir", "=", "os", ".", "listdir", "(", "dir", ")", "[", "0", "]", "# find a subdir starting with 'n'", "if", "subdir", ".", "startswith", "(", "'n'", ")", "and", "os", ".", "path", ".", "isdir", "(",...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f
train
COCODetection.print_coco_metrics
Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics
examples/FasterRCNN/dataset.py
def print_coco_metrics(self, json_file): """ Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics """ from pycocotools.cocoeval import COCOeval ret = {} cocoDt = self.coco.loadRes(json_fi...
def print_coco_metrics(self, json_file): """ Args: json_file (str): path to the results json file in coco format Returns: dict: the evaluation metrics """ from pycocotools.cocoeval import COCOeval ret = {} cocoDt = self.coco.loadRes(json_fi...
[ "Args", ":", "json_file", "(", "str", ")", ":", "path", "to", "the", "results", "json", "file", "in", "coco", "format", "Returns", ":", "dict", ":", "the", "evaluation", "metrics" ]
tensorpack/tensorpack
python
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L49-L75
[ "def", "print_coco_metrics", "(", "self", ",", "json_file", ")", ":", "from", "pycocotools", ".", "cocoeval", "import", "COCOeval", "ret", "=", "{", "}", "cocoDt", "=", "self", ".", "coco", ".", "loadRes", "(", "json_file", ")", "cocoEval", "=", "COCOeval"...
d7a13cb74c9066bc791d7aafc3b744b60ee79a9f