• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python statistics.stdev函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _aggregate

    def _aggregate(self):
        if not self._modified:
            return
        
        functions = defaultdict(lambda: defaultdict(list))
        for profile in filter(self._validate_profile, self._profiles.values()):
            for function, values in profile["functions"].items():
                functions[function]["num_calls"].append(values["num_calls"])
                functions[function]["total_time"].append(values["total_time"])
                functions[function]["cum_time"].append(values["cum_time"])

        for function, lists in functions.items():
            self._results[function] = Aggregator.Result(
                num_calls_median = int(median(lists["num_calls"])),
                total_time_mean = mean(lists["total_time"]),
                total_time_stdev = stdev(lists["total_time"]),
                cum_time_mean = mean(lists["cum_time"]),
                cum_time_stdev = stdev(lists["cum_time"]))
        
        run_times = lambda: (p["run_time"] for p in self._profiles.values())
        self._summary = Aggregator.Summary(
            run_time_mean = mean(run_times()),
            run_time_stdev = stdev(run_times()))

        self._modified = False
开发者ID:c4fcm,项目名称:CivilServant,代码行数:25,代码来源:perftest.py


示例2: csv_dict_reader

def csv_dict_reader(file_obj):
    """
    Read a CSV file using csv.DictReader
    """
    reader = csv.DictReader(file_obj, delimiter=',')
    num_likes = []
    num_comments = []
    num_shares = []
    for line in reader:
        p = int(line["num_likes"])
        q = int(line["first_page_comment"])
        r = int(line["comments_beyond_pageone"])
        num_likes.append(p)
        num_comments.append(q)
        num_shares.append(r)
    mean_num_likes = statistics.mean(num_likes)
    stdev_num_likes = statistics.stdev(num_likes)
    mean_num_comments = statistics.mean(num_comments)
    stdev_num_comments = statistics.stdev(num_comments)
    mean_num_shares = statistics.mean(num_shares)
    stdev_num_shares = statistics.stdev(num_shares)
    covariance_likes = stdev_num_likes / mean_num_likes
    covariance_comments = stdev_num_comments / mean_num_comments
    covariance_shares = stdev_num_shares / mean_num_shares
    w = csv.writer(open("svm_dataset.csv","a"),delimiter=',',quoting=csv.QUOTE_ALL)
    
    w.writerow([mean_num_likes,stdev_num_likes,covariance_likes,mean_num_comments,stdev_num_comments,covariance_comments,mean_num_shares,stdev_num_shares,covariance_shares])
开发者ID:envious777,项目名称:Brand-Valuation-using-Social-Media-Data,代码行数:27,代码来源:save.py


示例3: process_result

	def process_result(self, t_frame, r_frame):
		print(t_frame, r_frame) 
		
		try:
			stat_const = float(2.776)

			res2 = [] # frame transmission 
			res3 = [] # throughput 
			for i in range(int(self.T[0])):
				# frame transmission
				res2.append(t_frame[i]/r_frame[i])
				res3.append(self.F * r_frame[i] / self.R)

			# print(res2, res3)

			avg_res2 = statistics.mean(res2)
			sd2 = statistics.stdev(res2)
			dif2 = sd2/math.sqrt(int(self.T[0]))*stat_const
			upper_bound2 = avg_res2 + dif2 
			lower_bound2 = avg_res2 - dif2 

			avg_res3 = statistics.mean(res3)
			sd3 = statistics.stdev(res3)
			dif3 = sd3/math.sqrt(int(self.T[0]))*stat_const
			upper_bound3 = avg_res3 + dif3
			lower_bound3 = avg_res3 - dif3 

		except ZeroDivisionError: 
			return float("inf"), float("inf"), float("inf"), 0, 0, 0

		return avg_res2, lower_bound2, upper_bound2, avg_res3, lower_bound3, upper_bound3 
开发者ID:Hank-TNguyen,项目名称:W16,代码行数:31,代码来源:Simulation.py


