簡體   English   中英

添加循環以獲取結果'n'次並將平均值存入csv-Python

[英]Adding a loop to get result 'n' times and get the average into a csv - 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)

任何幫助將不勝感激。

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部分應該在循環之后

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM