text
stringlengths
81
112k
雪球登陆, 需要设置 cookies :param cookies: 雪球登陆需要设置 cookies, 具体见 https://smalltool.github.io/2016/08/02/cookie/ :return: def login(self, user=None, password=None, **kwargs): """ 雪球登陆, 需要设置 cookies :param cookies: 雪球登陆需要设置 cookies, 具体见 https://smalltool.github.io/...
跟踪 joinquant 对应的模拟交易,支持多用户多策略 :param users: 支持 easytrader 的用户对象,支持使用 [] 指定多个用户 :param strategies: 雪球组合名, 类似 ZH123450 :param total_assets: 雪球组合对应的总资产, 格式 [组合1对应资金, 组合2对应资金] 若 strategies=['ZH000001', 'ZH000002'], 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元 ...
根据实际持仓值计算雪球卖出股数 因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。 导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。 而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量, 导致卖出失败 :param stock_code: 证券代码 :type stock_code: str :param amount: 卖出股份数 :type amount: int :return:...
获取组合信息 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_i...
parse cookies str to dict :param cookies: cookies str :type cookies: str :return: cookie dict :rtype: dict def parse_cookies_str(cookies): """ parse cookies str to dict :param cookies: cookies str :type cookies: str :return: cookie dict :rtype: dict """ cookie_dict = {} ...
判断股票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 def get_stock_type(stock_code): """判断股票ID对应的证券市场 匹配规...
识别验证码,返回识别后的字符串,使用 tesseract 实现 :param image_path: 图片路径 :param broker: 券商 ['ht', 'yjb', 'gf', 'yh'] :return recognized: verify code string def recognize_verify_code(image_path, broker="ht"): """识别验证码,返回识别后的字符串,使用 tesseract 实现 :param image_path: 图片路径 :param broker: 券商 ['ht', 'yjb', 'gf', 'yh'] ...
封装了tesseract的识别,部署在阿里云上,服务端源码地址为: https://github.com/shidenggui/yh_verify_code_docker 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: ...
获得用于查询的默认日期, 今天的日期, 以及30天前的日期 用于查询的日期格式通常为 20160211 :return: 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.strf...
查询今天可以申购的新股信息 :return: 今日可申购新股列表 apply_code申购代码 price发行价格 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", ...
登陆接口 :param user: 用户名 :param password: 密码 :param kwargs: 其他参数 :return: def login(self, user=None, password=None, **kwargs): """ 登陆接口 :param user: 用户名 :param password: 密码 :param kwargs: 其他参数 :return: """ headers = self._gene...
跟踪平台对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param strategies: 雪球组合名, 类似 ZH123450 :param total_assets: 雪球组合对应的总资产, 格式 [ 组合1对应资金, 组合2对应资金 ] 若 strategies=['ZH000001', 'ZH000002'] 设置 total_assets=[10000, 10000], 则表明每个组合对应的资产为 1w 元, 假设组合 ZH000001 加仓 价...
计算考虑滑点之后的价格 :param action: 交易动作, 支持 ['buy', 'sell'] :param price: 原始交易价格 :return: 考虑滑点后的交易价格 def _calculate_price_by_slippage(self, action: str, price: float) -> float: """ 计算考虑滑点之后的价格 :param action: 交易动作, 支持 ['buy', 'sell'] :param price: 原始交易价格 :return: ...
跟踪下单worker :param strategy: 策略id :param name: 策略名字 :param interval: 轮询策略的时间间隔,单位为秒 def track_strategy_worker(self, strategy, name, interval=10, **kwargs): """跟踪下单worker :param strategy: 策略id :param name: 策略名字 :param interval: 轮询策略的时间间隔,单位为秒""" while True:...
分发交易指令到对应的 user 并执行 :param trade_cmd: :param users: :param expire_seconds: :param entrust_prop: :param send_interval: :return: def _execute_trade_cmd( self, trade_cmd, users, expire_seconds, entrust_prop, send_interval ): """分发交易指令到对应的 user 并执行 ...
:param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足 def trade_worker( self, users, expire_seconds=120, entrust_prop="limit", send_interval=0 ): """ :param send_interval: 交易发送间隔, 默认为0s。调大可防止卖出买入时买出单没有及时成交导致的买入金额不足 """ while True: trade_cmd = self.trad...
设置雪球 cookies,代码来自于 https://github.com/shidenggui/easytrader/issues/269 :param cookies: 雪球 cookies :type cookies: str def _set_cookies(self, cookies): """设置雪球 cookies,代码来自于 https://github.com/shidenggui/easytrader/issues/269 :param cookies: 雪球 cookies :type cookie...
转换参数到登录所需的字典格式 :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): """ ...
通过雪球的接口获取股票详细信息 :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'房地产'...
获取组合信息 :return: 字典 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_inf...
获取账户资金状况 :return: 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(portf...
获取雪球持仓 :return: 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 = positi...
获取持仓 :return: 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 ...
获取雪球调仓历史 :param instance: :param owner: :return: def _get_xq_history(self): """ 获取雪球调仓历史 :param instance: :param owner: :return: """ data = { "cube_symbol": str(self.account_config["portfolio_code"]), "count": 20, ...
获取委托单(目前返回20次调仓的结果) 操作数量都按1手模拟换算的 :return: 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_e...
对未成交的调仓进行伪撤单 :param entrust_no: :return: 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...
雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数 def adjust_weight(self, stock_code, weight): """ 雪球组合调仓, weight 为调整后的仓位比例 :param stock_code: str 股票代码 :param weight: float 调整之后的持仓百分比, 0 - 100 之间的浮点数 """ ...
调仓 :param security: :param price: :param amount: :param volume: :param entrust_bs: :return: def _trade(self, security, price=0, amount=0, volume=0, entrust_bs="buy"): """ 调仓 :param security: :param price: :param amount: :pa...
买入卖出股票 :param security: 股票代码 :param price: 买入价格 :param amount: 买入股数 :param volume: 买入总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: def buy(self, security, price=0, amount=0, volume=0, entrust_prop=0): """买入卖出股票 :param security: 股票代码 :para...
卖出股票 :param security: 股票代码 :param price: 卖出价格 :param amount: 卖出股数 :param volume: 卖出总金额 由 volume / price 取整, 若指定 price 则此参数无效 :param entrust_prop: def sell(self, security, price=0, amount=0, volume=0, entrust_prop=0): """卖出股票 :param security: 股票代码 :param p...
跟踪joinquant对应的模拟交易,支持多用户多策略 :param users: 支持easytrader的用户对象,支持使用 [] 指定多个用户 :param strategies: joinquant 的模拟交易地址,支持使用 [] 指定多个模拟交易, 地址类似 https://www.joinquant.com/algorithm/live/index?backtestId=xxx :param track_interval: 轮训模拟交易时间,单位为秒 :param trade_cmd_expire_seconds: 交易指令过期时间,...
直接连接登陆后的客户端 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :return: def connect(self, exe_path=None, **kwargs): """ 直接连接登陆后的客户端 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :return: """...
市价买入 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} def market_buy(self, security, amo...
市价卖出 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} def market_sell(self, security, am...
市价交易 :param security: 六位证券代码 :param amount: 交易数量 :param ttype: 市价委托类型,默认客户端默认选择, 深市可选 ['对手方最优价格', '本方最优价格', '即时成交剩余撤销', '最优五档即时成交剩余 '全额成交或撤销'] 沪市可选 ['最优五档成交剩余撤销', '最优五档成交剩余转限价'] :return: {'entrust_no': '委托单号'} def market_trade(self, security, a...
根据选择的市价交易类型选择对应的下拉选项 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, ...
登陆客户端 :param config_path: 登陆配置文件,跟参数登陆方式二选一 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 r'C:\\htzqzyb2\\xiadan.exe', 默认 r'C:\\htzqzyb2\\xiadan.exe' :param comm_password: 通讯密码 :return: def prepare( self, config_path=None, user=No...
登陆客户端 :param user: 账号 :param password: 明文密码 :param exe_path: 客户端路径类似 'C:\\中国银河证券双子星3.2\\Binarystar.exe', 默认 'C:\\中国银河证券双子星3.2\\Binarystar.exe' :param comm_password: 通讯密码, 华泰需要,可不设 :return: def login(self, user, password, exe_path, comm_password=None, **kwargs): ...
用于生成特定的券商对象 :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 platform:平台支持 ['jq', 'joinquant', '聚宽’] :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一万, 总资金由 initial_assets * 组合当前净值 得出 :param total_assets: [雪球参数] 控制雪球总资金,无默认值, 若设置则覆盖 initial_assets :return the class of follower Usage:: >>> import easytrader >>> u...
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`. ...
Memory information in bytes Example: >>> print(ctx.device(0).memory()) {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L} Returns: total/used/free memory in bytes def memory(self): """Memory information in bytes Example: ...
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: >>>...
Get number of 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
Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device def device(self, idx): """Get a specific GPU device Args: idx: index of device Returns: NvidiaDevice: single GPU device """ ...
Download and extract the tarball from Alex's website. Copied from tensorflow example 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_clas...
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 def get_per_pixel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): the names ('train' or 't...
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. def get_per_channel_mean(self, names=('train', 'test')): """ Args: names (tuple[str]): th...
Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 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...
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): def maskrcnn_upXconv_head(feature, num_catego...
Args: names (tuple[str]): names of the dataset split Returns: a 32x32x3 image, the mean of all images in the given datasets def get_per_pixel_mean(names=('train', 'test', 'extra')): """ Args: names (tuple[str]): names of the dataset split Returns: ...
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: def build_or_reuse_placeholder(tensor_spec): """ Build a tf.placeholder from the metadata in the given tensor spec, or return an existin...
Returns: A list of :class:`tf.TensorSpec`, which describes the inputs of this model. The result is cached for each instance of :class:`ModelDescBase`. def get_input_signature(self): """ Returns: A list of :class:`tf.TensorSpec`, which describes the inputs of this mod...
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 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...
Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name and simple scalar value v. def create_scalar_summary(name, v): """ Args: name (str): v (float): scalar value Returns: tf.Summary: a tf.Summary object with name an...
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: def create_image_summary(name, val): """ Args: name(str): val(np.ndarray): 4D tensor of NHWC. assume RGB ...
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...
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...
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_...
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. ...
Args: proposals: BoxProposals stage: 0, 1, 2 Returns: FastRCNNHead Nx4, updated boxes def run_head(self, proposals, stage): """ Args: proposals: BoxProposals stage: 0, 1, 2 Returns: FastRCNNHead ...
Args: boxes: Nx4 Returns: BoxProposals 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_...
Returns: Nx#classx4 def decoded_output_boxes(self): """ Returns: Nx#classx4 """ ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
Returns: Nx#class 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 / s...
Visualize some intermediate results (proposals, raw predictions) inside the pipeline. 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 visualiz...
Args: name (str): the name of the layer, e.g. 'Conv2D' Returns: the wrapped layer function, or None if not registered. 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 registere...
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...
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...
Export trained model to use it in TensorFlow Serving or cloudML. 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=['inpu...
Export trained model to use it as a frozen and pruned inference graph in mobile applications. 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(mod...
Run inference from a training model checkpoint. 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']) p...
Run inference from a different graph, which receives encoded images buffers. 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=InferenceOnlyMode...
Run the pruned and frozen inference graph. 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(gra...
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...
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] def SelectComponent(ds, idxs): """ ...
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...
Args: cnt(int): the count of some event of interest. tot(int): the total number of events. 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 += tota...
Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size. def feed(self, pred, label): """ Args: pred (np.ndarray): binary array. label (np.ndarray): binary array of the same size. """ assert pred.shape == l...
Args: x (float or np.ndarray): must have the same shape. 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 ...
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...
Args: box: 4 float mask: MxM floats shape: h,w Returns: A uint8 binary image of hxw. 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 ...
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] def predict_...
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...
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...
Flatten the tensor except the first dimension. 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]))
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 def FullyConnected( inputs, units, activation=N...
Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll have workers that run on multiGPUs 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 tenso...
Fetch a batch of data without waiting 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]...
Same as in :meth:`AsyncPredictorBase.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
Args: buf: the output of `dumps`. 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, ...
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...
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...
return an image generated from z 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=BNR...
return a (b, 1) logits 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) ...
Args: boxes: nx4 floatbox Returns: n 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])
Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections def pairwise_intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: box...
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. def pairwise_iou(boxlist1, boxlist2): """Computes pairwise intersection-over-union between box collections....
:param path: path to the model :param start: a `str`. the starting characters :param length: a `int`. the length of text to generate 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 g...
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): """...