3

我正在使用 DEAP 进行遗传算法。我在日志中得到了一些结果。日志的形状是字典的附加部分,如下所示。

{"gen": 0, "nevals": 200, "avg": 5678.124656362589, "std": 1665.10303246997, "min": 2414.709605862963, "max": 10544.10349270114, "time": 3.061805009841919}
{"gen": 1, "nevals": 200, "avg": 4615.100755434814, "std": 1032.0542912118117, "min": 2414.709605862963, "max": 8710.009719746668, "time": 5.24877405166626}
{"gen": 2, "nevals": 200, "avg": 4426.86753960162, "std": 952.752217081577, "min": 2414.709605862963, "max": 7834.360961929298, "time": 7.716948747634888}
{"gen": 3, "nevals": 200, "avg": 4312.832205468258, "std": 954.6308089644021, "min": 2820.0828681777357, "max": 8069.475022854921, "time": 10.185122013092041}
{"gen": 4, "nevals": 200, "avg": 4333.539783185404, "std": 1155.0262921447736, "min": 2761.1404825322666, "max": 9830.868579904474, "time": 12.684537410736084}
{"gen": 5, "nevals": 200, "avg": 4285.034002752331, "std": 1136.5306484499206, "min": 2571.9258380478823, "max": 10371.549396541837, "time": 15.215197086334229}

我可以用方法把它写成文本文件json.dumps。但我想把它写成一个像下面这样的文本文件,和控制台上的结果一样。

python控制台上的结果

我能处理这个吗?

我现在使用 python 3.6。

4

1 回答 1

3

您可以使用pandas创建 DataFrame 并将其写入 CSV 文件。

In [1]: import pandas as pd
In [2]: from deap import tools

In [3]: logbook = tools.Logbook() # Creating a logbook

In [4]: logbook.record(gen=0, nevals=200, avg=5678.124656362589, std=1665.10303246997, 
                       min=2414.709605862963, max=10544.10349270114, time=3.061805009841919)   
In [5]: logbook.record(gen=1, nevals=200, avg=4615.100755434814, std=1032.0542912118117, 
                       min=2414.709605862963, max=8710.009719746668, time=5.24877405166626)    
In [6]: logbook.record(gen=2, nevals=200, avg=4426.86753960162, std=952.752217081577, 
                       min=2414.709605862963, max=7834.360961929298, time=7.716948747634888)

In [7]: df_log = pd.DataFrame(logbook)

In [8]: df_log
Out[8]: 
           avg  gen           max          min  nevals          std      time
0  5678.124656    0  10544.103493  2414.709606     200  1665.103032  3.061805
1  4615.100755    1   8710.009720  2414.709606     200  1032.054291  5.248774
2  4426.867540    2   7834.360962  2414.709606     200   952.752217  7.716949

In [9]: df_log.to_csv('/path/to/your/file.csv', index=False) # Writing to a CSV file
于 2018-07-06T15:40:22.237 回答