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


Python statistics.mean方法代码示例

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


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

示例1: evaluate_and_update_max_score

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [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

示例2: aggregate_vote

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def aggregate_vote(evaluations):
    """Return the consensus evaluation given a an iterable of evaluations, or None if no evaluations.

    Calculated as (1) whether or not the evidence is applicable, and (2) if the evidence is applicable, how consistent
    the evidence is with the hypothesis. The calculation is conservative, rounding the result toward Eval.neutral
    if there is a tie.
    """
    na_it, rated_it = partition(Eval.not_applicable.__ne__, evaluations)
    na_votes = list(na_it)
    rated_votes = list(rated_it)

    if not na_votes and not rated_votes:
        return None
    elif len(na_votes) > len(rated_votes):
        return Eval.not_applicable
    else:
        consensus = round(statistics.mean([v.value for v in rated_votes]))
        return Eval(round(consensus)) 
开发者ID:twschiller,项目名称:open-synthesis,代码行数:20,代码来源:metrics.py

示例3: _random

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def _random(self, env, min_mean, max_mean, min_stdev, max_stdev,
                test_count=3, sample_count=300):
        mmin, smin, mmax, smax = 100, 100, 0, 0
        for i in range(test_count):
            values = [env(0) for i in range(sample_count)]
            mean, stdev = statistics.mean(values), statistics.stdev(values)
            mmax = max(mmax, mean)
            mmin = min(mmin, mean)
            smax = max(smax, stdev)
            smin = min(smin, stdev)

        self.assertGreater(mmin, min_mean)
        self.assertLess(mmax, max_mean)
        self.assertGreater(smin, min_stdev)
        self.assertLess(smax, max_stdev)

        return mmin, mmax, smin, smax 
开发者ID:ManiacalLabs,项目名称:BiblioPixel,代码行数:19,代码来源:envelope_test.py

示例4: update_first_half_time_difference_mean

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def update_first_half_time_difference_mean(timestamp_differences):
    """
    First half time difference mean update.

    Input:  - timestamp_differences: The list of all action timestamp differences.

    Output: - first_half_time_difference_mean: The first half time difference mean.
    """
    half_index = len(timestamp_differences)//2
    first_half = timestamp_differences[:half_index]

    if len(first_half) == 0:
        first_half_time_difference_mean = 0.0
    else:
        first_half_time_difference_mean = statistics.mean(first_half)

    return first_half_time_difference_mean 
开发者ID:MKLab-ITI,项目名称:news-popularity-prediction,代码行数:19,代码来源:temporal.py

示例5: eval_performance

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [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 mean [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: r_squared

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def r_squared(pred, res):
    """
    Calculating the R² score of this model.
    Value returned is between 0.0 and 1.0, the higher the better.
    :param pred: List<Int>
    :param res:  List<Int>
    :return: Float
    """
    ss_t = 0
    ss_r = 0

    for i in range(len(pred)):
        ss_t += (res[i] - statistics.mean(res)) ** 2
        ss_r += (res[i] - pred[i]) ** 2

    return 1 - (ss_r / ss_t) 
开发者ID:HoussemCharf,项目名称:FunUtils,代码行数:18,代码来源:linear_regression.py

示例8: get_partitions_info_str

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [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

示例9: get_default_value

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def get_default_value(downloads):
    """Find the default value (one day's worth of downloads) for a given input

    Parameters
    ----------
    downloads : dict
        A dict of dates and downloads on that day

    Returns
    -------
    default_value : int
        The default value, which is the average of the last 7 days of downloads
        that are contained in the input dictionary.
    """
    last_7_keys = sorted(downloads.keys())[-7:]
    default_value = int(mean([downloads[key] for key in last_7_keys]))
    return default_value


# Used to calculate downloads for the last week 
开发者ID:alkaline-ml,项目名称:pmdarima,代码行数:22,代码来源:downloads_badges.py

示例10: get_center_ip_entities

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [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

示例11: get_center_geo_locs

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [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

示例12: _get_center_coords

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [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

示例13: test_decision_frontier_pct_of_avg_value

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def test_decision_frontier_pct_of_avg_value(self):
        import logging as base_logging
        base_logging.disable(base_logging.NOTSET)

        for values_array in list_values_array:
            mean_values_array = mean(values_array)
            for sensitivity in list_sensitivity:

                expected_res = np.float64(mean_values_array * (sensitivity / 100))
                if expected_res < 0:
                    with self.assertLogs(logging.logger, level='DEBUG'):
                        res = helpers.utils.get_decision_frontier("pct_of_avg_value", values_array, sensitivity)
                else:
                    res = helpers.utils.get_decision_frontier("pct_of_avg_value", values_array, sensitivity)
                self.assertEqual(res, expected_res)

        base_logging.disable(base_logging.CRITICAL) 
开发者ID:NVISO-BE,项目名称:ee-outliers,代码行数:19,代码来源:test_utils.py

示例14: __init__

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def __init__(self, gdf, spatial_weights, unique_id):
        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]
        # define empty list for results
        results_list = []

        data = gdf.set_index(unique_id).geometry

        # iterating over rows one by one
        for index, geom in tqdm(data.iteritems(), total=data.shape[0]):
            if index in spatial_weights.neighbors.keys():
                neighbours = spatial_weights.neighbors[index]
                building_neighbours = data.loc[neighbours]
                if len(building_neighbours) > 0:
                    results_list.append(
                        building_neighbours.geometry.distance(geom).mean()
                    )
                else:
                    results_list.append(np.nan)
            else:
                results_list.append(np.nan)

        self.series = pd.Series(results_list, index=gdf.index) 
开发者ID:martinfleis,项目名称:momepy,代码行数:26,代码来源:distribution.py

示例15: prepare_plots

# 需要导入模块: import statistics [as 别名]
# 或者: from statistics import mean [as 别名]
def prepare_plots():
    fig, axarr = plt.subplots(2, sharex=True)
    fig.canvas.set_window_title('EVOLUTIONARY PROGRESS')
    fig.subplots_adjust(hspace = 0.5)
    axarr[0].set_title('error', fontsize=14)
    axarr[1].set_title('mean size', fontsize=14)
    plt.xlabel('generation', fontsize=18)
    plt.ion() # interactive mode for plot
    axarr[0].set_xlim(0, GENERATIONS)
    axarr[0].set_ylim(0, 1) # fitness range
    xdata = []
    ydata = [ [], [] ]
    line = [None, None]
    line[0], = axarr[0].plot(xdata, ydata[0], 'b-') # 'b-' = blue line    
    line[1], = axarr[1].plot(xdata, ydata[1], 'r-') # 'r-' = red line
    return axarr, line, xdata, ydata 
开发者ID:moshesipper,项目名称:tiny_gp,代码行数:18,代码来源:tiny_gp_plus.py


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