当前位置: 首页>>代码示例>>Python>>正文


Python six.viewkeys方法代码示例

本文整理汇总了Python中six.viewkeys方法的典型用法代码示例。如果您正苦于以下问题:Python six.viewkeys方法的具体用法?Python six.viewkeys怎么用?Python six.viewkeys使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在six的用法示例。


在下文中一共展示了six.viewkeys方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _linthompsamp_score

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def _linthompsamp_score(self, context):
        """Thompson Sampling"""
        action_ids = list(six.viewkeys(context))
        context_array = np.asarray([context[action_id]
                                    for action_id in action_ids])
        model = self._model_storage.get_model()
        B = model['B']  # pylint: disable=invalid-name
        mu_hat = model['mu_hat']
        v = self.R * np.sqrt(24 / self.epsilon
                             * self.context_dimension
                             * np.log(1 / self.delta))
        mu_tilde = self.random_state.multivariate_normal(
            mu_hat.flat, v**2 * np.linalg.inv(B))[..., np.newaxis]
        estimated_reward_array = context_array.dot(mu_hat)
        score_array = context_array.dot(mu_tilde)

        estimated_reward_dict = {}
        uncertainty_dict = {}
        score_dict = {}
        for action_id, estimated_reward, score in zip(
                action_ids, estimated_reward_array, score_array):
            estimated_reward_dict[action_id] = float(estimated_reward)
            score_dict[action_id] = float(score)
            uncertainty_dict[action_id] = float(score - estimated_reward)
        return estimated_reward_dict, uncertainty_dict, score_dict 
开发者ID:ntucllab,项目名称:striatum,代码行数:27,代码来源:linthompsamp.py

示例2: _do_update_cluster_template

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def _do_update_cluster_template(self, cluster_template_id, values):
        session = get_session()
        with session.begin():
            query = model_query(models.ClusterTemplate, session=session)
            query = add_identity_filter(query, cluster_template_id)
            try:
                ref = query.with_lockmode('update').one()
            except NoResultFound:
                raise exception.ClusterTemplateNotFound(
                    clustertemplate=cluster_template_id)

            if self._is_cluster_template_referenced(session, ref['uuid']):
                # NOTE(flwang): We only allow to update ClusterTemplate to be
                # public, hidden and rename
                if (not self._is_publishing_cluster_template(values) and
                        list(six.viewkeys(values)) != ["name"]):
                    raise exception.ClusterTemplateReferenced(
                        clustertemplate=cluster_template_id)

            ref.update(values)
        return ref 
开发者ID:openstack,项目名称:magnum,代码行数:23,代码来源:api.py

示例3: _is_thing_array

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def _is_thing_array(categories_json, ignored_label):
  """is_thing[category_id] is a bool on if category is "thing" or "stuff"."""
  is_thing_dict = {}
  for category_json in categories_json:
    is_thing_dict[category_json['id']] = bool(category_json['isthing'])

  # Check our assumption that the category ids are consecutive.
  # Usually metrics should be able to handle this case, but adding a warning
  # here.
  max_category_id = max(six.iterkeys(is_thing_dict))
  if len(is_thing_dict) != max_category_id + 1:
    seen_ids = six.viewkeys(is_thing_dict)
    all_ids = set(six.moves.range(max_category_id + 1))
    unseen_ids = all_ids.difference(seen_ids)
    if unseen_ids != {ignored_label}:
      logging.warning(
          'Nonconsecutive category ids or no category JSON specified for ids: '
          '%s', unseen_ids)

  is_thing_array = np.zeros(max_category_id + 1)
  for category_id, is_thing in six.iteritems(is_thing_dict):
    is_thing_array[category_id] = is_thing

  return is_thing_array 
开发者ID:IBM,项目名称:MAX-Image-Segmenter,代码行数:26,代码来源:eval_coco_format.py

示例4: test_blocked_lookup_symbol_query

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def test_blocked_lookup_symbol_query(self):
        # we will try to query for more variables than sqlite supports
        # to make sure we are properly chunking on the client side
        as_of = pd.Timestamp('2013-01-01', tz='UTC')
        # we need more sids than we can query from sqlite
        nsids = SQLITE_MAX_VARIABLE_NUMBER + 10
        sids = range(nsids)
        frame = pd.DataFrame.from_records(
            [
                {
                    'sid': sid,
                    'symbol':  'TEST.%d' % sid,
                    'start_date': as_of.value,
                    'end_date': as_of.value,
                    'exchange': uuid.uuid4().hex
                }
                for sid in sids
            ]
        )
        self.write_assets(equities=frame)
        assets = self.asset_finder.retrieve_equities(sids)
        assert_equal(viewkeys(assets), set(sids)) 