示例4: good_stdev

    def good_stdev(self, current_offer):
        if self.counter < 5:
            return False

        # array of utilities the opponent would get for their offer
        past_utils = [self.utility_for(x) for x in self.opponent_offers]
        old_stdev = statistics.stdev(past_utils)
        old_mean = statistics.mean(past_utils)

        if past_utils[-1] < self.penalty:
            return False

        new_utils = []
        # filter outliers (2 standard deviations above or below)
        for u in past_utils:
            if old_mean - 2*old_stdev < u < old_mean + 2*old_stdev:
               new_utils.append(u)

        if len(new_utils) < 2:
            return False

        # if the utility we get for the offer is greater than the mean + 1 std dev, then return True
        offer_utility = self.utility_for(current_offer)
        new_stdev = statistics.stdev(new_utils)
        new_mean = statistics.mean(new_utils)
        return offer_utility > new_mean + new_stdev
开发者ID:nealp9084,项目名称:hw3,代码行数:26,代码来源:door_in_face_negotiator.py


示例5: pCalc

def pCalc (movMat, movNumber, n, reviewers):
      
    xVals = [int(x) for i,x in enumerate(movMat[movNumber][1].split(';')) if i in reviewers]
    yVals = [int(x) for i,x in enumerate(movMat[n][1].split(';')) if i in reviewers]
    
    xi = sum(xVals) #get first movie values
    average1 = xi/len(reviewers)
    stdDev1 = statistics.stdev(xVals)
  
    yi = sum(yVals) #get second movie values
    average2 = yi/len(yVals)
    stdDev2 = statistics.stdev(yVals)

    r = 0 		#get r value
    newSum = [((x - average1) / stdDev1) * ((y-average2)/stdDev2) for x,y in zip(xVals, yVals)]
    r = (1/(len(reviewers)-1))*sum(newSum)    
    
    review = []		#append all values to the list
    review.append(r)
    review.append(average1)
    review.append(average2)
    review.append(stdDev1)
    review.append(stdDev2)
    review.append(n)
    review.append(len(reviewers))
         
    return review 
开发者ID:VoR0220,项目名称:Artificial-Intelligence-Python,代码行数:27,代码来源:hw4.py


示例6: run_simulation

def run_simulation(init_duration, init_stake, samples, player):
    """ Run simulation, print the result to stdout

    """
    wheel = create_wheel()
    table = Table(wheel)
    game = RouletteGame(wheel, table)
    simulator = Simulator(game, player,
                          init_duration=init_duration, samples=samples,
                          init_stake=init_stake)
    simulator.gather()
    durations = simulator.durations
    maxima = simulator.maxima
    print(player)
    print()
    print("Durations")
    print("  min :", min(durations))
    print("  max :", max(durations))
    print("  mean: %.2f" % statistics.mean(durations))
    print("  dev : %.2f" % statistics.stdev(durations))
    print("Maxima")
    print("  min :", min(maxima))
    print("  max :", max(maxima))
    print("  mean: %.2f" % statistics.mean(maxima))
    print("  dev : %.2f" % statistics.stdev(maxima))
开发者ID:yannicklm,项目名称:pyroulette,代码行数:25,代码来源:simulator.py


示例7: replacePearsonPvalueWithZscore

def replacePearsonPvalueWithZscore():
    all_sample_data={}
    for tissue in tissue_comparison_scores:
        for (r,p,sample) in tissue_comparison_scores[tissue]:
            all_sample_data[sample] = [] ### populate this dictionary and create sub-dictionaries
        break

    for tissue in tissue_comparison_scores:
        for (r,p,sample) in tissue_comparison_scores[tissue]:
            all_sample_data[sample].append(r)

    sample_stats={}
    all_dataset_rho_values=[]
    ### Get average and standard deviation for all sample rho's
    for sample in all_sample_data:
        all_dataset_rho_values+=all_sample_data[sample]
        avg=statistics.avg(all_sample_data[sample])
        stdev=statistics.stdev(all_sample_data[sample])
        sample_stats[sample]=avg,stdev
    
    global_rho_avg = statistics.avg(all_dataset_rho_values)
    global_rho_stdev = statistics.stdev(all_dataset_rho_values)
    
    ### Replace the p-value for each rho
    for tissue in tissue_comparison_scores:
        scores = []
        for (r,p,sample) in tissue_comparison_scores[tissue]:
            #u,s=sample_stats[sample]
            #z = (r-u)/s
            z = (r-global_rho_avg)/global_rho_stdev ### Instead of doing this for the sample background, do it relative to all analyzed samples
            scores.append([r,z,sample])
        tissue_comparison_scores[tissue] = scores
开发者ID:wuxue,项目名称:altanalyze,代码行数:32,代码来源:LineageProfiler.py


示例8: calc_evalmetrics

    def calc_evalmetrics(self):
        """Calculate evaluation metrics: 
           Tour Recall, Tour Precision, Tour F1-score, RMSE of POI visit duration
           Tour Popularity, Tour Interest, Popularity and Interest Rank
        """
        assert(len(self.recommendSeqs) > 0)

        # calculate intersection size of recommended POI set and real POI set
        intersize = dict()
        for k, v in self.recommendSeqs.items():
            intersize[k] = len(set(v) & set(self.sequences[k]))

        # calculate tour recall
        recalls = []
        for k, v in intersize.items():
            recalls.append(v / len(self.sequences[k]))

        # calculate tour precision
        precisions = []
        for k, v in intersize.items():
            precisions.append(v / len(self.recommendSeqs[k]))

        # calculate F1-score
        f1scores = []
        assert(len(recalls) == len(precisions))
        for i in range(len(recalls)):
            f1scores.append(2 * precisions[i] * recalls[i] / (precisions[i] + recalls[i]))

        print('Recall:   ', stat.mean(recalls),    stat.stdev(recalls))
        print('Precision:', stat.mean(precisions), stat.stdev(precisions))
        print('F1-score: ', stat.mean(f1scores),   stat.stdev(f1scores))
开发者ID:gitter-badger,项目名称:digbeta,代码行数:31,代码来源:ijcai15.py


示例9: mean_dev

def mean_dev(training_set):
    '''
    Calculates and returns the mean and standard deviation to the classes yes and no of a given training set
    '''
    class_yes = []
    class_no = []
    mean_yes = {}
    mean_no = {}
    dev_yes = {}
    dev_no = {}
    for key in training_set[0]:
        for i in range(len(training_set)):
            if training_set[i]['DiabetesClass'] == 'yes':
                class_yes.append(training_set[i][key])
            else:
                class_no.append(training_set[i][key])
        if not key == 'DiabetesClass':
            mean_yes[key] = statistics.mean(class_yes)
            mean_no[key] = statistics.mean(class_no)
            dev_yes[key] = statistics.stdev(class_yes)
            dev_no[key] = statistics.stdev(class_no)
        else:
            prob_yes = float(len(class_yes) / len(training_set))
            prob_no = float(len(class_no) / len(training_set))
        class_yes = []
        class_no = []
    return mean_yes, mean_no, dev_yes, dev_no, prob_yes, prob_no
开发者ID:pedrotst,项目名称:trab1-ai,代码行数:27,代码来源:old_main.py


示例10: bootstrap_test

    def bootstrap_test(self, nsamples=100, noise=0.2):
        """Returns mean and std. dev. of successful recognitions."""
        boot = {}
        for vec, pat in zip(self.pattern_vectors, self.patterns):
            boot[pat] = {"closest": [], "iterations": [], "full_matches": [], "accuracy": []}
            for sample in range(nsamples):
                recalled, noisy, iterations = self.recall_noisy(vec, noise=noise)
                self.show_pattern(noisy, "{}_{}_noisy_{}".format(
                    noise, pat, sample))
                self.show_pattern(recalled,      "{}_{}_recalled_{}".format(
                    noise, pat, sample))

                # equal to any patterns?
                matches = {}
                full_match = None
                for vec2, pat2 in zip(self.pattern_vectors, self.patterns):
                    matches[pat2] = list( \
                            vec2[0] == recalled[0]).count(True)
                    if matches[pat2] == vec2.size:
                        full_match = pat2

                boot[pat]["iterations"].append(iterations)
                boot[pat]["full_matches"].append(full_match)
                boot[pat]["closest"].append(pat == max(matches, key=matches.get))
                boot[pat]["accuracy"].append(matches[pat] / vec.size)
            boot[pat]["iterations"] = (mean(boot[pat]["iterations"]), stdev(boot[pat]["iterations"]))
            boot[pat]["accuracy"] = (mean(boot[pat]["accuracy"]), stdev(boot[pat]["accuracy"]))

            count_matches = lambda l: len(list(filter(lambda f: not f is None, l)))

            boot[pat]["full_matches"] = count_matches(boot[pat]["full_matches"])
            boot[pat]["closest"] = count_matches(boot[pat]["closest"])
        return boot
