[英]Adding a loop to get result 'n' times and get the average into a csv - Python
I wrote a python function for particle filtering. 我编写了一个用于粒子过滤的python函数。 I need to write a loop for the below function to save the best cost(Variable) for a csv file and get the average.
我需要为以下函数编写一个循环,以保存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)
Any help would be greatly appreciated. 任何帮助将不胜感激。
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))
This will write the best cost and the average to results.csv
with ;
这将使用
;
将最佳成本和平均值写入results.csv
;
as delimiter. 作为分隔符。 For a more specific approach, more information would be needed...
对于更具体的方法,将需要更多信息...
Edit: You're right, the writing to csv part should be after the loop 编辑:你是对的,写csv部分应该在循环之后
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.