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


Python statistics.median方法代码示例

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


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

示例1: transpose_metrics

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def transpose_metrics():
    """ flatten data up to the timestamp"""
    for timestamp in track['current_dict'].keys():
        track['line_count'] += 1
        new_row = dict()
        new_row['timestamp'] = timestamp
        for key in track['current_dict'][timestamp]:
            value = track['current_dict'][timestamp][key]
            if '|' in value:
                value = statistics.median(map(lambda v: float(v), value.split('|')))
            new_row[key] = str(value)
        track['current_row'].append(new_row)


################################
# Functions to send data to IF #
################################ 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:19,代码来源:getlogs_k8s.py

示例2: transpose_metrics

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def transpose_metrics():
    """ flatten data up to the timestamp"""
    for timestamp in track['current_dict'].keys():
        logger.debug(timestamp)
        track['line_count'] += 1
        new_row = dict()
        new_row['timestamp'] = timestamp
        for key in track['current_dict'][timestamp]:
            value = track['current_dict'][timestamp][key]
            if '|' in value:
                value = statistics.median(map(lambda v: float(v), value.split('|')))
            new_row[key] = str(value)
        track['current_row'].append(new_row)


################################
# Functions to send data to IF #
################################ 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:20,代码来源:getmessages_prometheus.py

示例3: transpose_metrics

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def transpose_metrics():
    """ builds a flatten data up to the timestamp"""
    for timestamp in track['current_dict'].keys():
        new_row = dict()
        new_row['timestamp'] = timestamp
        for key in track['current_dict'][timestamp]:
            value = track['current_dict'][timestamp][key]
            if '|' in value:
                value = median(map(lambda v: int(v), value.split('|')))
            new_row[key] = str(value)
        track['current_row'].append(new_row)


################################
# Functions to send data to IF #
################################ 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:18,代码来源:getmetrics_zipkin.py

示例4: evaluate_and_update_max_score

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def evaluate_and_update_max_score(self, t, episodes):
        eval_stats = eval_performance(
            self.env, self.agent, self.n_steps, self.n_episodes,
            max_episode_len=self.max_episode_len,
            logger=self.logger)
        elapsed = time.time() - self.start_time
        custom_values = tuple(tup[1] for tup in self.agent.get_statistics())
        mean = eval_stats['mean']
        values = (t,
                  episodes,
                  elapsed,
                  mean,
                  eval_stats['median'],
                  eval_stats['stdev'],
                  eval_stats['max'],
                  eval_stats['min']) + custom_values
        record_stats(self.outdir, values)
        if mean > self.max_score:
            self.logger.info('The best score is updated %s -> %s',
                             self.max_score, mean)
            self.max_score = mean
            if self.save_best_so_far_agent:
                save_agent(self.agent, "best", self.outdir, self.logger)
        return mean 
开发者ID:chainer,项目名称:chainerrl,代码行数:26,代码来源:evaluator.py

示例5: eval_performance

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def eval_performance(process_idx, make_env, model, phi, n_runs):
    assert n_runs > 1, 'Computing stdev requires at least two runs'
    scores = []
    for i in range(n_runs):
        model.reset_state()
        env = make_env(process_idx, test=True)
        obs = env.reset()
        done = False
        test_r = 0
        while not done:
            s = chainer.Variable(np.expand_dims(phi(obs), 0))
            pout, _ = model.pi_and_v(s)
            a = pout.action_indices[0]
            obs, r, done, info = env.step(a)
            test_r += r
        scores.append(test_r)
        print('test_{}:'.format(i), test_r)
    mean = statistics.mean(scores)
    median = statistics.median(scores)
    stdev = statistics.stdev(scores)
    return mean, median, stdev 
开发者ID:muupan,项目名称:async-rl,代码行数:23,代码来源:run_a3c.py

示例6: eval_performance

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def eval_performance(rom, p_func, n_runs):
    assert n_runs > 1, 'Computing stdev requires at least two runs'
    scores = []
    for i in range(n_runs):
        env = ale.ALE(rom, treat_life_lost_as_terminal=False)
        test_r = 0
        while not env.is_terminal:
            s = chainer.Variable(np.expand_dims(dqn_phi(env.state), 0))
            pout = p_func(s)
            a = pout.action_indices[0]
            test_r += env.receive_action(a)
        scores.append(test_r)
        print('test_{}:'.format(i), test_r)
    mean = statistics.mean(scores)
    median = statistics.median(scores)
    stdev = statistics.stdev(scores)
    return mean, median, stdev 