开发者ID:hucal,项目名称:hopfield_tests,代码行数:33,代码来源:tests.py


示例11: addDataToPlt

def addDataToPlt(fig, ax, dates, diff, c = 'c', label="raw", isMultiple=True):
    assert len(dates) == len(diff), "Plot and data are of different lenght"
    label1 = "average of 3"
    label2 = "average of 7"

    med3 = [i for i in diff]
    med7 = [i for i in diff]
    for i in range(3, len(diff) - 4):
        if i > 2 and i < len(diff) - 4:
            med7[i] = stats.median(diff[i-3:i+3])
        if i > 0 and i < len(diff) - 2:
            med3[i] = stats.median(diff[i-1:i+2])
        
    marker = "o"
    if len(diff) > 200:
        marker = "."
    if not isMultiple:
        if len(diff) > 1 and stats.stdev(diff) > 0.1:
            logger.error("Why do you have a high stdev?" + str(stats.stdev(diff)))
            marker = "x"

    ax.plot_date(dates, diff, c, xdate=True, marker = marker, linestyle="", label=label)
    if isMultiple:
        ax.plot_date(dates, med3, 'b', xdate=True, marker = ".", linestyle="", label=label1)
        ax.plot_date(dates, med7, 'r', xdate=True, marker = ".", linestyle="", label=label2)
    ax.xaxis.set_major_locator(matplotlib.dates.HourLocator())
    ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:00"))
    ax.xaxis.set_minor_locator(matplotlib.dates.MinuteLocator())
    ax.autoscale_view()
    fig.autofmt_xdate()
    ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
开发者ID:nibrivia,项目名称:atlas,代码行数:31,代码来源:graph.py


示例12: model_analysis

def model_analysis(x, x_matrix, y, line, y_hat, b):
    n = len(x) # number of samples
    s_x = stats.stdev(x) # standard deviation of x values
    s_y = stats.stdev(y) # standard deviation of y values
    s2_x = stats.variance(x) # variance of x values
    s2_y = stats.variance(y) # variance of y values
    s_xy = b * s2_x # covariance of VM
    
    mad_temp = 0
    SSE = 0
    for i in range(len(y)):
        temp = abs(y[i] - y_hat[i])
        mad_temp += temp
        SSE += temp**2 # sum of squares for error
    MAD = mad_temp / n    
    s_err = math.sqrt(SSE / (n - 2)) # standard error of estimate
    s_b = s_err / math.sqrt((n - 1) * s2_x)
    
    r = s_xy / (s_x * s_y) # sample coefficient of correlation
    R_2 = line.score(x_matrix, y) # coefficient of determination 
    R_2calc = s_xy**2 / (s2_x * s2_y)
    t = b / s_b # t-value for slope assuming true slope = 0
    
    f1.write('\nSkew = ' + str(b) + '\n')
    f1.write('Coefficient of correlation (r) = ' + str(r) + '\n')
    #f1.write('Coefficient of determination (R^2) via scikit = ' + str(R_2) + '\n')
    f1.write('Coefficient of determination (R^2) calculate = ' + str(R_2calc) + '\n')
    f1.write('Test statistic for clock skew (t) = ' + str(t) + '\n')
    f1.write('Mean Absolute Deviation (MAD) = ' + str(MAD) + '\n')
    f1.write('Sum of Squares for Forecast Error (SSE) = ' + str(SSE) + '\n')
    
    return
开发者ID:cjwasek,项目名称:Traffic-Analysis-Project,代码行数:32,代码来源:SingleVM_Anal_v2.py


示例13: main

