如何计算每次迭代的平均值?

时间:2019-12-24 09:45:41

标签: python

我想在每次迭代中计算合适的候选平均值,但是我不知道该怎么做。

import pandas as pd
import numpy as np

  while iteration < n_iterations:
        print('iteration     fitness_candidate')
        for i in range(n_particles):

            temp = []
            fitness_cadidate = fitness_function(particle_position_vector[i])
            print(iteration,' ', -(fitness_cadidate))

            temp.append(iteration)
            temp.append(particle_position_vector[i])
            temp.append(-(fitness_cadidate))
            ls.append(temp)

        iteration = iteration + 1

ls = pd.DataFrame(ls)

如您所见,每次迭代都会生成多个适应度候选者。因此,我只需要计算迭代中适合度的平均值。如果它有4次迭代,则需要生成4个平均值。

输出:

iteration     fitness_candidate
0            20.24475
0            15.720000000000002
0            16.242250000000002
0            11.0975
0            20.923250000000007
0            15.720000000000002
0            22.924500000000002
0            17.472250000000003
0            24.247250000000005
0            24.305750000000003
iteration     fitness_candidate
1            21.72342
1            16.798420000000004
1            19.321920000000002
1            10.945920000000001
1            21.601420000000008
1            17.598920000000003
1            23.202420000000007
1            20.55192
1            24.124920000000003
1            24.305750000000003
iteration     fitness_candidate
2            22.801840000000002
2            19.47784
2            21.601090000000003
2            15.597339999999999
2            22.279590000000002
2            19.878089999999997
2            23.080090000000002
2            22.152920000000005
2            24.402840000000005
2            24.305750000000003
iteration     fitness_candidate
3            23.050510000000006
3            20.52701
3            21.44951
3            17.447010000000002
3            22.12801
3            19.72651
3            22.528260000000003
3            22.001340000000003
3            24.402840000000005
3            24.00259

2 个答案:

答案 0 :(得分:0)

您可以使用:

while iteration < n_iterations:
    print('iteration     fitness_candidate')
    for i in range(n_particles):
        print(iteration,' ', -(fitness_cadidate)

    print("Average",' ', sum([-(fitness_function(particle_position_vector[i])) for i in range(n_particles)])/len(n_particles))
    iteration = iteration + 1

答案 1 :(得分:0)

如果有循环,则python list comprehension可让您直接将结果转储到列表[i for i in data]中。这意味着我们可以将numpys mean函数应用于所述列表并获得结果。如果需要结果列表,我们可以在每个迭代周期将它们添加到新列表(results)中。

import numpy as np

results =[]

while iteration < n_iterations:
    print('iteration     fitness_candidate')

    mean = np.mean( [-(fitness_cadidate) for i in range(n_particles)] )

    print(iteration,mean)
    results.append(mean)

    iteration = iteration + 1