开发者ID:muupan,项目名称:async-rl,代码行数:19,代码来源:a3c_ale.py

示例7: get_partitions_info_str

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def get_partitions_info_str(j):
    partitions = j['components']['partition_counts']['counts']
    partitions_info = {
                          'Partitions': len(partitions),
                          'Rows': sum(partitions),
                          'Empty partitions': len([p for p in partitions if p == 0])
                      }
    if partitions_info['Partitions'] > 1:
        partitions_info.update({
            'Min(rows/partition)': min(partitions),
            'Max(rows/partition)': max(partitions),
            'Median(rows/partition)': median(partitions),
            'Mean(rows/partition)': int(mean(partitions)),
            'StdDev(rows/partition)': int(stdev(partitions))
        })


    return "\n{}".format(IDENT).join(['{}: {}'.format(k, v) for k, v in partitions_info.items()]) 
开发者ID:Nealelab,项目名称:cloudtools,代码行数:20,代码来源:describe.py

示例8: get_center_ip_entities

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def get_center_ip_entities(
    ip_entities: Iterable[IpAddress], mode: str = "median"
) -> Tuple[float, float]:
    """
    Return the geographical center of the IP address locations.

    Parameters
    ----------
    ip_entities : Iterable[IpAddress]
        IpAddress entities with location information
    mode : str, optional
        The averaging method to us, by default "median".
        "median" and "mean" are the supported values.

    Returns
    -------
    Tuple[Union[int, float], Union[int, float]]
        Tuple of latitude, longitude

    """
    ip_locs_longs = _extract_locs_ip_entities(ip_entities)
    return get_center_geo_locs(ip_locs_longs, mode=mode) 
开发者ID:microsoft,项目名称:msticpy,代码行数:24,代码来源:foliummap.py

示例9: get_center_geo_locs

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def get_center_geo_locs(
    loc_entities: Iterable[GeoLocation], mode: str = "median"
) -> Tuple[float, float]:
    """
    Return the geographical center of the geo locations.

    Parameters
    ----------
    loc_entities : Iterable[GeoLocation]
        GeoLocation entities with location information
    mode : str, optional
        The averaging method to use, by default "median".
        "median" and "mean" are the supported values.

    Returns
    -------
    Tuple[Union[int, float], Union[int, float]]
        Tuple of latitude, longitude

    """
    lat_longs = _extract_coords_loc_entities(loc_entities)
    return _get_center_coords(lat_longs, mode=mode) 
开发者ID:microsoft,项目名称:msticpy,代码行数:24,代码来源:foliummap.py

示例10: _get_center_coords

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def _get_center_coords(
    locations: Iterable[Tuple[float, float]], mode: str = "median"
) -> Tuple[float, float]:
    """Return the center (median) of the coordinates."""
    if not locations:
        return 0, 0
    locs = list(locations)
    if mode == "median":
        try:
            return (
                stats.median([loc[0] for loc in locs if not math.isnan(loc[0])]),
                stats.median([loc[1] for loc in locs if not math.isnan(loc[1])]),
            )
        except stats.StatisticsError:
            pass
    return (
        stats.mean([loc[0] for loc in locs if not math.isnan(loc[0])]),
        stats.mean([loc[1] for loc in locs if not math.isnan(loc[1])]),
    ) 
开发者ID:microsoft,项目名称:msticpy,代码行数:21,代码来源:foliummap.py

示例11: get_mad_decision_frontier

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def get_mad_decision_frontier(values_array, trigger_sensitivity, trigger_on):
    """
    Compute median decision frontier

    :param values_array: list of values used to make the computation
    :param trigger_sensitivity: sensitivity
    :param trigger_on: high or low
    :return: the decision frontier
    """
    mad = np.nanmedian(np.absolute(values_array - np.nanmedian(values_array, 0)), 0)  # median absolute deviation

    if trigger_on == "high":
        decision_frontier = np.nanmedian(values_array) + trigger_sensitivity * mad

    elif trigger_on == "low":
        decision_frontier = np.nanmedian(values_array) - trigger_sensitivity * mad
    else:
        raise ValueError("Unexpected trigger condition " + trigger_on + ", could not calculate decision frontier")

    return decision_frontier 
