repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
shidenggui/easytrader | easytrader/xq_follower.py | XueQiuFollower.login | def login(self, user=None, password=None, **kwargs):
"""
雪球登陆, 需要设置 cookies
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:return:
"""
cookies = kwargs.get('cookies')
if cookies is None:
raise TypeErro... | python | def login(self, user=None, password=None, **kwargs):
"""
雪球登陆, 需要设置 cookies
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:return:
"""
cookies = kwargs.get('cookies')
if cookies is None:
raise TypeErro... | [
"def",
"login",
"(",
"self",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cookies",
"=",
"kwargs",
".",
"get",
"(",
"'cookies'",
")",
"if",
"cookies",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'雪球... | 雪球登陆, 需要设置 cookies
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:return: | [
"雪球登陆,",
"需要设置",
"cookies",
":",
"param",
"cookies",
":",
"雪球登陆需要设置",
"cookies,",
"具体见",
"https",
":",
"//",
"smalltool",
".",
"github",
".",
"io",
"/",
"2016",
"/",
"08",
"/",
"02",
"/",
"cookie",
"/",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xq_follower.py#L27-L46 | train |
shidenggui/easytrader | easytrader/xq_follower.py | XueQiuFollower.follow | def follow( # type: ignore
self,
users,
strategies,
total_assets=10000,
initial_assets=None,
adjust_sell=False,
track_interval=10,
trade_cmd_expire_seconds=120,
cmd_cache=True,
slippage: float = 0.0)... | python | def follow( # type: ignore
self,
users,
strategies,
total_assets=10000,
initial_assets=None,
adjust_sell=False,
track_interval=10,
trade_cmd_expire_seconds=120,
cmd_cache=True,
slippage: float = 0.0)... | [
"def",
"follow",
"(",
"# type: ignore",
"self",
",",
"users",
",",
"strategies",
",",
"total_assets",
"=",
"10000",
",",
"initial_assets",
"=",
"None",
",",
"adjust_sell",
"=",
"False",
",",
"track_interval",
"=",
"10",
",",
"trade_cmd_expire_seconds",
"=",
"1... | 跟踪 joinquant 对应的模拟交易,支持多用户多策略
:param users: 支持 easytrader 的用户对象,支持使用 [] 指定多个用户
:param strategies: 雪球组合名, 类似 ZH123450
:param total_assets: 雪球组合对应的总资产, 格式 [组合1对应资金, 组合2对应资金]
若 strategies=['ZH000001', 'ZH000002'],
设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元
... | [
"跟踪",
"joinquant",
"对应的模拟交易,支持多用户多策略",
":",
"param",
"users",
":",
"支持",
"easytrader",
"的用户对象,支持使用",
"[]",
"指定多个用户",
":",
"param",
"strategies",
":",
"雪球组合名",
"类似",
"ZH123450",
":",
"param",
"total_assets",
":",
"雪球组合对应的总资产,",
"格式",
"[",
"组合1对应资金",
"组合2对应资金",
... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xq_follower.py#L48-L117 | train |
shidenggui/easytrader | easytrader/xq_follower.py | XueQiuFollower._adjust_sell_amount | def _adjust_sell_amount(self, stock_code, amount):
"""
根据实际持仓值计算雪球卖出股数
因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。
导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。
而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量,
导致卖出失败
:param stock_code: 证券代码
:type stock_code: str
... | python | def _adjust_sell_amount(self, stock_code, amount):
"""
根据实际持仓值计算雪球卖出股数
因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。
导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。
而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量,
导致卖出失败
:param stock_code: 证券代码
:type stock_code: str
... | [
"def",
"_adjust_sell_amount",
"(",
"self",
",",
"stock_code",
",",
"amount",
")",
":",
"stock_code",
"=",
"stock_code",
"[",
"-",
"6",
":",
"]",
"user",
"=",
"self",
".",
"_users",
"[",
"0",
"]",
"position",
"=",
"user",
".",
"position",
"try",
":",
... | 根据实际持仓值计算雪球卖出股数
因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。
导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。
而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量,
导致卖出失败
:param stock_code: 证券代码
:type stock_code: str
:param amount: 卖出股份数
:type amount: int
:return:... | [
"根据实际持仓值计算雪球卖出股数",
"因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。",
"导致如下情况的产生,计算出的指令为买入",
"1049",
"股,取近似值买入",
"1000",
"股。",
"而卖出的指令计算出为卖出",
"1051",
"股,取近似值卖出",
"1100",
"股,超过",
"1000",
"股的买入量,",
"导致卖出失败",
":",
"param",
"stock_code",
":",
"证券代码",
":",
"type",
"stock_code",
":",... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xq_follower.py#L192-L223 | train |
shidenggui/easytrader | easytrader/xq_follower.py | XueQiuFollower._get_portfolio_info | def _get_portfolio_info(self, portfolio_code):
"""
获取组合信息
"""
url = self.PORTFOLIO_URL + portfolio_code
portfolio_page = self.s.get(url)
match_info = re.search(r'(?<=SNB.cubeInfo = ).*(?=;\n)',
portfolio_page.text)
if match_info is N... | python | def _get_portfolio_info(self, portfolio_code):
"""
获取组合信息
"""
url = self.PORTFOLIO_URL + portfolio_code
portfolio_page = self.s.get(url)
match_info = re.search(r'(?<=SNB.cubeInfo = ).*(?=;\n)',
portfolio_page.text)
if match_info is N... | [
"def",
"_get_portfolio_info",
"(",
"self",
",",
"portfolio_code",
")",
":",
"url",
"=",
"self",
".",
"PORTFOLIO_URL",
"+",
"portfolio_code",
"portfolio_page",
"=",
"self",
".",
"s",
".",
"get",
"(",
"url",
")",
"match_info",
"=",
"re",
".",
"search",
"(",
... | 获取组合信息 | [
"获取组合信息"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xq_follower.py#L225-L240 | train |
shidenggui/easytrader | easytrader/helpers.py | parse_cookies_str | def parse_cookies_str(cookies):
"""
parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict
"""
cookie_dict = {}
for record in cookies.split(";"):
key, value = record.strip().split("=", 1)
cookie_dict[key] = value
... | python | def parse_cookies_str(cookies):
"""
parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict
"""
cookie_dict = {}
for record in cookies.split(";"):
key, value = record.strip().split("=", 1)
cookie_dict[key] = value
... | [
"def",
"parse_cookies_str",
"(",
"cookies",
")",
":",
"cookie_dict",
"=",
"{",
"}",
"for",
"record",
"in",
"cookies",
".",
"split",
"(",
"\";\"",
")",
":",
"key",
",",
"value",
"=",
"record",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"=\"",
",",
... | parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict | [
"parse",
"cookies",
"str",
"to",
"dict",
":",
"param",
"cookies",
":",
"cookies",
"str",
":",
"type",
"cookies",
":",
"str",
":",
"return",
":",
"cookie",
"dict",
":",
"rtype",
":",
"dict"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L12-L24 | train |
shidenggui/easytrader | easytrader/helpers.py | get_stock_type | def get_stock_type(stock_code):
"""判断股票ID对应的证券市场
匹配规则
['50', '51', '60', '90', '110'] 为 sh
['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz
:param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断
:return 'sh' or 'sz'"""
stock_code = s... | python | def get_stock_type(stock_code):
"""判断股票ID对应的证券市场
匹配规则
['50', '51', '60', '90', '110'] 为 sh
['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz
:param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断
:return 'sh' or 'sz'"""
stock_code = s... | [
"def",
"get_stock_type",
"(",
"stock_code",
")",
":",
"stock_code",
"=",
"str",
"(",
"stock_code",
")",
"if",
"stock_code",
".",
"startswith",
"(",
"(",
"\"sh\"",
",",
"\"sz\"",
")",
")",
":",
"return",
"stock_code",
"[",
":",
"2",
"]",
"if",
"stock_code... | 判断股票ID对应的证券市场
匹配规则
['50', '51', '60', '90', '110'] 为 sh
['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz
:param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型,否则使用内置规则判断
:return 'sh' or 'sz | [
"判断股票ID对应的证券市场",
"匹配规则",
"[",
"50",
"51",
"60",
"90",
"110",
"]",
"为",
"sh",
"[",
"00",
"13",
"18",
"15",
"16",
"18",
"20",
"30",
"39",
"115",
"]",
"为",
"sz",
"[",
"5",
"6",
"9",
"]",
"开头的为",
"sh,",
"其余为",
"sz",
":",
"param",
"stock_code",
":... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L32-L53 | train |
shidenggui/easytrader | easytrader/helpers.py | recognize_verify_code | def recognize_verify_code(image_path, broker="ht"):
"""识别验证码,返回识别后的字符串,使用 tesseract 实现
:param image_path: 图片路径
:param broker: 券商 ['ht', 'yjb', 'gf', 'yh']
:return recognized: verify code string"""
if broker == "gf":
return detect_gf_result(image_path)
if broker in ["yh_client", "gj_clie... | python | def recognize_verify_code(image_path, broker="ht"):
"""识别验证码,返回识别后的字符串,使用 tesseract 实现
:param image_path: 图片路径
:param broker: 券商 ['ht', 'yjb', 'gf', 'yh']
:return recognized: verify code string"""
if broker == "gf":
return detect_gf_result(image_path)
if broker in ["yh_client", "gj_clie... | [
"def",
"recognize_verify_code",
"(",
"image_path",
",",
"broker",
"=",
"\"ht\"",
")",
":",
"if",
"broker",
"==",
"\"gf\"",
":",
"return",
"detect_gf_result",
"(",
"image_path",
")",
"if",
"broker",
"in",
"[",
"\"yh_client\"",
",",
"\"gj_client\"",
"]",
":",
... | 识别验证码,返回识别后的字符串,使用 tesseract 实现
:param image_path: 图片路径
:param broker: 券商 ['ht', 'yjb', 'gf', 'yh']
:return recognized: verify code string | [
"识别验证码,返回识别后的字符串,使用",
"tesseract",
"实现",
":",
"param",
"image_path",
":",
"图片路径",
":",
"param",
"broker",
":",
"券商",
"[",
"ht",
"yjb",
"gf",
"yh",
"]",
":",
"return",
"recognized",
":",
"verify",
"code",
"string"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L56-L67 | train |
shidenggui/easytrader | easytrader/helpers.py | detect_yh_client_result | def detect_yh_client_result(image_path):
"""封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker"""
api = "http://yh.ez.shidenggui.com:5000/yh_client"
with open(image_path, "rb") as f:
rep = requests.post(api, files={"image": f})
if rep.status_code != 201:
... | python | def detect_yh_client_result(image_path):
"""封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker"""
api = "http://yh.ez.shidenggui.com:5000/yh_client"
with open(image_path, "rb") as f:
rep = requests.post(api, files={"image": f})
if rep.status_code != 201:
... | [
"def",
"detect_yh_client_result",
"(",
"image_path",
")",
":",
"api",
"=",
"\"http://yh.ez.shidenggui.com:5000/yh_client\"",
"with",
"open",
"(",
"image_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"rep",
"=",
"requests",
".",
"post",
"(",
"api",
",",
"files",
"... | 封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker | [
"封装了tesseract的识别,部署在阿里云上,服务端源码地址为:",
"https",
":",
"//",
"github",
".",
"com",
"/",
"shidenggui",
"/",
"yh_verify_code_docker"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L70-L78 | train |
shidenggui/easytrader | easytrader/helpers.py | get_30_date | def get_30_date():
"""
获得用于查询的默认日期, 今天的日期, 以及30天前的日期
用于查询的日期格式通常为 20160211
:return:
"""
now = datetime.datetime.now()
end_date = now.date()
start_date = end_date - datetime.timedelta(days=30)
return start_date.strftime("%Y%m%d"), end_date.strftime("%Y%m%d") | python | def get_30_date():
"""
获得用于查询的默认日期, 今天的日期, 以及30天前的日期
用于查询的日期格式通常为 20160211
:return:
"""
now = datetime.datetime.now()
end_date = now.date()
start_date = end_date - datetime.timedelta(days=30)
return start_date.strftime("%Y%m%d"), end_date.strftime("%Y%m%d") | [
"def",
"get_30_date",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"end_date",
"=",
"now",
".",
"date",
"(",
")",
"start_date",
"=",
"end_date",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"30",
")",
"return"... | 获得用于查询的默认日期, 今天的日期, 以及30天前的日期
用于查询的日期格式通常为 20160211
:return: | [
"获得用于查询的默认日期",
"今天的日期",
"以及30天前的日期",
"用于查询的日期格式通常为",
"20160211",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L142-L151 | train |
shidenggui/easytrader | easytrader/helpers.py | get_today_ipo_data | def get_today_ipo_data():
"""
查询今天可以申购的新股信息
:return: 今日可申购新股列表 apply_code申购代码 price发行价格
"""
agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0"
send_headers = {
"Host": "xueqiu.com",
"User-Agent": agent,
"Accept": "application/jso... | python | def get_today_ipo_data():
"""
查询今天可以申购的新股信息
:return: 今日可申购新股列表 apply_code申购代码 price发行价格
"""
agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0"
send_headers = {
"Host": "xueqiu.com",
"User-Agent": agent,
"Accept": "application/jso... | [
"def",
"get_today_ipo_data",
"(",
")",
":",
"agent",
"=",
"\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0\"",
"send_headers",
"=",
"{",
"\"Host\"",
":",
"\"xueqiu.com\"",
",",
"\"User-Agent\"",
":",
"agent",
",",
"\"Accept\"",
":",
"\"a... | 查询今天可以申购的新股信息
:return: 今日可申购新股列表 apply_code申购代码 price发行价格 | [
"查询今天可以申购的新股信息",
":",
"return",
":",
"今日可申购新股列表",
"apply_code申购代码",
"price发行价格"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L154-L200 | train |
shidenggui/easytrader | easytrader/follower.py | BaseFollower.login | def login(self, user=None, password=None, **kwargs):
"""
登陆接口
:param user: 用户名
:param password: 密码
:param kwargs: 其他参数
:return:
"""
headers = self._generate_headers()
self.s.headers.update(headers)
# init cookie
self.s.get(self.LOG... | python | def login(self, user=None, password=None, **kwargs):
"""
登陆接口
:param user: 用户名
:param password: 密码
:param kwargs: 其他参数
:return:
"""
headers = self._generate_headers()
self.s.headers.update(headers)
# init cookie
self.s.get(self.LOG... | [
"def",
"login",
"(",
"self",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"self",
".",
"_generate_headers",
"(",
")",
"self",
".",
"s",
".",
"headers",
".",
"update",
"(",
"headers",
")"... | 登陆接口
:param user: 用户名
:param password: 密码
:param kwargs: 其他参数
:return: | [
"登陆接口",
":",
"param",
"user",
":",
"用户名",
":",
"param",
"password",
":",
"密码",
":",
"param",
"kwargs",
":",
"其他参数",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/follower.py#L39-L58 | train |
shidenggui/easytrader | easytrader/follower.py | BaseFollower.follow | def follow(
self,
users,
strategies,
track_interval=1,
trade_cmd_expire_seconds=120,
cmd_cache=True,
slippage: float = 0.0,
**kwargs
):
"""跟踪平台对应的模拟交易,支持多用户多策略
:param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户
:param strategies: 雪... | python | def follow(
self,
users,
strategies,
track_interval=1,
trade_cmd_expire_seconds=120,
cmd_cache=True,
slippage: float = 0.0,
**kwargs
):
"""跟踪平台对应的模拟交易,支持多用户多策略
:param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户
:param strategies: 雪... | [
"def",
"follow",
"(",
"self",
",",
"users",
",",
"strategies",
",",
"track_interval",
"=",
"1",
",",
"trade_cmd_expire_seconds",
"=",
"120",
",",
"cmd_cache",
"=",
"True",
",",
"slippage",
":",
"float",
"=",
"0.0",
",",
"*",
"*",
"kwargs",
")",
":",
"s... | 跟踪平台对应的模拟交易,支持多用户多策略
:param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户
:param strategies: 雪球组合名, 类似 ZH123450
:param total_assets: 雪球组合对应的总资产, 格式 [ 组合1对应资金, 组合2对应资金 ]
若 strategies=['ZH000001', 'ZH000002'] 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元,
假设组合 ZH000001 加仓 价... | [
"跟踪平台对应的模拟交易,支持多用户多策略"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/follower.py#L89-L113 | train |
shidenggui/easytrader | easytrader/follower.py | BaseFollower._calculate_price_by_slippage | def _calculate_price_by_slippage(self, action: str, price: float) -> float:
"""
计算考虑滑点之后的价格
:param action: 交易动作, 支持 ['buy', 'sell']
:param price: 原始交易价格
:return: 考虑滑点后的交易价格
"""
if action == "buy":
return price * (1 + self.slippage)
if action ==... | python | def _calculate_price_by_slippage(self, action: str, price: float) -> float:
"""
计算考虑滑点之后的价格
:param action: 交易动作, 支持 ['buy', 'sell']
:param price: 原始交易价格
:return: 考虑滑点后的交易价格
"""
if action == "buy":
return price * (1 + self.slippage)
if action ==... | [
"def",
"_calculate_price_by_slippage",
"(",
"self",
",",
"action",
":",
"str",
",",
"price",
":",
"float",
")",
"->",
"float",
":",
"if",
"action",
"==",
"\"buy\"",
":",
"return",
"price",
"*",
"(",
"1",
"+",
"self",
".",
"slippage",
")",
"if",
"action... | 计算考虑滑点之后的价格
:param action: 交易动作, 支持 ['buy', 'sell']
:param price: 原始交易价格
:return: 考虑滑点后的交易价格 | [
"计算考虑滑点之后的价格",
":",
"param",
"action",
":",
"交易动作,",
"支持",
"[",
"buy",
"sell",
"]",
":",
"param",
"price",
":",
"原始交易价格",
":",
"return",
":",
"考虑滑点后的交易价格"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/follower.py#L115-L126 | train |
shidenggui/easytrader | easytrader/follower.py | BaseFollower.track_strategy_worker | def track_strategy_worker(self, strategy, name, interval=10, **kwargs):
"""跟踪下单worker
:param strategy: 策略id
:param name: 策略名字
:param interval: 轮询策略的时间间隔,单位为秒"""
while True:
try:
transactions = self.query_strategy_transaction(
strate... | python | def track_strategy_worker(self, strategy, name, interval=10, **kwargs):
"""跟踪下单worker
:param strategy: 策略id
:param name: 策略名字
:param interval: 轮询策略的时间间隔,单位为秒"""
while True:
try:
transactions = self.query_strategy_transaction(
strate... | [
"def",
"track_strategy_worker",
"(",
"self",
",",
"strategy",
",",
"name",
",",
"interval",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"transactions",
"=",
"self",
".",
"query_strategy_transaction",
"(",
"strategy",
","... | 跟踪下单worker
:param strategy: 策略id
:param name: 策略名字
:param interval: 轮询策略的时间间隔,单位为秒 | [
"跟踪下单worker",
":",
"param",
"strategy",
":",
"策略id",
":",
"param",
"name",
":",
"策略名字",
":",
"param",
"interval",
":",
"轮询策略的时间间隔,单位为秒"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/follower.py#L175-L218 | train |
shidenggui/easytrader | easytrader/follower.py | BaseFollower._execute_trade_cmd | def _execute_trade_cmd(
self, trade_cmd, users, expire_seconds, entrust_prop, send_interval
):
"""分发交易指令到对应的 user 并执行
:param trade_cmd:
:param users:
:param expire_seconds:
:param entrust_prop:
:param send_interval:
:return:
"""
for use... | python | def _execute_trade_cmd(
self, trade_cmd, users, expire_seconds, entrust_prop, send_interval
):
"""分发交易指令到对应的 user 并执行
:param trade_cmd:
:param users:
:param expire_seconds:
:param entrust_prop:
:param send_interval:
:return:
"""
for use... | [
"def",
"_execute_trade_cmd",
"(",
"self",
",",
"trade_cmd",
",",
"users",
",",
"expire_seconds",
",",
"entrust_prop",
",",
"send_interval",
")",
":",
"for",
"user",
"in",
"users",
":",
"# check expire",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(... | 分发交易指令到对应的 user 并执行
:param trade_cmd:
:param users:
:param expire_seconds:
:param entrust_prop:
:param send_interval:
:return: | [
"分发交易指令到对应的",
"user",
"并执行",
":",
"param",
"trade_cmd",
":",
":",
"param",
"users",
":",
":",
"param",
"expire_seconds",
":",
":",
"param",
"entrust_prop",
":",
":",
"param",
"send_interval",
":",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/follower.py#L250-L343 | train |
shidenggui/easytrader | easytrader/follower.py | BaseFollower.trade_worker | def trade_worker(
self, users, expire_seconds=120, entrust_prop="limit", send_interval=0
):
"""
:param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足
"""
while True:
trade_cmd = self.trade_queue.get()
self._execute_trade_cmd(
... | python | def trade_worker(
self, users, expire_seconds=120, entrust_prop="limit", send_interval=0
):
"""
:param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足
"""
while True:
trade_cmd = self.trade_queue.get()
self._execute_trade_cmd(
... | [
"def",
"trade_worker",
"(",
"self",
",",
"users",
",",
"expire_seconds",
"=",
"120",
",",
"entrust_prop",
"=",
"\"limit\"",
",",
"send_interval",
"=",
"0",
")",
":",
"while",
"True",
":",
"trade_cmd",
"=",
"self",
".",
"trade_queue",
".",
"get",
"(",
")"... | :param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足 | [
":",
"param",
"send_interval",
":",
"交易发送间隔,",
"默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/follower.py#L345-L356 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader._set_cookies | def _set_cookies(self, cookies):
"""设置雪球 cookies,代码来自于
https://github.com/shidenggui/easytrader/issues/269
:param cookies: 雪球 cookies
:type cookies: str
"""
cookie_dict = helpers.parse_cookies_str(cookies)
self.s.cookies.update(cookie_dict) | python | def _set_cookies(self, cookies):
"""设置雪球 cookies,代码来自于
https://github.com/shidenggui/easytrader/issues/269
:param cookies: 雪球 cookies
:type cookies: str
"""
cookie_dict = helpers.parse_cookies_str(cookies)
self.s.cookies.update(cookie_dict) | [
"def",
"_set_cookies",
"(",
"self",
",",
"cookies",
")",
":",
"cookie_dict",
"=",
"helpers",
".",
"parse_cookies_str",
"(",
"cookies",
")",
"self",
".",
"s",
".",
"cookies",
".",
"update",
"(",
"cookie_dict",
")"
] | 设置雪球 cookies,代码来自于
https://github.com/shidenggui/easytrader/issues/269
:param cookies: 雪球 cookies
:type cookies: str | [
"设置雪球",
"cookies,代码来自于",
"https",
":",
"//",
"github",
".",
"com",
"/",
"shidenggui",
"/",
"easytrader",
"/",
"issues",
"/",
"269",
":",
"param",
"cookies",
":",
"雪球",
"cookies",
":",
"type",
"cookies",
":",
"str"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L56-L63 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader._prepare_account | def _prepare_account(self, user="", password="", **kwargs):
"""
转换参数到登录所需的字典格式
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:param portfolio_code: 组合代码
:param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn'
:return:... | python | def _prepare_account(self, user="", password="", **kwargs):
"""
转换参数到登录所需的字典格式
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:param portfolio_code: 组合代码
:param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn'
:return:... | [
"def",
"_prepare_account",
"(",
"self",
",",
"user",
"=",
"\"\"",
",",
"password",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"portfolio_code\"",
"not",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"\"雪球登录需要设置 portfolio_code(组合代码) 参数\")",
"",
... | 转换参数到登录所需的字典格式
:param cookies: 雪球登陆需要设置 cookies, 具体见
https://smalltool.github.io/2016/08/02/cookie/
:param portfolio_code: 组合代码
:param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn'
:return: | [
"转换参数到登录所需的字典格式",
":",
"param",
"cookies",
":",
"雪球登陆需要设置",
"cookies,",
"具体见",
"https",
":",
"//",
"smalltool",
".",
"github",
".",
"io",
"/",
"2016",
"/",
"08",
"/",
"02",
"/",
"cookie",
"/",
":",
"param",
"portfolio_code",
":",
"组合代码",
":",
"param",
... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L65-L87 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader._search_stock_info | def _search_stock_info(self, code):
"""
通过雪球的接口获取股票详细信息
:param code: 股票代码 000001
:return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',
u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,
u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,
... | python | def _search_stock_info(self, code):
"""
通过雪球的接口获取股票详细信息
:param code: 股票代码 000001
:return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',
u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,
u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,
... | [
"def",
"_search_stock_info",
"(",
"self",
",",
"code",
")",
":",
"data",
"=",
"{",
"\"code\"",
":",
"str",
"(",
"code",
")",
",",
"\"size\"",
":",
"\"300\"",
",",
"\"key\"",
":",
"\"47bce5c74f\"",
",",
"\"market\"",
":",
"self",
".",
"account_config",
"[... | 通过雪球的接口获取股票详细信息
:param code: 股票代码 000001
:return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',
u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,
u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,
u'hasexist': None, u'flag': 1, u'ind_name': u'房地产'... | [
"通过雪球的接口获取股票详细信息",
":",
"param",
"code",
":",
"股票代码",
"000001",
":",
"return",
":",
"查询到的股票",
"{",
"u",
"stock_id",
":",
"1000279",
"u",
"code",
":",
"u",
"SH600325",
"u",
"name",
":",
"u",
"华发股份",
"u",
"ind_color",
":",
"u",
"#d9633b",
"u",
"chg",
"... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L100-L123 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader._get_portfolio_info | def _get_portfolio_info(self, portfolio_code):
"""
获取组合信息
:return: 字典
"""
url = self.config["portfolio_url"] + portfolio_code
html = self._get_html(url)
match_info = re.search(r"(?<=SNB.cubeInfo = ).*(?=;\n)", html)
if match_info is None:
raise... | python | def _get_portfolio_info(self, portfolio_code):
"""
获取组合信息
:return: 字典
"""
url = self.config["portfolio_url"] + portfolio_code
html = self._get_html(url)
match_info = re.search(r"(?<=SNB.cubeInfo = ).*(?=;\n)", html)
if match_info is None:
raise... | [
"def",
"_get_portfolio_info",
"(",
"self",
",",
"portfolio_code",
")",
":",
"url",
"=",
"self",
".",
"config",
"[",
"\"portfolio_url\"",
"]",
"+",
"portfolio_code",
"html",
"=",
"self",
".",
"_get_html",
"(",
"url",
")",
"match_info",
"=",
"re",
".",
"sear... | 获取组合信息
:return: 字典 | [
"获取组合信息",
":",
"return",
":",
"字典"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L125-L141 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader.get_balance | def get_balance(self):
"""
获取账户资金状况
:return:
"""
portfolio_code = self.account_config.get("portfolio_code", "ch")
portfolio_info = self._get_portfolio_info(portfolio_code)
asset_balance = self._virtual_to_balance(
float(portfolio_info["net_value"])
... | python | def get_balance(self):
"""
获取账户资金状况
:return:
"""
portfolio_code = self.account_config.get("portfolio_code", "ch")
portfolio_info = self._get_portfolio_info(portfolio_code)
asset_balance = self._virtual_to_balance(
float(portfolio_info["net_value"])
... | [
"def",
"get_balance",
"(",
"self",
")",
":",
"portfolio_code",
"=",
"self",
".",
"account_config",
".",
"get",
"(",
"\"portfolio_code\"",
",",
"\"ch\"",
")",
"portfolio_info",
"=",
"self",
".",
"_get_portfolio_info",
"(",
"portfolio_code",
")",
"asset_balance",
... | 获取账户资金状况
:return: | [
"获取账户资金状况",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L143-L165 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader._get_position | def _get_position(self):
"""
获取雪球持仓
:return:
"""
portfolio_code = self.account_config["portfolio_code"]
portfolio_info = self._get_portfolio_info(portfolio_code)
position = portfolio_info["view_rebalancing"] # 仓位结构
stocks = position["holdings"] # 持仓股票
... | python | def _get_position(self):
"""
获取雪球持仓
:return:
"""
portfolio_code = self.account_config["portfolio_code"]
portfolio_info = self._get_portfolio_info(portfolio_code)
position = portfolio_info["view_rebalancing"] # 仓位结构
stocks = position["holdings"] # 持仓股票
... | [
"def",
"_get_position",
"(",
"self",
")",
":",
"portfolio_code",
"=",
"self",
".",
"account_config",
"[",
"\"portfolio_code\"",
"]",
"portfolio_info",
"=",
"self",
".",
"_get_portfolio_info",
"(",
"portfolio_code",
")",
"position",
"=",
"portfolio_info",
"[",
"\"v... | 获取雪球持仓
:return: | [
"获取雪球持仓",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L167-L176 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader.get_position | def get_position(self):
"""
获取持仓
:return:
"""
xq_positions = self._get_position()
balance = self.get_balance()[0]
position_list = []
for pos in xq_positions:
volume = pos["weight"] * balance["asset_balance"] / 100
position_list.appe... | python | def get_position(self):
"""
获取持仓
:return:
"""
xq_positions = self._get_position()
balance = self.get_balance()[0]
position_list = []
for pos in xq_positions:
volume = pos["weight"] * balance["asset_balance"] / 100
position_list.appe... | [
"def",
"get_position",
"(",
"self",
")",
":",
"xq_positions",
"=",
"self",
".",
"_get_position",
"(",
")",
"balance",
"=",
"self",
".",
"get_balance",
"(",
")",
"[",
"0",
"]",
"position_list",
"=",
"[",
"]",
"for",
"pos",
"in",
"xq_positions",
":",
"vo... | 获取持仓
:return: | [
"获取持仓",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L187-L211 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader._get_xq_history | def _get_xq_history(self):
"""
获取雪球调仓历史
:param instance:
:param owner:
:return:
"""
data = {
"cube_symbol": str(self.account_config["portfolio_code"]),
"count": 20,
"page": 1,
}
resp = self.s.get(self.config["his... | python | def _get_xq_history(self):
"""
获取雪球调仓历史
:param instance:
:param owner:
:return:
"""
data = {
"cube_symbol": str(self.account_config["portfolio_code"]),
"count": 20,
"page": 1,
}
resp = self.s.get(self.config["his... | [
"def",
"_get_xq_history",
"(",
"self",
")",
":",
"data",
"=",
"{",
"\"cube_symbol\"",
":",
"str",
"(",
"self",
".",
"account_config",
"[",
"\"portfolio_code\"",
"]",
")",
",",
"\"count\"",
":",
"20",
",",
"\"page\"",
":",
"1",
",",
"}",
"resp",
"=",
"s... | 获取雪球调仓历史
:param instance:
:param owner:
:return: | [
"获取雪球调仓历史",
":",
"param",
"instance",
":",
":",
"param",
"owner",
":",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L213-L227 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader.get_entrust | 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"] # 调... | python | 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",
")",
":",
"xq_entrust_list",
"=",
"self",
".",
"_get_xq_history",
"(",
")",
"entrust_list",
"=",
"[",
"]",
"replace_none",
"=",
"lambda",
"s",
":",
"s",
"or",
"0",
"for",
"xq_entrusts",
"in",
"xq_entrust_list",
":",
"stat... | 获取委托单(目前返回20次调仓的结果)
操作数量都按1手模拟换算的
:return: | [
"获取委托单",
"(",
"目前返回20次调仓的结果",
")",
"操作数量都按1手模拟换算的",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L233-L271 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader.cancel_entrust | 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... | python | 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",
")",
":",
"xq_entrust_list",
"=",
"self",
".",
"_get_xq_history",
"(",
")",
"is_have",
"=",
"False",
"for",
"xq_entrusts",
"in",
"xq_entrust_list",
":",
"status",
"=",
"xq_entrusts",
"[",
"\"status\"",
"... | 对未成交的调仓进行伪撤单
:param entrust_no:
:return: | [
"对未成交的调仓进行伪撤单",
":",
"param",
"entrust_no",
":",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L273-L313 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader.adjust_weight | 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"没有查询要... | python | 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",
")",
":",
"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 之间的浮点数 | [
"雪球组合调仓",
"weight",
"为调整后的仓位比例",
":",
"param",
"stock_code",
":",
"str",
"股票代码",
":",
"param",
"weight",
":",
"float",
"调整之后的持仓百分比,",
"0",
"-",
"100",
"之间的浮点数"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L315-L394 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader._trade | 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.... | python | 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\"",
")",
":",
"stock",
"=",
"self",
".",
"_search_stock_info",
"(",
"security",
")",
"balance",
"=... | 调仓
:param security:
:param price:
:param amount:
:param volume:
:param entrust_bs:
:return: | [
"调仓",
":",
"param",
"security",
":",
":",
"param",
"price",
":",
":",
"param",
"amount",
":",
":",
"param",
"volume",
":",
":",
"param",
"entrust_bs",
":",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L396-L528 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader.buy | 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... | python | 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",
")",
":",
"return",
"self",
".",
"_trade",
"(",
"security",
",",
"price",
",",
"amount",
",",
"vo... | 买入卖出股票
:param security: 股票代码
:param price: 买入价格
:param amount: 买入股数
:param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效
:param entrust_prop: | [
"买入卖出股票",
":",
"param",
"security",
":",
"股票代码",
":",
"param",
"price",
":",
"买入价格",
":",
"param",
"amount",
":",
"买入股数",
":",
"param",
"volume",
":",
"买入总金额",
"由",
"volume",
"/",
"price",
"取整,",
"若指定",
"price",
"则此参数无效",
":",
"param",
"entrust_prop",
... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L530-L538 | train |
shidenggui/easytrader | easytrader/xqtrader.py | XueQiuTrader.sell | 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... | python | 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",
")",
":",
"return",
"self",
".",
"_trade",
"(",
"security",
",",
"price",
",",
"amount",
",",
"v... | 卖出股票
:param security: 股票代码
:param price: 卖出价格
:param amount: 卖出股数
:param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效
:param entrust_prop: | [
"卖出股票",
":",
"param",
"security",
":",
"股票代码",
":",
"param",
"price",
":",
"卖出价格",
":",
"param",
"amount",
":",
"卖出股数",
":",
"param",
"volume",
":",
"卖出总金额",
"由",
"volume",
"/",
"price",
"取整,",
"若指定",
"price",
"则此参数无效",
":",
"param",
"entrust_prop",
":... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/xqtrader.py#L540-L548 | train |
shidenggui/easytrader | easytrader/joinquant_follower.py | JoinQuantFollower.follow | 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 ... | python | 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 strategies: joinquant 的模拟交易地址,支持使用 [] 指定多个模拟交易,
地址类似 https://www.joinquant.com/algorithm/live/index?backtestId=xxx
:param track_interval: 轮训模拟交易时间,单位为秒
:param trade_cmd_expire_seconds: 交易指令过期时间,... | [
"跟踪joinquant对应的模拟交易,支持多用户多策略",
":",
"param",
"users",
":",
"支持easytrader的用户对象,支持使用",
"[]",
"指定多个用户",
":",
"param",
"strategies",
":",
"joinquant",
"的模拟交易地址,支持使用",
"[]",
"指定多个模拟交易",
"地址类似",
"https",
":",
"//",
"www",
".",
"joinquant",
".",
"com",
"/",
"algorithm",
... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/joinquant_follower.py#L34-L81 | train |
shidenggui/easytrader | easytrader/clienttrader.py | ClientTrader.connect | 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... | python | 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",
")",
":",
"connect_path",
"=",
"exe_path",
"or",
"self",
".",
"_config",
".",
"DEFAULT_EXE_PATH",
"if",
"connect_path",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"... | 直接连接登陆后的客户端
:param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe'
:return: | [
"直接连接登陆后的客户端",
":",
"param",
"exe_path",
":",
"客户端路径类似",
"r",
"C",
":",
"\\\\",
"htzqzyb2",
"\\\\",
"xiadan",
".",
"exe",
"默认",
"r",
"C",
":",
"\\\\",
"htzqzyb2",
"\\\\",
"xiadan",
".",
"exe",
":",
"return",
":"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L70-L86 | train |
shidenggui/easytrader | easytrader/clienttrader.py | ClientTrader.market_buy | def market_buy(self, security, amount, ttype=None, **kwargs):
"""
市价买入
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余... | python | def market_buy(self, security, amount, ttype=None, **kwargs):
"""
市价买入
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余... | [
"def",
"market_buy",
"(",
"self",
",",
"security",
",",
"amount",
",",
"ttype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_switch_left_menus",
"(",
"[",
"\"市价委托\", \"买入\"])",
"",
"",
"",
"",
"return",
"self",
".",
"market_trade",
"(... | 市价买入
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价']
:return: {'entrust_no': '委托单号'} | [
"市价买入",
":",
"param",
"security",
":",
"六位证券代码",
":",
"param",
"amount",
":",
"交易数量",
":",
"param",
"ttype",
":",
"市价委托类型,默认客户端默认选择,",
"深市可选",
"[",
"对手方最优价格",
"本方最优价格",
"即时成交剩余撤销",
"最优五档即时成交剩余",
"全额成交或撤销",
"]",
"沪市可选",
"[",
"最优五档成交剩余撤销",
"最优五档成交剩余转限价",
"]"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L154-L167 | train |
shidenggui/easytrader | easytrader/clienttrader.py | ClientTrader.market_sell | def market_sell(self, security, amount, ttype=None, **kwargs):
"""
市价卖出
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩... | python | def market_sell(self, security, amount, ttype=None, **kwargs):
"""
市价卖出
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩... | [
"def",
"market_sell",
"(",
"self",
",",
"security",
",",
"amount",
",",
"ttype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_switch_left_menus",
"(",
"[",
"\"市价委托\", \"卖出\"])",
"",
"",
"",
"",
"return",
"self",
".",
"market_trade",
"... | 市价卖出
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价']
:return: {'entrust_no': '委托单号'} | [
"市价卖出",
":",
"param",
"security",
":",
"六位证券代码",
":",
"param",
"amount",
":",
"交易数量",
":",
"param",
"ttype",
":",
"市价委托类型,默认客户端默认选择,",
"深市可选",
"[",
"对手方最优价格",
"本方最优价格",
"即时成交剩余撤销",
"最优五档即时成交剩余",
"全额成交或撤销",
"]",
"沪市可选",
"[",
"最优五档成交剩余撤销",
"最优五档成交剩余转限价",
"]"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L169-L182 | train |
shidenggui/easytrader | easytrader/clienttrader.py | ClientTrader.market_trade | def market_trade(self, security, amount, ttype=None, **kwargs):
"""
市价交易
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交... | python | def market_trade(self, security, amount, ttype=None, **kwargs):
"""
市价交易
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交... | [
"def",
"market_trade",
"(",
"self",
",",
"security",
",",
"amount",
",",
"ttype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_set_market_trade_params",
"(",
"security",
",",
"amount",
")",
"if",
"ttype",
"is",
"not",
"None",
":",
"se... | 市价交易
:param security: 六位证券代码
:param amount: 交易数量
:param ttype: 市价委托类型,默认客户端默认选择,
深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销']
沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价']
:return: {'entrust_no': '委托单号'} | [
"市价交易",
":",
"param",
"security",
":",
"六位证券代码",
":",
"param",
"amount",
":",
"交易数量",
":",
"param",
"ttype",
":",
"市价委托类型,默认客户端默认选择,",
"深市可选",
"[",
"对手方最优价格",
"本方最优价格",
"即时成交剩余撤销",
"最优五档即时成交剩余",
"全额成交或撤销",
"]",
"沪市可选",
"[",
"最优五档成交剩余撤销",
"最优五档成交剩余转限价",
"]"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L184-L202 | train |
shidenggui/easytrader | easytrader/clienttrader.py | ClientTrader._set_market_trade_type | 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... | python | 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\"",
",",
"... | 根据选择的市价交易类型选择对应的下拉选项 | [
"根据选择的市价交易类型选择对应的下拉选项"
] | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L204-L218 | train |
shidenggui/easytrader | easytrader/clienttrader.py | BaseLoginClientTrader.prepare | 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:... | python | 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",
")",
":",
"if",
"config_path",
"is",
"no... | 登陆客户端
:param config_path: 登陆配置文件,跟参数登陆方式二选一
:param user: 账号
:param password: 明文密码
:param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe'
:param comm_password: 通讯密码
:return: | [
"登陆客户端",
":",
"param",
"config_path",
":",
"登陆配置文件,跟参数登陆方式二选一",
":",
"param",
"user",
":",
"账号",
":",
"param",
"password",
":",
"明文密码",
":",
"param",
"exe_path",
":",
"客户端路径类似",
"r",
"C",
":",
"\\\\",
"htzqzyb2",
"\\\\",
"xiadan",
".",
"exe",
"默认",
"r",
... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/clienttrader.py#L396-L426 | train |
shidenggui/easytrader | easytrader/yh_clienttrader.py | YHClientTrader.login | 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: 通讯密码, 华泰需要,可不设
... | python | 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",
")",
":",
"try",
":",
"self",
".",
"_app",
"=",
"pywinauto",
".",
"Application",
"(",
")",
".",
"connect",
"(",
... | 登陆客户端
:param user: 账号
:param password: 明文密码
:param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe',
默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe'
:param comm_password: 通讯密码, 华泰需要,可不设
:return: | [
"登陆客户端",
":",
"param",
"user",
":",
"账号",
":",
"param",
"password",
":",
"明文密码",
":",
"param",
"exe_path",
":",
"客户端路径类似",
"C",
":",
"\\\\",
"中国银河证券双子星3",
".",
"2",
"\\\\",
"Binarystar",
".",
"exe",
"默认",
"C",
":",
"\\\\",
"中国银河证券双子星3",
".",
"2",
"\\... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/yh_clienttrader.py#L25-L80 | train |
shidenggui/easytrader | easytrader/api.py | use | 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... | python | 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",
")",
":",
"if",
"not",
"debug",
":",
"log",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"if",
"broker",
".",
"lower",
"(",
")",
"in",
"[",
"\"xq\"",
",",
"\... | 用于生成特定的券商对象
: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.... | [
"用于生成特定的券商对象",
":",
"param",
"broker",
":",
"券商名支持",
"[",
"yh_client",
"银河客户端",
"]",
"[",
"ht_client",
"华泰客户端",
"]",
":",
"param",
"debug",
":",
"控制",
"debug",
"日志的显示",
"默认为",
"True",
":",
"param",
"initial_assets",
":",
"[",
"雪球参数",
"]",
"控制雪球初始资金,默认为一百万"... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/api.py#L16-L50 | train |
shidenggui/easytrader | easytrader/api.py | follower | def follower(platform, **kwargs):
"""用于生成特定的券商对象
:param platform:平台支持 ['jq', 'joinquant', '聚宽’]
:param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万,
总资金由 initial_assets * 组合当前净值 得出
:param total_assets: [雪球参数] 控制雪球总资金,无默认值,
若设置则覆盖 initial_assets
:return the class of follower
Usage::
... | python | 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",
")",
":",
"if",
"platform",
".",
"lower",
"(",
")",
"in",
"[",
"\"rq\"",
",",
"\"ricequant\"",
",",
"\"米筐\"]:",
"",
"",
"return",
"RiceQuantFollower",
"(",
")",
"if",
"platform",
".",
"lower"... | 用于生成特定的券商对象
:param platform:平台支持 ['jq', 'joinquant', '聚宽’]
:param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万,
总资金由 initial_assets * 组合当前净值 得出
:param total_assets: [雪球参数] 控制雪球总资金,无默认值,
若设置则覆盖 initial_assets
:return the class of follower
Usage::
>>> import easytrader
>>> u... | [
"用于生成特定的券商对象",
":",
"param",
"platform",
":",
"平台支持",
"[",
"jq",
"joinquant",
"聚宽’",
"]",
":",
"param",
"initial_assets",
":",
"[",
"雪球参数",
"]",
"控制雪球初始资金,默认为一万",
"总资金由",
"initial_assets",
"*",
"组合当前净值",
"得出",
":",
"param",
"total_assets",
":",
"[",
"雪球参数",
... | e5ae4daeda4ea125763a95b280dd694c7f68257d | https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/api.py#L53-L77 | train |
tensorpack/tensorpack | tensorpack/dataflow/format.py | CaffeLMDB | 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... | python | 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",
")",
":",
"cpb",
"=",
"get_caffe_pb",
"(",
")",
"lmdb_data",
"=",
"LMDBData",
"(",
"lmdb_path",
",",
"shuffle",
",",
"keys",
")",
"def",
"decoder",
"(",
"k",
... | 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`.
... | [
"Read",
"a",
"Caffe",
"LMDB",
"file",
"where",
"each",
"value",
"contains",
"a",
"caffe",
".",
"Datum",
"protobuf",
".",
"Produces",
"datapoints",
"of",
"the",
"format",
":",
"[",
"HWC",
"image",
"label",
"]",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/format.py#L167-L202 | train |
tensorpack/tensorpack | tensorpack/utils/nvml.py | NvidiaDevice.memory | 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):
... | python | 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",
")",
":",
"class",
"GpuMemoryInfo",
"(",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"'total'",
",",
"c_ulonglong",
")",
",",
"(",
"'free'",
",",
"c_ulonglong",
")",
",",
"(",
"'used'",
",",
"c_ulonglong",
")",
",",
... | Memory information in bytes
Example:
>>> print(ctx.device(0).memory())
{'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}
Returns:
total/used/free memory in bytes | [
"Memory",
"information",
"in",
"bytes"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L92-L113 | train |
tensorpack/tensorpack | tensorpack/utils/nvml.py | NvidiaDevice.utilization | 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
... | python | 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",
")",
":",
"class",
"GpuUtilizationInfo",
"(",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"'gpu'",
",",
"c_uint",
")",
",",
"(",
"'memory'",
",",
"c_uint",
")",
",",
"]",
"c_util",
"=",
"GpuUtilizationInfo",
"(",
... | 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:
>>>... | [
"Percent",
"of",
"time",
"over",
"the",
"past",
"second",
"was",
"utilized",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L115-L138 | train |
tensorpack/tensorpack | tensorpack/utils/nvml.py | NVMLContext.num_devices | 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 | python | 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",
")",
":",
"c_count",
"=",
"c_uint",
"(",
")",
"_check_return",
"(",
"_NVML",
".",
"get_function",
"(",
"\"nvmlDeviceGetCount_v2\"",
")",
"(",
"byref",
"(",
"c_count",
")",
")",
")",
"return",
"c_count",
".",
"value"
] | Get number of devices | [
"Get",
"number",
"of",
"devices"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L171-L176 | train |
tensorpack/tensorpack | tensorpack/utils/nvml.py | NVMLContext.device | 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)
... | python | 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",
")",
":",
"class",
"GpuDevice",
"(",
"Structure",
")",
":",
"pass",
"c_nvmlDevice_t",
"=",
"POINTER",
"(",
"GpuDevice",
")",
"c_index",
"=",
"c_uint",
"(",
"idx",
")",
"device",
"=",
"c_nvmlDevice_t",
"(",
")",
... | Get a specific GPU device
Args:
idx: index of device
Returns:
NvidiaDevice: single GPU device | [
"Get",
"a",
"specific",
"GPU",
"device"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L185-L204 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/cifar.py | maybe_download_and_extract | 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... | python | 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",
")",
":",
"assert",
"cifar_classnum",
"==",
"10",
"or",
"cifar_classnum",
"==",
"100",
"if",
"cifar_classnum",
"==",
"10",
":",
"cifar_foldername",
"=",
"'cifar-10-batches-py'",
"else",... | Download and extract the tarball from Alex's website. Copied from tensorflow example | [
"Download",
"and",
"extract",
"the",
"tarball",
"from",
"Alex",
"s",
"website",
".",
"Copied",
"from",
"tensorflow",
"example"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L24-L39 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/cifar.py | CifarBase.get_per_pixel_mean | 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 ... | python | 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'",
")",
")",
":",
"for",
"name",
"in",
"names",
":",
"assert",
"name",
"in",
"[",
"'train'",
",",
"'test'",
"]",
",",
"name",
"train_files",
",",
"test_files",
","... | 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 | [
"Args",
":",
"names",
"(",
"tuple",
"[",
"str",
"]",
")",
":",
"the",
"names",
"(",
"train",
"or",
"test",
")",
"of",
"the",
"datasets"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L135-L154 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/cifar.py | CifarBase.get_per_channel_mean | 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... | python | 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'",
")",
")",
":",
"mean",
"=",
"self",
".",
"get_per_pixel_mean",
"(",
"names",
")",
"return",
"np",
".",
"mean",
"(",
"mean",
",",
"axis",
"=",
"(",
"0",
",",... | 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. | [
"Args",
":",
"names",
"(",
"tuple",
"[",
"str",
"]",
")",
":",
"the",
"names",
"(",
"train",
"or",
"test",
")",
"of",
"the",
"datasets"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L163-L172 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_mrcnn.py | maskrcnn_loss | 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]... | python | 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",
")",
":",
"num_fg",
"=",
"tf",
".",
"size",
"(",
"fg_labels",
",",
"out_type",
"=",
"tf",
".",
"int64",
")",
"indices",
"=",
"tf",
".",
"stack",
"(",
"[",
"tf",
".",
... | Args:
mask_logits: #fg x #category xhxw
fg_labels: #fg, in 1~#class, int64
fg_target_masks: #fgxhxw, float32 | [
"Args",
":",
"mask_logits",
":",
"#fg",
"x",
"#category",
"xhxw",
"fg_labels",
":",
"#fg",
"in",
"1~#class",
"int64",
"fg_target_masks",
":",
"#fgxhxw",
"float32"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_mrcnn.py#L16-L51 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_mrcnn.py | maskrcnn_upXconv_head | 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... | python | 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",
")",
":",
"assert",
"norm",
"in",
"[",
"None",
",",
"'GN'",
"]",
",",
"norm",
"l",
"=",
"feature",
"with",
"argscope",
"(",
"[",
"Conv2D",
... | 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): | [
"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",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_mrcnn.py#L55-L79 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/svhn.py | SVHNDigit.get_per_pixel_mean | 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', '... | python | 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'",
")",
")",
":",
"for",
"name",
"in",
"names",
":",
"assert",
"name",
"in",
"[",
"'train'",
",",
"'test'",
",",
"'extra'",
"]",
",",
"name",
"images",
"=",
"... | Args:
names (tuple[str]): names of the dataset split
Returns:
a 32x32x3 image, the mean of all images in the given datasets | [
"Args",
":",
"names",
"(",
"tuple",
"[",
"str",
"]",
")",
":",
"names",
"of",
"the",
"dataset",
"split"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/svhn.py#L65-L76 | train |
tensorpack/tensorpack | tensorpack/graph_builder/model_desc.py | build_or_reuse_placeholder | 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... | python | 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",
")",
":",
"g",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"name",
"=",
"tensor_spec",
".",
"name",
"try",
":",
"tensor",
"=",
"g",
".",
"get_tensor_by_name",
"(",
"name",
"+",
"':0'",
")",
"ass... | 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: | [
"Build",
"a",
"tf",
".",
"placeholder",
"from",
"the",
"metadata",
"in",
"the",
"given",
"tensor",
"spec",
"or",
"return",
"an",
"existing",
"one",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/model_desc.py#L19-L41 | train |
tensorpack/tensorpack | tensorpack/graph_builder/model_desc.py | ModelDescBase.get_input_signature | 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... | python | 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",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"G",
":",
"# create these placeholder in a temporary graph",
"inputs",
"=",
"self",
".",
"inputs",
"(",
")",
"if",
"isinstance",
"("... | Returns:
A list of :class:`tf.TensorSpec`, which describes the inputs of this model.
The result is cached for each instance of :class:`ModelDescBase`. | [
"Returns",
":",
"A",
"list",
"of",
":",
"class",
":",
"tf",
".",
"TensorSpec",
"which",
"describes",
"the",
"inputs",
"of",
"this",
"model",
".",
"The",
"result",
"is",
"cached",
"for",
"each",
"instance",
"of",
":",
"class",
":",
"ModelDescBase",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/model_desc.py#L79-L92 | train |
tensorpack/tensorpack | tensorpack/tfutils/dependency.py | dependency_of_targets | 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... | python | 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",
")",
":",
"# TODO tensorarray? sparsetensor?",
"if",
"isinstance",
"(",
"op",
",",
"tf",
".",
"Tensor",
")",
":",
"op",
"=",
"op",
".",
"op",
"assert",
"isinstance",
"(",
"op",
",",
"tf",
".",
"O... | 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... | [
"Check",
"that",
"op",
"is",
"in",
"the",
"subgraph",
"induced",
"by",
"the",
"dependencies",
"of",
"targets",
".",
"The",
"result",
"is",
"memoized",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L16-L38 | train |
tensorpack/tensorpack | tensorpack/tfutils/dependency.py | dependency_of_fetches | 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:... | python | 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",
")",
":",
"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... | 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... | [
"Check",
"that",
"op",
"is",
"in",
"the",
"subgraph",
"induced",
"by",
"the",
"dependencies",
"of",
"fetches",
".",
"fetches",
"may",
"have",
"more",
"general",
"structure",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L41-L66 | train |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | create_scalar_summary | 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=... | python | 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",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"six",
".",
"string_types",
")",
",",
"type",
"(",
"name",
")",
"v",
"=",
"float",
"(",
"v",
")",
"s",
"=",
"tf",
".",
"Summary",
"(",
")",
... | Args:
name (str):
v (float): scalar value
Returns:
tf.Summary: a tf.Summary object with name and simple scalar value v. | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"v",
"(",
"float",
")",
":",
"scalar",
"value",
"Returns",
":",
"tf",
".",
"Summary",
":",
"a",
"tf",
".",
"Summary",
"object",
"with",
"name",
"and",
"simple",
"scalar",
"value",
"v",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L41-L53 | train |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | create_image_summary | 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 ... | python | 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",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"six",
".",
"string_types",
")",
",",
"type",
"(",
"name",
")",
"n",
",",
"h",
",",
"w",
",",
"c",
"=",
"val",
".",
"shape",
"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: | [
"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"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L56-L92 | train |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | add_tensor_summary | 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):... | python | 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",
")",
":",
"types",
"=",
"set",
"(",
"types",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"x",
... | 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... | [
"Summarize",
"a",
"tensor",
"by",
"different",
"methods",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L95-L137 | train |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | add_activation_summary | 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... | python | 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",
")",
":",
"ndim",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"ndims",
"if",
"ndim",
"<",
"2",
":",
"logger",
".",
"warn... | 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... | [
"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",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L140-L158 | train |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | add_param_summary | 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... | python | 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",
")",
":",
"collections",
"=",
"kwargs",
".",
"pop",
"(",
"'collections'",
",",
"None",
")",
"assert",
"len",
"(",
"kwargs",
")",
"==",
"0",
",",
"\"Unknown 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]).
Summary type is defined in :func:`add_tensor_... | [
"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... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L161-L195 | train |
tensorpack/tensorpack | tensorpack/tfutils/summary.py | add_moving_summary | 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 ... | python | 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",
")",
":",
"decay",
"=",
"kwargs",
".",
"pop",
"(",
"'decay'",
",",
"0.95",
")",
"coll",
"=",
"kwargs",
".",
"pop",
"(",
"'collection'",
",",
"MOVING_SUMMARY_OPS_KEY",
")",
"summ_coll... | 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.
... | [
"Summarize",
"the",
"moving",
"average",
"for",
"scalar",
"tensors",
".",
"This",
"function",
"is",
"a",
"no",
"-",
"op",
"if",
"not",
"calling",
"from",
"main",
"training",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L198-L270 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_cascade.py | CascadeRCNNHead.run_head | 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... | python | 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",
")",
":",
"reg_weights",
"=",
"tf",
".",
"constant",
"(",
"cfg",
".",
"CASCADE",
".",
"BBOX_REG_WEIGHTS",
"[",
"stage",
"]",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"pooled_feature",
... | Args:
proposals: BoxProposals
stage: 0, 1, 2
Returns:
FastRCNNHead
Nx4, updated boxes | [
"Args",
":",
"proposals",
":",
"BoxProposals",
"stage",
":",
"0",
"1",
"2"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L54-L74 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_cascade.py | CascadeRCNNHead.match_box_with_gt | 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) #... | python | 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",
")",
":",
"if",
"self",
".",
"is_training",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'match_box_with_gt_{}'",
".",
"format",
"(",
"iou_threshold",
")",
")",
":",
"iou",
"=",
"p... | Args:
boxes: Nx4
Returns:
BoxProposals | [
"Args",
":",
"boxes",
":",
"Nx4",
"Returns",
":",
"BoxProposals"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L76-L94 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_cascade.py | CascadeRCNNHead.decoded_output_boxes | 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]) | python | 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",
")",
":",
"ret",
"=",
"self",
".",
"_cascade_boxes",
"[",
"-",
"1",
"]",
"ret",
"=",
"tf",
".",
"expand_dims",
"(",
"ret",
",",
"1",
")",
"# class-agnostic",
"return",
"tf",
".",
"tile",
"(",
"ret",
",",
"[... | Returns:
Nx#classx4 | [
"Returns",
":",
"Nx#classx4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L103-L110 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_cascade.py | CascadeRCNNHead.output_scores | 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... | python | 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",
")",
":",
"scores",
"=",
"[",
"head",
".",
"output_scores",
"(",
"'cascade_scores_stage{}'",
".",
"format",
"(",
"idx",
"+",
"1",
")",
")",
"for",
"idx",
",",
"head",
"in",
"enumerate",
"("... | Returns:
Nx#class | [
"Returns",
":",
"Nx#class"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_cascade.py#L112-L119 | train |
tensorpack/tensorpack | examples/FasterRCNN/train.py | do_visualize | 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... | python | 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'",
")",
":",
"df",
"=",
"get_train_dataflow",
"(",
")",
"# we don't visualize mask stuff",
"df",
".",
"reset_state",
"(",
")",
"pred",
"="... | Visualize some intermediate results (proposals, raw predictions) inside the pipeline. | [
"Visualize",
"some",
"intermediate",
"results",
"(",
"proposals",
"raw",
"predictions",
")",
"inside",
"the",
"pipeline",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/train.py#L34-L83 | train |
tensorpack/tensorpack | tensorpack/models/registry.py | get_registered_layer | 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... | python | 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",
")",
":",
"ret",
"=",
"_LAYER_REGISTRY",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"ret",
"==",
"_NameConflict",
":",
"raise",
"KeyError",
"(",
"\"Layer named '{}' is registered with `@layer_register` more than once!\... | Args:
name (str): the name of the layer, e.g. 'Conv2D'
Returns:
the wrapped layer function, or None if not registered. | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"the",
"name",
"of",
"the",
"layer",
"e",
".",
"g",
".",
"Conv2D",
"Returns",
":",
"the",
"wrapped",
"layer",
"function",
"or",
"None",
"if",
"not",
"registered",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/registry.py#L39-L49 | train |
tensorpack/tensorpack | tensorpack/models/registry.py | layer_register | 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... | python | 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",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | 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... | [
"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"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/registry.py#L64-L155 | train |
tensorpack/tensorpack | tensorpack/train/tower.py | TowerTrainer.get_predictor | 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... | python | 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",
")",
":",
"assert",
"self",
".",
"tower_func",
"is",
"not",
"None",
",",
"\"Must set tower_func on the trainer to use get_predictor()!\"",
"tower_name",
"=",
"'tow... | 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... | [
"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... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/tower.py#L89-L147 | train |
tensorpack/tensorpack | examples/basics/export-model.py | export_serving | 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'])
... | python | 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",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"InferenceOnlyModel",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img_bytes'",
... | Export trained model to use it in TensorFlow Serving or cloudML. | [
"Export",
"trained",
"model",
"to",
"use",
"it",
"in",
"TensorFlow",
"Serving",
"or",
"cloudML",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L106-L113 | train |
tensorpack/tensorpack | examples/basics/export-model.py | export_compact | 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_... | python | 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",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"Model",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img'",
"]",
",",
"out... | Export trained model to use it as a frozen and pruned inference graph in
mobile applications. | [
"Export",
"trained",
"model",
"to",
"use",
"it",
"as",
"a",
"frozen",
"and",
"pruned",
"inference",
"graph",
"in",
"mobile",
"applications",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L116-L124 | train |
tensorpack/tensorpack | examples/basics/export-model.py | apply | 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... | python | 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",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"Model",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img'",
"]",
",",
"output_names... | Run inference from a training model checkpoint. | [
"Run",
"inference",
"from",
"a",
"training",
"model",
"checkpoint",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L127-L138 | train |
tensorpack/tensorpack | examples/basics/export-model.py | apply_inference_graph | 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... | python | 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",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"InferenceOnlyModel",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img_byt... | Run inference from a different graph, which receives encoded images buffers. | [
"Run",
"inference",
"from",
"a",
"different",
"graph",
"which",
"receives",
"encoded",
"images",
"buffers",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L141-L153 | train |
tensorpack/tensorpack | examples/basics/export-model.py | apply_compact | 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 =... | python | 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",
")",
":",
"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... | Run the pruned and frozen inference graph. | [
"Run",
"the",
"pruned",
"and",
"frozen",
"inference",
"graph",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L156-L169 | train |
tensorpack/tensorpack | tensorpack/models/_old_batch_norm.py | BatchNorm | 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... | python | 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",
"(",
")",
",... | 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... | [
"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... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/_old_batch_norm.py#L67-L169 | train |
tensorpack/tensorpack | tensorpack/dataflow/common.py | SelectComponent | 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... | python | 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",
")",
":",
"return",
"MapData",
"(",
"ds",
",",
"lambda",
"dp",
":",
"[",
"dp",
"[",
"i",
"]",
"for",
"i",
"in",
"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, c2] | [
"Select",
"/",
"reorder",
"components",
"from",
"datapoints",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/common.py#L570-L586 | train |
tensorpack/tensorpack | tensorpack/dataflow/common.py | PrintData._analyze_input_data | 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
... | python | 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",
")",
":",
"class",
"_elementInfo",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"el",
... | 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... | [
"Gather",
"useful",
"debug",
"information",
"from",
"a",
"datapoint",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/common.py#L745-L804 | train |
tensorpack/tensorpack | tensorpack/utils/stats.py | RatioCounter.feed | 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 | python | 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",
")",
":",
"self",
".",
"_tot",
"+=",
"total",
"self",
".",
"_cnt",
"+=",
"count"
] | Args:
cnt(int): the count of some event of interest.
tot(int): the total number of events. | [
"Args",
":",
"cnt",
"(",
"int",
")",
":",
"the",
"count",
"of",
"some",
"event",
"of",
"interest",
".",
"tot",
"(",
"int",
")",
":",
"the",
"total",
"number",
"of",
"events",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/stats.py#L67-L74 | train |
tensorpack/tensorpack | tensorpack/utils/stats.py | BinaryStatistics.feed | 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... | python | 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",
")",
":",
"assert",
"pred",
".",
"shape",
"==",
"label",
".",
"shape",
",",
"\"{} != {}\"",
".",
"format",
"(",
"pred",
".",
"shape",
",",
"label",
".",
"shape",
")",
"self",
".",
"nr_pos",
"+=... | Args:
pred (np.ndarray): binary array.
label (np.ndarray): binary array of the same size. | [
"Args",
":",
"pred",
"(",
"np",
".",
"ndarray",
")",
":",
"binary",
"array",
".",
"label",
"(",
"np",
".",
"ndarray",
")",
":",
"binary",
"array",
"of",
"the",
"same",
"size",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/stats.py#L123-L135 | train |
tensorpack/tensorpack | tensorpack/utils/stats.py | OnlineMoments.feed | 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 | python | 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",
")",
":",
"self",
".",
"_n",
"+=",
"1",
"delta",
"=",
"x",
"-",
"self",
".",
"_mean",
"self",
".",
"_mean",
"+=",
"delta",
"*",
"(",
"1.0",
"/",
"self",
".",
"_n",
")",
"delta2",
"=",
"x",
"-",
"self",
... | Args:
x (float or np.ndarray): must have the same shape. | [
"Args",
":",
"x",
"(",
"float",
"or",
"np",
".",
"ndarray",
")",
":",
"must",
"have",
"the",
"same",
"shape",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/stats.py#L173-L182 | train |
tensorpack/tensorpack | tensorpack/tfutils/optimizer.py | apply_grad_processors | 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... | python | 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",
")",
":",
"assert",
"isinstance",
"(",
"gradprocs",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"gradprocs",
"for",
"gp",
"in",
"gradprocs",
":",
"assert",
"isinstance",
"(",
"gp",
",",
"Gr... | 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... | [
"Wrapper",
"around",
"optimizers",
"to",
"apply",
"gradient",
"processors",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/optimizer.py#L44-L76 | train |
tensorpack/tensorpack | examples/FasterRCNN/eval.py | _paste_mask | 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... | python | 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",
")",
":",
"# int() is floor",
"# box fpcoor=0.0 -> intcoor=0.0",
"x0",
",",
"y0",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"box",
"[",
":",
"2",
"]",
"+",
"0.5",
")",
")",
"# box fpcoor=h -> i... | Args:
box: 4 float
mask: MxM floats
shape: h,w
Returns:
A uint8 binary image of hxw. | [
"Args",
":",
"box",
":",
"4",
"float",
"mask",
":",
"MxM",
"floats",
"shape",
":",
"h",
"w",
"Returns",
":",
"A",
"uint8",
"binary",
"image",
"of",
"hxw",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L44-L69 | train |
tensorpack/tensorpack | examples/FasterRCNN/eval.py | predict_image | 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])
... | python | 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",
")",
":",
"orig_shape",
"=",
"img",
".",
"shape",
"[",
":",
"2",
"]",
"resizer",
"=",
"CustomResize",
"(",
"cfg",
".",
"PREPROC",
".",
"TEST_SHORT_EDGE_SIZE",
",",
"cfg",
".",
"PREPROC",
".",
"MAX_SI... | 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] | [
"Run",
"detection",
"on",
"one",
"image",
"using",
"the",
"TF",
"callable",
".",
"This",
"function",
"should",
"handle",
"the",
"preprocessing",
"internally",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L72-L105 | train |
tensorpack/tensorpack | examples/FasterRCNN/eval.py | predict_dataflow | 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... | python | 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",
")",
":",
"df",
".",
"reset_state",
"(",
")",
"all_results",
"=",
"[",
"]",
"with",
"ExitStack",
"(",
")",
"as",
"stack",
":",
"# tqdm is not quite thread-safe: https://gith... | 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... | [
"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",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L108-L146 | train |
tensorpack/tensorpack | examples/FasterRCNN/eval.py | multithread_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`... | python | 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",
")",
":",
"num_worker",
"=",
"len",
"(",
"model_funcs",
")",
"assert",
"len",
"(",
"dataflows",
")",
"==",
"num_worker",
"if",
"num_worker",
"==",
"1",
":",
"return",
"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... | [
"Running",
"multiple",
"predict_dataflow",
"in",
"multiple",
"threads",
"and",
"aggregate",
"the",
"results",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L149-L172 | train |
tensorpack/tensorpack | tensorpack/models/fc.py | batch_flatten | 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])) | python | 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",
")",
":",
"shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
":",
"]",
"if",
"None",
"not",
"in",
"shape",
":",
"return",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
",... | Flatten the tensor except the first dimension. | [
"Flatten",
"the",
"tensor",
"except",
"the",
"first",
"dimension",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/fc.py#L15-L22 | train |
tensorpack/tensorpack | tensorpack/models/fc.py | FullyConnected | 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... | python | 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",
"=",
... | 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 | [
"A",
"wrapper",
"around",
"tf",
".",
"layers",
".",
"Dense",
".",
"One",
"difference",
"to",
"maintain",
"backward",
"-",
"compatibility",
":",
"Default",
"weight",
"initializer",
"is",
"variance_scaling_initializer",
"(",
"2",
".",
"0",
")",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/fc.py#L29-L73 | train |
tensorpack/tensorpack | tensorpack/predict/concurrency.py | MultiProcessPredictWorker._init_runtime | 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 = ... | python | 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",
")",
":",
"if",
"self",
".",
"idx",
"!=",
"0",
":",
"from",
"tensorpack",
".",
"models",
".",
"registry",
"import",
"disable_layer_logging",
"disable_layer_logging",
"(",
")",
"self",
".",
"predictor",
"=",
"OfflinePredicto... | Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll
have workers that run on multiGPUs | [
"Call",
"_init_runtime",
"under",
"different",
"CUDA_VISIBLE_DEVICES",
"you",
"ll",
"have",
"workers",
"that",
"run",
"on",
"multiGPUs"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L35-L45 | train |
tensorpack/tensorpack | tensorpack/predict/concurrency.py | PredictorWorkerThread.fetch_batch | 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... | python | 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",
")",
":",
"inp",
",",
"f",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"nr_input_var",
"=",
"len",
"(",
"inp",
")",
"batched",
",",
"futures",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"nr_input_v... | Fetch a batch of data without waiting | [
"Fetch",
"a",
"batch",
"of",
"data",
"without",
"waiting"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L110-L129 | train |
tensorpack/tensorpack | tensorpack/predict/concurrency.py | MultiThreadAsyncPredictor.put_task | 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 | python | 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",
")",
":",
"f",
"=",
"Future",
"(",
")",
"if",
"callback",
"is",
"not",
"None",
":",
"f",
".",
"add_done_callback",
"(",
"callback",
")",
"self",
".",
"input_queue",
".",
"put",
... | Same as in :meth:`AsyncPredictorBase.put_task`. | [
"Same",
"as",
"in",
":",
"meth",
":",
"AsyncPredictorBase",
".",
"put_task",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L172-L180 | train |
tensorpack/tensorpack | tensorpack/utils/serialize.py | loads_msgpack | 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... | python | 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",
")",
":",
"# 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... | Args:
buf: the output of `dumps`. | [
"Args",
":",
"buf",
":",
"the",
"output",
"of",
"dumps",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/serialize.py#L32-L43 | train |
tensorpack/tensorpack | tensorpack/models/batch_norm.py | BatchNorm | 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',
... | python | 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",
".",
"zero... | 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... | [
"Almost",
"equivalent",
"to",
"tf",
".",
"layers",
".",
"batch_normalization",
"but",
"different",
"(",
"and",
"more",
"powerful",
")",
"in",
"the",
"following",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/batch_norm.py#L68-L319 | train |
tensorpack/tensorpack | tensorpack/models/batch_norm.py | BatchRenorm | 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... | python | 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-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... | [
"Batch",
"Renormalization",
"layer",
"as",
"described",
"in",
"the",
"paper",
":",
"Batch",
"Renormalization",
":",
"Towards",
"Reducing",
"Minibatch",
"Dependence",
"in",
"Batch",
"-",
"Normalized",
"Models",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"ab... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/batch_norm.py#L331-L399 | train |
tensorpack/tensorpack | examples/GAN/DCGAN.py | Model.generator | 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):
... | python | 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",
")",
":",
"nf",
"=",
"64",
"l",
"=",
"FullyConnected",
"(",
"'fc0'",
",",
"z",
",",
"nf",
"*",
"8",
"*",
"4",
"*",
"4",
",",
"activation",
"=",
"tf",
".",
"identity",
")",
"l",
"=",
"tf",
".",
"resha... | return an image generated from z | [
"return",
"an",
"image",
"generated",
"from",
"z"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/DCGAN.py#L46-L58 | train |
tensorpack/tensorpack | examples/GAN/DCGAN.py | Model.discriminator | 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')
... | python | 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",
")",
":",
"nf",
"=",
"64",
"with",
"argscope",
"(",
"Conv2D",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=",
"2",
")",
":",
"l",
"=",
"(",
"LinearWrap",
"(",
"imgs",
")",
".",
"Conv2D",
"(",
"... | return a (b, 1) logits | [
"return",
"a",
"(",
"b",
"1",
")",
"logits"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/DCGAN.py#L61-L77 | train |
tensorpack/tensorpack | examples/FasterRCNN/utils/box_ops.py | area | 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]) | python | 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",
")",
":",
"x_min",
",",
"y_min",
",",
"x_max",
",",
"y_max",
"=",
"tf",
".",
"split",
"(",
"boxes",
",",
"4",
",",
"axis",
"=",
"1",
")",
"return",
"tf",
".",
"squeeze",
"(",
"(",
"y_max",
"-",
"y_min",
")",
"*",
... | Args:
boxes: nx4 floatbox
Returns:
n | [
"Args",
":",
"boxes",
":",
"nx4",
"floatbox"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/box_ops.py#L16-L25 | train |
tensorpack/tensorpack | examples/FasterRCNN/utils/box_ops.py | pairwise_intersection | 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=... | python | 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",
")",
":",
"x_min1",
",",
"y_min1",
",",
"x_max1",
",",
"y_max1",
"=",
"tf",
".",
"split",
"(",
"boxlist1",
",",
"4",
",",
"axis",
"=",
"1",
")",
"x_min2",
",",
"y_min2",
",",
"x_max2",
... | Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections | [
"Compute",
"pairwise",
"intersection",
"areas",
"between",
"boxes",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/box_ops.py#L29-L47 | train |
tensorpack/tensorpack | examples/FasterRCNN/utils/box_ops.py | pairwise_iou | 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... | python | 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",
")",
":",
"intersections",
"=",
"pairwise_intersection",
"(",
"boxlist1",
",",
"boxlist2",
")",
"areas1",
"=",
"area",
"(",
"boxlist1",
")",
"areas2",
"=",
"area",
"(",
"boxlist2",
")",
"unions",
"=",
... | 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. | [
"Computes",
"pairwise",
"intersection",
"-",
"over",
"-",
"union",
"between",
"box",
"collections",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/box_ops.py#L51-L68 | train |
tensorpack/tensorpack | examples/Char-RNN/char-rnn.py | sample | 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... | python | 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",
")",
":",
"# initialize vocabulary and sequence length",
"param",
".",
"seq_len",
"=",
"1",
"ds",
"=",
"CharRNNData",
"(",
"param",
".",
"corpus",
",",
"100000",
")",
"pred",
"=",
"OfflinePredictor",
... | :param path: path to the model
:param start: a `str`. the starting characters
:param length: a `int`. the length of text to generate | [
":",
"param",
"path",
":",
"path",
"to",
"the",
"model",
":",
"param",
"start",
":",
"a",
"str",
".",
"the",
"starting",
"characters",
":",
"param",
"length",
":",
"a",
"int",
".",
"the",
"length",
"of",
"text",
"to",
"generate"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Char-RNN/char-rnn.py#L132-L167 | train |
tensorpack/tensorpack | tensorpack/models/nonlin.py | Maxout | 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... | python | 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",
")",
":",
"input_shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"ndim",
"=",
"len",
"(",
"input_shape",
")",
"assert",
"ndim",
"==",
"4",
"or",
"ndim",
"==",
"2",
"ch",
"=",
"in... | 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",
">",
"_",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L15-L35 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.