You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义数据集GAN使用Tensorboard报FailedPreconditionError求助

Tensorboard SummaryWriter 报错:FailedPreconditionError: runs is not a directory

问题重现

我用自定义数据集搭建GAN模型,尝试通过Tensorboard实现可视化,运行以下代码时出现错误:

from torch.utils.tensorboard import SummaryWriter

writer_fake = SummaryWriter()
writer_real = SummaryWriter()

程序创建了名为run的文件夹后,抛出如下错误:

---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
Cell In[28], line 14
      9 # os.makedirs("runs/Images/fake")
     10 # os.makedirs("runs/Images/real")
     11 
     12 # Initialize SummaryWriter
     13 writer_fake = SummaryWriter()
---> 14 writer_real = SummaryWriter()

File ~\pytorch\MLvenv\Lib\site-packages\torch\utils\tensorboard\writer.py:247, in SummaryWriter.__init__(self, log_dir, comment, purge_step, max_queue, flush_secs, filename_suffix)
    244 # Initialize the file writers, but they can be cleared out on close
    245 # and recreated later as needed.
    246 self.file_writer = self.all_writers = None
---> 247 self._get_file_writer()
    249 # Create default bins for histograms, see generate_testdata.py in tensorflow/tensorboard
    250 v = 1e-12

File ~\pytorch\MLvenv\Lib\site-packages\torch\utils\tensorboard\writer.py:277, in SummaryWriter._get_file_writer(self)
    275 """Returns the default FileWriter instance. Recreates it if closed."""
    276 if self.all_writers is None or self.file_writer is None:
---> 277     self.file_writer = FileWriter(
    278         self.log_dir, self.max_queue, self.flush_secs, self.filename_suffix
    279     )
    280     self.all_writers = {self.file_writer.get_logdir(): self.file_writer}
    281     if self.purge_step is not None:

File ~\pytorch\MLvenv\Lib\site-packages\torch\utils\tensorboard\writer.py:76, in FileWriter.__init__(self, log_dir, max_queue, flush_secs, filename_suffix)
     71 # Sometimes PosixPath is passed in and we need to coerce it to
     72 # a string in all cases
     73 # TODO: See if we can remove this in the future if we are
     74 # actually the ones passing in a PosixPath
     75 log_dir = str(log_dir)
---> 76 self.event_writer = EventFileWriter(
     77     log_dir, max_queue, flush_secs, filename_suffix
     78 )

File ~\pytorch\MLvenv\Lib\site-packages\tensorboard\summary\writer\event_file_writer.py:72, in EventFileWriter.__init__(self, logdir, max_queue_size, flush_secs, filename_suffix)
     57 """Creates a `EventFileWriter` and an event file to write to.
     58 
     59 On construction the summary writer creates a new event file in `logdir`.
   (...)
     69     pending events and summaries to disk.
     70 """
     71 self._logdir = logdir
---> 72 tf.io.gfile.makedirs(logdir)
     73 self._file_name = (
     74     os.path.join(
     75         logdir,
   (...)
     84     + filename_suffix
     85 )  # noqa E128
     86 self._general_file_writer = tf.io.gfile.GFile(self._file_name, "wb")

File ~\pytorch\MLvenv\Lib\site-packages\tensorflow\python\lib\io\file_io.py:513, in recursive_create_dir_v2(path)
    501 @tf_export("io.gfile.makedirs")
    502 def recursive_create_dir_v2(path):
    503   """Creates a directory and all parent/intermediate directories.
    504 
    505   It succeeds if path already exists and is writable.
   (...)
    511     errors.OpError: If the operation fails.
    512   """
---> 513   _pywrap_file_io.RecursivelyCreateDir(compat.path_to_bytes(path))

FailedPreconditionError: runs is not a directory

原因分析

当未指定log_dir参数时,SummaryWriter会默认生成runs/日期时间格式的子目录。但第一个writer_fake创建时,可能因文件系统冲突、权限问题等意外将runs创建为文件而非目录,导致第二个writer_real尝试创建子目录时,TensorFlow的tf.io.gfile.makedirs检测到runs不是目录,触发报错。

解决方案

方案1:手动指定独立日志目录

给两个SummaryWriter分别指定明确的子目录,避免自动生成时的冲突:

import os
from torch.utils.tensorboard import SummaryWriter

# 先创建父目录(如果不存在)
os.makedirs('runs/Images/fake', exist_ok=True)
os.makedirs('runs/Images/real', exist_ok=True)

# 初始化不同目录的SummaryWriter
writer_fake = SummaryWriter(log_dir='runs/Images/fake')
writer_real = SummaryWriter(log_dir='runs/Images/real')

方案2:清理错误的文件/目录

  • 检查当前工作目录,找到名为run或runs的文件(注意不是目录),直接删除。
  • 如果runs是目录但权限异常,右键打开目录属性,确保当前用户拥有读写权限。

方案3:使用单个SummaryWriter区分标签

不需要创建多个SummaryWriter实例,可通过标签区分真实与生成图像,更简洁且避免冲突:

from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter()
# 写入真实图像,用"Real Images"作为标签
writer.add_images('Real Images', real_images, global_step=step)
# 写入生成图像,用"Fake Images"作为标签
writer.add_images('Fake Images', fake_images, global_step=step)

内容的提问来源于stack exchange,提问作者Cihan Yalçın

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 13:30:09