【问题标题】:Adding a loop to get result 'n' times and get the average into a csv - Python添加一个循环以获取“n”次结果并将平均值转换为 csv - Python
【发布时间】:2017-09-20 07:38:48
【问题描述】:

我写了一个用于粒子过滤的python函数。我需要为以下函数编写一个循环,以保存 csv 文件的最佳成本(变量)并获得平均值。

#loop should start here        
    pop_size=50
    #128 to #135 loop
    W = initial_population(region, scale , pop_size)

    pop = PatternPosePopulation(W, pat)
    pop.set_distance_image(imd)

    pop.temperature = 5

    Lw, Lc = pop.particle_filter_search(int(1000/pop_size),log=True)
    #Loop should end here for example run pop 50 x n times and store best_cost, take average of bestcost save to csv file.

    plt.plot(Lc)
    plt.title('Cost vs generation index')
    plt.show()

    print(pop.best_w)
    print(pop.best_cost)

任何帮助将不胜感激。

【问题讨论】:

  • “50 x n 次”中的“n”是什么?如果没有步号的依赖,可以使用for i in range(50*n):
  • @Alperen 它可以是任何数字。就我而言,它是“5”。

标签: python loops csv particle-filter


【解决方案1】:
best_costs = []
for iteration in range(n):     
    pop_size=50
    W = initial_population(region, scale , pop_size)

    pop = PatternPosePopulation(W, pat)
    pop.set_distance_image(imd)

    pop.temperature = 5

    Lw, Lc = pop.particle_filter_search(int(1000/pop_size),log=True)

    best_costs.append(pop.best_cost)#store the best cost for this iteration

    #Loop should end here for example run pop 50 x n times and store best_cost, take average of bestcost save to csv file.

    plt.plot(Lc)
    plt.title('Cost vs generation index')
    plt.show()

    print(pop.best_w)
    print(pop.best_cost)

#write to csv
best_cost_total = min(best_costs)
best_cost_avg = sum(best_costs) / n

results = [str(best_cost_total), str(best_cost_avg)]

with open('results.csv', 'w') as f:
    f.write(";".join(results))

这会将最佳成本和平均值写入results.csv,并以; 作为分隔符。对于更具体的方法,需要更多信息...

编辑:你是对的,写入 csv 部分应该在循环之后

【讨论】:

  • 这个错误可能是由stackoverflow使用的那个奇怪的4空格缩进引起的。只需检查所有缩进是否都是实际的制表符而不是空格。很高兴我能帮上忙
  • 我当然会这样做。现在缩进问题没问题。有一个值错误“min() arg 是一个空序列”。任何提示@LcdDrm ?
  • 第 128 到 143 行必须在 for 循环内,所以你必须缩进它们
猜你喜欢
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 2014-03-06
  • 2018-06-14
相关资源
最近更新 更多