添加循环以获得n次结果,并将平均值输入csv Python

2024-04-19 00:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我为粒子过滤编写了一个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)

任何帮助都将不胜感激。你知道吗


Tags: csvto函数loopsizehere粒子plt
1条回答
网友
1楼 · 发布于 2024-04-19 00:27:44
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部分应该在循环之后

相关问题 更多 >