def main(y):
    print("Give me",y,"numbers")
    r = int(input())
    numbers =[]
    while len(numbers) < y:
        numbers.append(r)
        if len(numbers) < y:
            r = int(input("Give me another number"))
    print (numbers)
    #sum of the 10 numbers
    def function(x):
        name = x
        var = 0
        for i in numbers:
            var += i
        result = var/len(numbers)
        if name == 1:
            return var
        else:
            return result
    #Paul´s blog idea -->https://pololarinette.wordpress.com/2015/10/15/wsq10-lists/
    #Standar deviation
    import statistics
    statistics.stdev(numbers)

    print("The sum of the",y,"numbers is",function(1))
    print("The average of the",y,"numbers is",function(2))
    print("The stardart deviation is",statistics.stdev(numbers))
开发者ID:Jocapear,项目名称:TC1014,代码行数:28,代码来源:WSQ10.py


示例14: cmp

    def cmp(tweet1_counts1, tweet2_counts2):
        (tweet1, counts1) = tweet1_counts1
        (tweet2, counts2) = tweet2_counts2

        "1. Из твитов с разным количеством элементов списков более информативен тот, в котором элементов больше"
        if sum(counts1) > sum(counts2):
            return -1
        elif sum(counts2) > sum(counts1):
            return 1

        """
        2. Из твитов с одинаковой суммой количеств элементов список выбираем тот, где количества элементов более
        сбалансированы (например, [1, 1] лучше, чем [2, 0])
        """
        std1 = statistics.stdev(counts1)
        std2 = statistics.stdev(counts2)
        if std1 < std2:
            return -1
        elif std2 < std1:
            return 1

        "И, наконец, наиболее информативен твит большей длины"
        if len(tweet1) > len(tweet2):
            return -1
        elif len(tweet2) > len(tweet1):
            return 1

        return 0
开发者ID:themylogin,项目名称:twitter-overkill,代码行数:28,代码来源:utils.py


示例15: bench_throughput_latency

def bench_throughput_latency(samples=3, max_rsd=0.1,
                             *args, **kwargs):
    while True:
        throughputs = []
        latencies = []
        iteration = 1
        errors = 0
        while iteration <= samples:
            sys.stdout.write(' [*] Iteration %d/%d\r' % (iteration,samples))
            sys.stdout.flush()
            try:
                bench = Benchmark(*args, **kwargs)
                bench.run()
                throughputs.append(bench.throughput)
                latencies.append(bench.latency)
                iteration += 1
            except Exception as e:
                errors += 1
                if errors >= samples:
                    raise
                print(' [!] Iteration %d failed: %s\n%s' % \
                    (iteration, str(type(e)), str(e)))
        mean_throughput = statistics.mean(throughputs)
        mean_latency = statistics.mean(latencies)
        stdev_throughput = statistics.stdev(throughputs)
        stdev_latency = statistics.stdev(latencies)
        rsd_throughput = stdev_throughput/mean_throughput
        rsd_latency = stdev_latency/mean_latency
        if rsd_throughput > max_rsd or rsd_latency > max_rsd:
            sys.stderr.write(' [!] Discarding experiment: '+\
                'throughput RSD %.2f %%, latency RSD %.2f %%\n' %\
                (rsd_throughput*100, rsd_latency*100))
            continue
        return (mean_throughput, mean_latency,
            rsd_throughput, rsd_latency)
开发者ID:mtth-bfft,项目名称:muslkl,代码行数:35,代码来源:bench_memcached_throughput_latency.py


示例16: extract_results

def extract_results(input, out):
    header = ['fft_type', 'n_threads', 'n_points', 'n_iterations',
              'Throughput', 'Stdev']
    records = []
    for dirs, subdirs, files in os.walk(input):
        for file in files:
            if ('.stderr' not in file):
                continue
            l = []
            threads = string_between(file, 'n_thr', '.')
            points = string_between(file, 'n_p', 'n_i')
            iters = string_between(file, 'n_i', 'n_thr')
            exe = string_between(file, '', '-bench')
            #implementation = dirs.split('/')[-2]
            for line in open(os.path.join(dirs, file), 'r'):
                if 'Throughput' in line:
                    temp = string_between(line, ':', 'M')
                    l.append(float(temp.strip()))
            if l:
                records.append([exe, threads, points, iters,
                                stat.mean(l), stat.stdev(l)])
                print file
                percent = 100.0 * stat.stdev(l) / stat.mean(l)
                if percent > 10:
                    print "The previous file has %.2f %% error" % percent
            else:
                print "I found an empty file called %s" % file
    records.sort(key=lambda a: (a[0], int(a[1]), int(a[2]), int(a[3])))
    t = PrettyTable(header)
    t.align = 'l'
    t.border = False
    for r in records:
        t.add_row(r)
    with open(out, 'w') as f:
        f.writelines(str(t) + '\n')
