将输出标签值保存到csv



我是python的新手,也许这是一个非常基本的问题,但我还没有得到这个问题的解决方案。我正在研究一个分类问题,我已经训练了40个类的模型,并对测试数据进行了测试。我得到了大约4000+的标签,在测试数据中的每个图像上都有一个标签。我想把所有这些4000多个标签保存在一个CSV文件中。我写了一段代码,问题是当我运行代码时,只有最后一个标签保存到CSV文件中,我如何将所有标签保存在CSV文件的单列中。

import csv
Labels=[]
model.eval()
with torch.no_grad():
for data in test_loader:
output=model(data)
Labels.append(output.argmax().item())
print(output.argmax().item())

x = output.argmax().item()
reader = [[x]]
with open('Submission.csv', 'w', newline='') as f:
thewriter = csv.writer(f)              
thewriter.writerows(reader)
import csv
model.eval()
with open('Submission.csv', 'a+', newline='') as f:  # 'a+' means append to a file
thewriter = csv.writer(f)

with torch.no_grad():
for data in test_loader:
output=model(data)
label = output.argmax().item()  # this your label
print(label)
thewriter.writerow([label])

最新更新