如何通过python字典循环保存每个输出数据



今天我发现我的python字典有问题。我需要从循环收集所有输出数据并将其写入 json 文件中。编写过程效果很好,但结果是,在 json 文件中只有一个,最后一个输出。我应该如何使用字典修复部分代码?这是代码:

def classify(sess, label_list, softmax_output, coder, images, image_file):
print('Running file %s' % image_file)
image_batch = make_batch(image_file, coder, not FLAGS.single_look)
batch_results = sess.run(softmax_output, feed_dict={images:image_batch.eval()})
output = batch_results[0]
batch_sz = batch_results.shape[0]
for i in range(1, batch_sz):
output = output + batch_results[i]
output /= batch_sz
best = np.argmax(output)
best_choice = (label_list[best], output[best])
Guess = 'Guess @ 1 %s, prob = %.2f' % best_choice
print('Guess @ 1 %s, prob = %.2f' % best_choice)
faces_pred = dict()
faces_pred =  {"face_pred": Guess}
with open('pred.json', 'w') as fp:
json.dump( faces_pred, fp)
nlabels = len(label_list)
if nlabels > 2:
output[best] = 0
second_best = np.argmax(output)
print('Guess @ 2 %s, prob = %.2f' % (label_list[second_best], output[second_best]))
return best_choice

我只对猜测 1 的所有输出感兴趣! 感谢您抽出宝贵时间:3

更新--------- 在 json 文件中,运行我的程序后,有以下输出:

{"face_pred": "Guess @ 1 (60, 100), prob = 0.75"}

没错,但仅适用于一张脸(我有 3+ 猜 @ 1)。它不是在json文件中添加新数据,只是重写它!

UPD2-------- 它的外观是控制台:

  • 运行文件 ./正面-脸-1.jpg
  • 运行多裁剪图像
  • 猜测 @ 1 (60, 100),概率 = 0.95
  • 猜测 @ 2 (4, 6),概率 = 0.02
  • 运行文件 ./正面-脸-2.jpg
  • 运行多裁剪图像
  • 猜测 @ 1 (60, 100),概率 = 0.75
  • 猜测 @ 2 (38, 43),概率 = 0.12
  • ubuntu@ubuntu122:~/罗马/IWAdector$

通过您的评论,我现在了解您的问题...你像这样打开你的文件:

with open('pred.json', 'w') as fp:
json.dump( faces_pred, fp)

并且每次都会重写整个文件,因此您只能在那里获得最后一个结果

您可以改为这样做:

with open('pred.json', 'a') as fp:
data_to_write = json.dumps(faces_pred)
fp.write(faces_pred + 'n')

请注意我在这里做的两件事:

  1. 我用"a"标志而不是"w"打开文件,该标志用于每次附加到文件末尾,而不是重写文件

  2. 我使用json.dumps而不是json.dump来生成一个字符串,然后将该字符串(附加它)写入文件,末尾带有n以确保每次后都会换行

最新更新