开发者ID:enigmampc,项目名称:catalyst,代码行数:24,代码来源:test_assets.py

示例5: assert_dict_equal

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def assert_dict_equal(result, expected, path=(), msg='', **kwargs):
    _check_sets(
        viewkeys(result),
        viewkeys(expected),
        msg,
        path + ('.%s()' % ('viewkeys' if PY2 else 'keys'),),
        'key',
    )

    failures = []
    for k, (resultv, expectedv) in iteritems(dzip_exact(result, expected)):
        try:
            assert_equal(
                resultv,
                expectedv,
                path=path + ('[%r]' % (k,),),
                msg=msg,
                **kwargs
            )
        except AssertionError as e:
            failures.append(str(e))

    if failures:
        raise AssertionError('\n'.join(failures)) 
开发者ID:enigmampc,项目名称:catalyst,代码行数:26,代码来源:predicates.py

示例6: this_is_okay

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def this_is_okay():
    d = {}
    iterkeys(d)
    six.iterkeys(d)
    six.itervalues(d)
    six.iteritems(d)
    six.iterlists(d)
    six.viewkeys(d)
    six.viewvalues(d)
    six.viewlists(d)
    itervalues(d)
    future.utils.iterkeys(d)
    future.utils.itervalues(d)
    future.utils.iteritems(d)
    future.utils.iterlists(d)
    future.utils.viewkeys(d)
    future.utils.viewvalues(d)
    future.utils.viewlists(d)
    six.next(d)
    builtins.next(d) 
开发者ID:PyCQA,项目名称:flake8-bugbear,代码行数:22,代码来源:b301_b302_b305.py

示例7: measure_dissymmetry

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def measure_dissymmetry(self, other):
        """Return measure of difference as a Dissymmetry."""
        other_ts_to_val = other.ts_to_val if other else {}
        all_ts_set = six.viewkeys(self.ts_to_val) | six.viewkeys(other_ts_to_val)

        if not all_ts_set:
            return None

        val_tuples = [
            (self.ts_to_val.get(ts), other_ts_to_val.get(ts)) for ts in all_ts_set
        ]
        diff_measures = [
            self._measure_relative_gap(val1, val2) for val1, val2 in val_tuples
        ]

        return Dissymmetry(self.name, diff_measures) 
开发者ID:criteo,项目名称:biggraphite,代码行数:18,代码来源:clusters_diff.py

示例8: frame

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def frame(cls, F, *tags):
        '''Iterate through each field containing the specified `tags` within the frame belonging to the function `ea`.'''
        global read, internal
        tags_ = { tag for tag in tags }

        for ofs, item in read.frame(F):
            field, type, comment = item

            # if the entire comment is in tags (like None) or no tags were specified, then save the entire member
            if not tags or comment in tags_:
                yield ofs, item
                continue

            # otherwise, decode the comment into a dictionary using only the tags the user asked for
            comment_ = internal.comment.decode(comment)
            res = { name : comment_[name] for name in six.viewkeys(comment_) & tags_ }

            # if anything was found, then re-encode it and yield to the user
            if res: yield ofs, (field, type, internal.comment.encode(res))
        return

    ## query the entire database for the specified tags 
开发者ID:arizvisa,项目名称:ida-minsc,代码行数:24,代码来源:tags.py

示例9: _gc

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def _gc(self):
        """Remove disconnected websocket handlers."""
        for directory in list(six.viewkeys(self.handlers)):
            handlers = [
                (pattern, handler, impl, sub_id)
                for pattern, handler, impl, sub_id in self.handlers[directory]
                if handler.active(sub_id=sub_id)
            ]

            _LOGGER.debug('Number of active handlers for %s: %s',
                          directory, len(handlers))

            if not handlers:
                _LOGGER.debug('No active handlers for %s', directory)
                self.handlers.pop(directory, None)
                if directory not in self.watch_dirs:
                    # Watch is not permanent, remove dir from watcher.
                    self.watcher.remove_dir(directory)
            else:
                self.handlers[directory] = handlers 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:22,代码来源:__init__.py

示例10: test_query_tag_intersection

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def test_query_tag_intersection(self, query, expected_keys):
    tasks = containers.TaggedTasks()

    # pylint: disable=unused-variable
    @tasks.add('a', 'b')
    def f1():
      pass

    @tasks.add('a', 'b', 'c')
    def f2():
      pass

    @tasks.add('a', 'c', 'd')
    def f3():
      pass
    # pylint: enable=unused-variable

    result = tasks.tagged(*query)
    self.assertSetEqual(frozenset(six.viewkeys(result)), expected_keys) 
开发者ID:deepmind,项目名称:dm_control,代码行数:21,代码来源:containers_test.py

示例11: tagged

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def tagged(self, *tags):
    """Returns a (possibly empty) dict of functions matching all the given tags.

    Args:
      *tags: Strings specifying tags to query by.

    Returns:
      A dict of `{name: function}` containing all the functions that are tagged
      by all of the strings in `tags`.
    """
    if not tags:
      return {}
    tags = set(tags)
    if not tags.issubset(six.viewkeys(self._tags)):
      return {}
    names = six.viewkeys(self._tags[tags.pop()])
    while tags:
      names &= six.viewkeys(self._tags[tags.pop()])
    return {name: self._tasks[name] for name in names} 
开发者ID:deepmind,项目名称:dm_control,代码行数:21,代码来源:containers.py

示例12: viewflatkeys

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def viewflatkeys(self):
        ''' Return view of flattened keys '''
        return six.viewkeys(self.flattened()) 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:5,代码来源:xdict.py

示例13: _exp4p_score

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def _exp4p_score(self, context):
        """The main part of Exp4.P.
        """
        advisor_ids = list(six.viewkeys(context))

        w = self._modelstorage.get_model()['w']
        if len(w) == 0:
            for i in advisor_ids:
                w[i] = 1
        w_sum = sum(six.viewvalues(w))

        action_probs_list = []
        for action_id in self.action_ids:
            weighted_exp = [w[advisor_id] * context[advisor_id][action_id]
                            for advisor_id in advisor_ids]
            prob_vector = np.sum(weighted_exp) / w_sum
            action_probs_list.append((1 - self.n_actions * self.p_min)
                                     * prob_vector
                                     + self.p_min)
        action_probs_list = np.asarray(action_probs_list)
        action_probs_list /= action_probs_list.sum()

        estimated_reward = {}
        uncertainty = {}
        score = {}
        for action_id, action_prob in zip(self.action_ids, action_probs_list):
            estimated_reward[action_id] = action_prob
            uncertainty[action_id] = 0
            score[action_id] = action_prob
        self._modelstorage.save_model(
            {'action_probs': estimated_reward, 'w': w})

        return estimated_reward, uncertainty, score 
开发者ID:ntucllab,项目名称:striatum,代码行数:35,代码来源:exp4p.py

示例14: reward

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def reward(self, history_id, rewards):
        """Reward the previous action with reward.

        Parameters
        ----------
        history_id : int
            The history id of the action to reward.

        rewards : dictionary
            The dictionary {action_id, reward}, where reward is a float.
        """
        context = (self._historystorage
                   .get_unrewarded_history(history_id)
                   .context)

        model = self._modelstorage.get_model()
        w = model['w']
        action_probs = model['action_probs']
        action_ids = list(six.viewkeys(six.next(six.itervalues(context))))

        # Update the model
        for action_id, reward in six.viewitems(rewards):
            y_hat = {}
            v_hat = {}
            for i in six.viewkeys(context):
                y_hat[i] = (context[i][action_id] * reward
                            / action_probs[action_id])
                v_hat[i] = sum(
                    [context[i][k] / action_probs[k] for k in action_ids])
                w[i] = w[i] * np.exp(
                    self.p_min / 2
                    * (y_hat[i] + v_hat[i]
                       * np.sqrt(np.log(len(context) / self.delta)
                                 / (len(action_ids) * self.max_rounds))))

        self._modelstorage.save_model({
            'action_probs': action_probs, 'w': w})

        # Update the history
        self._historystorage.add_reward(history_id, rewards) 
开发者ID:ntucllab,项目名称:striatum,代码行数:42,代码来源:exp4p.py

示例15: iterids

# 需要导入模块: import six [as 别名]
# 或者: from six import viewkeys [as 别名]
def iterids(self):
        r"""Return iterable of the Action ids.

        Returns
        -------
        action_ids: iterable
            Action ids.
        """
        return six.viewkeys(self._actions) 
开发者ID:ntucllab,项目名称:striatum,代码行数:11,代码来源:action.py


注:本文中的six.viewkeys方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。