开发者ID:kiliakis,项目名称:cpp-benchmark,代码行数:35,代码来源:extract-throughput.py


示例17: test

def test():
    n = [random.random() for _ in range(20)]
    bag = Bag()
    for i in n:
        bag.add(i)
    print(bag)
    for i in bag:
        print(i)

    total = 0
    for item in bag:
        total += item
    mean = total / bag.size()

    total = 0
    for item in bag:
        total += (item - mean)**2
    std = math.sqrt(total / (bag.size() - 1))

    print('calculated mean is {}'.format(mean))
    print('calculated stdev is {}'.format(std))

    print('stdlib mean is {}'.format(statistics.mean(n)))
    print('stdlib stdev is {}'.format(statistics.stdev(n)))

    assert(round(mean, 10) == round(statistics.mean(n), 10))
    assert(round(std, 10) == round(statistics.stdev(n), 10))
开发者ID:alekseyrybalkin,项目名称:cs-again,代码行数:27,代码来源:bag.py


示例18: main

def main(total_rolls=20000):
    rolls_list = rolls(total_rolls, 1, 6)
    sliced_sum20 = sliced_sums(20, rolls_list)
    sums20 = sums(sliced_sum20, -20)
    roll_count20 = lens(sliced_sum20)
    sliced_sum10k = sliced_sums(10000, rolls_list)
    sums10k = sums(sliced_sum10k, -10000)
    roll_count10k = lens(sliced_sum10k)
    paired_sums = [(20, sums20), (10000, sums10k)]
    paired_rolls = [(20, roll_count20), (10000, roll_count10k)]

    answers("Mean of the sum - {0} when M is {0}:",
            paired_sums, lambda s: statistics.mean(s))
    answers("Mean of the number of rolls when M is {0}:",
            paired_rolls, lambda s: statistics.mean(s))
    answers("Standard deviation of the sum - {0} when M is {0}:",
            paired_sums, lambda s: statistics.stdev(s))
    answers("Standard deviation of the number of rolls when M is {0}:",
            paired_rolls, lambda s: statistics.stdev(s))
    answers("\nView of the rolls summing to {0}\n" +
            format("Count", ">7") + " " + format("Sum", ">7") + " Rolls\n",
            [(20, sliced_sum20), (10000, sliced_sum10k)],
            lambda ss: ''.join(
                format(len(s[1]), ">7") + " " + format(s[0], ">7") + " " +
                format(s[1]) + "\n" for s in ss)
            , sep=''
            )
开发者ID:dlamblin,项目名称:NYC-taxi-Data-Incubator-challenge,代码行数:27,代码来源:rolls.py