开发者ID:NVISO-BE,项目名称:ee-outliers,代码行数:22,代码来源:utils.py

示例12: test_odd_number_repeated

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def test_odd_number_repeated(self):
        # Test median.grouped with repeated median values.
        data = [12, 13, 14, 14, 14, 15, 15]
        assert len(data)%2 == 1
        self.assertEqual(self.func(data), 14)
        #---
        data = [12, 13, 14, 14, 14, 14, 15]
        assert len(data)%2 == 1
        self.assertEqual(self.func(data), 13.875)
        #---
        data = [5, 10, 10, 15, 20, 20, 20, 20, 25, 25, 30]
        assert len(data)%2 == 1
        self.assertEqual(self.func(data, 5), 19.375)
        #---
        data = [16, 18, 18, 18, 18, 20, 20, 20, 22, 22, 22, 24, 24, 26, 28]
        assert len(data)%2 == 1
        self.assertApproxEqual(self.func(data, 2), 20.66666667, tol=1e-8) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_statistics.py

示例13: test_even_number_repeated

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def test_even_number_repeated(self):
        # Test median.grouped with repeated median values.
        data = [5, 10, 10, 15, 20, 20, 20, 25, 25, 30]
        assert len(data)%2 == 0
        self.assertApproxEqual(self.func(data, 5), 19.16666667, tol=1e-8)
        #---
        data = [2, 3, 4, 4, 4, 5]
        assert len(data)%2 == 0
        self.assertApproxEqual(self.func(data), 3.83333333, tol=1e-8)
        #---
        data = [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6]
        assert len(data)%2 == 0
        self.assertEqual(self.func(data), 4.5)
        #---
        data = [3, 4, 4, 4, 5, 5, 5, 5, 6, 6]
        assert len(data)%2 == 0
        self.assertEqual(self.func(data), 4.75) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:19,代码来源:test_statistics.py

示例14: run_users

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def run_users(url, payload, mnu, mxu):
    payload_len = len(payload)
    async with aiohttp.ClientSession() as session:
        for i in range(mnu, mxu + 1):
            tasks = []
            for _ in range(0, i):
                user_id = uuid.uuid4().hex
                tasks.append(asyncio.ensure_future(perform_test_dialogue(session, url, user_id, payload)))
            test_start_time = time()
            responses = await asyncio.gather(*tasks)
            test_time = time() - test_start_time
            times = []
            for resp in responses:
                times.extend(resp)

            print(f'test No {i} finished: {max(times)} {min(times)} {mean(times)} {median(times)} '
                  f'total_time {test_time} msgs {i*payload_len} mean_rps {(i*payload_len)/test_time}') 
开发者ID:deepmipt,项目名称:dp-agent,代码行数:19,代码来源:http_api_stress_test.py

示例15: evaluate_and_update_max_score

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import median [as 别名]
def evaluate_and_update_max_score(self, t, episodes):
        eval_stats = eval_performance(
            self.env, self.agent, self.n_runs,
            max_episode_len=self.max_episode_len, explorer=self.explorer,
            logger=self.logger)
        elapsed = time.time() - self.start_time
        custom_values = tuple(tup[1] for tup in self.agent.get_statistics())
        mean = eval_stats['mean']
        values = (t,
                  episodes,
                  elapsed,
                  mean,
                  eval_stats['median'],
                  eval_stats['stdev'],
                  eval_stats['max'],
                  eval_stats['min']) + custom_values
        record_stats(self.outdir, values)
        if mean > self.max_score:
            self.logger.info('The best score is updated %s -> %s',
                             self.max_score, mean)
            self.max_score = mean
            if self.save_best_so_far_agent:
                save_agent(self.agent, t, self.outdir, self.logger)
        return mean 
开发者ID:crowdAI,项目名称:marLo,代码行数:26,代码来源:evaluator.py


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