示例19: get_result

    def get_result(self, raw_fname):
        node_flow_num_vs_performance = {}

        in_file = open(raw_fname, 'r')
        lines = in_file.readlines()
        in_file.close()
        for line in lines:
            #get each value
            line = line[1:-2]
            #print(line)
            items = line.split(', ')
            if len(items) != 9:
                continue
            num_nodes = int(items[0])
            num_tasks = int(items[1])
            num_candidate_pair = int(items[2])
            max_node_flows = int(items[3])
            num_pairs = int(items[4])
            latency = int(items[5])
            flow_avg_latency = int(items[7])
            max_flow_latency = int(items[8])

            if max_node_flows not in node_flow_num_vs_performance:
                node_flow_num_vs_performance[max_node_flows] = []
            node_flow_num_vs_performance[max_node_flows].append(
                (num_nodes, num_tasks, num_candidate_pair, num_pairs, latency, flow_avg_latency, max_flow_latency)
            )
                
        #statistics results
        for max_node_flows, tuples in sorted(node_flow_num_vs_performance.items(), key=lambda item: item[0]):
            list_num_tasks = []
            list_num_candidate_pair = []
            list_num_pairs = []
            list_latency = []
            list_flow_avg_latency = []
            all_rounds_max_flow_latency = 0
            for one_tuple in tuples:
                list_num_tasks.append(one_tuple[1])
                list_num_candidate_pair.append(one_tuple[2])
                list_num_pairs.append(one_tuple[3])
                list_latency.append(one_tuple[4])
                list_flow_avg_latency.append(one_tuple[5])
                all_rounds_max_flow_latency = max(all_rounds_max_flow_latency, int(one_tuple[6]))
            avg_num_tasks = statistics.mean(list_num_tasks)
            avg_num_candidate_pair = statistics.mean(list_num_candidate_pair)
            avg_num_pairs = statistics.mean(list_num_pairs)
            avg_latency = statistics.mean(list_latency)
            avg_flow_avg_latency = statistics.mean(list_flow_avg_latency)
            stdv_num_tasks = 0
            stdv_num_candidate_pair = 0
            stdv_num_pairs = 0
            stdv_latency = 0
            stdv_flow_avg_latency = 0
            if len(tuples) > 1:
                stdv_num_tasks = statistics.stdev(list_num_tasks)
                stdv_num_candidate_pair = statistics.stdev(list_num_candidate_pair)
                stdv_num_pairs = statistics.stdev(list_num_pairs)
                stdv_latency = statistics.stdev(list_latency)
                stdv_flow_avg_latency = statistics.stdev(list_flow_avg_latency)
            print(max_node_flows, avg_num_tasks, stdv_num_tasks, avg_num_candidate_pair, stdv_num_candidate_pair, avg_num_pairs, stdv_num_pairs, avg_latency, stdv_latency, avg_flow_avg_latency, stdv_flow_avg_latency, all_rounds_max_flow_latency) 
开发者ID:cfdream,项目名称:MonitorPlacement,代码行数:60,代码来源:get_nodeFlowNum_vs_performance_forGreedy.py


示例20: main

def main():
    dailymotion = acquire_dailymotion()
    print "Dailymotion"
    print "total videos: " + str(len(dailymotion[0]))
    print "mean views: " + str(statistics.mean(dailymotion[0]))
    print "median views: " + str(statistics.median(dailymotion[0]))
    print "STD views: " + str(statistics.stdev(dailymotion[0]))
    print "Average Date: " + str(convert_to_datetime(statistics.mean(dailymotion[1])))
    print "Median Date: " + str(convert_to_datetime(statistics.median(dailymotion[1])))
    print "Average Lengths: " + str(statistics.mean(dailymotion[2]))
    print "Median Lengths: " + str(statistics.median(dailymotion[2]))
    print "STD Lengths: " + str(statistics.stdev(dailymotion[2]))
    print "Top 20 most used word in title: "
    word_count_dailymotion("title")
    print "Top 20 most used word in description:"
    word_count_dailymotion("description")
    youtube = acquire_youtube()
    print "YouTube"
    print "total videos: " + str(len(youtube[0]))
    print "mean views: " + str(statistics.mean(youtube[0]))
    print "median views: " + str(statistics.median(youtube[0]))
    print "STD views: " + str(statistics.stdev(youtube[0]))
    print "Average Date: " + str(convert_to_datetime(statistics.mean(youtube[1])))
    print "Median Date: " + str(convert_to_datetime(statistics.median(youtube[1])))
    print "Video Definition: " , str(statistics.mode(youtube[2])) , " - " , str(youtube[2].count(statistics.mode(youtube[2]))) ,"/" , str(len(youtube[2]))
    print "Average Lengths: " + str(statistics.mean(youtube[3]))
    print "Median Lengths: " + str(statistics.median(youtube[3]))
    print "STD Lengths: " + str(statistics.stdev(youtube[3]))    
    print "Top 20 most used word in title: "
    word_count_yt("title")
    print "Top 20 most used words in description: "
    word_count_yt("description")
    client.close()
开发者ID:mavanes,项目名称:CS-454,代码行数:33,代码来源:dataStatistics.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python statistics.variance函数代码示例发布时间:2022-05-27
下一篇:
Python statistics.pstdev函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap