python简单日志类的创建

在训练模型的时候,希望把训练过程中的loss,acc等指标记录到文件中以便后续查看。

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout  #stdout
        self.file = None

    def open(self, file, mode=None):
        if mode is None: mode ='w'
        self.file = open(file, mode)

    def write(self, message, is_terminal=1, is_file=1 ):
        if '\r' in message: is_file=0

        if is_terminal == 1:
            self.terminal.write(message)
            self.terminal.flush()
            #time.sleep(1)

        if is_file == 1:
            self.file.write(message)
            self.file.flush()

    def flush(self):
        # this flush method is needed for python 3 compatibility.
        # this handles the flush command by doing nothing.
        # you might want to specify some extra behavior here.
        pass
    log.open('log.txt',mode='a')
    log.write("epoch:{}\n".format(epoch))
    log.write("loss:{}\n".format(loss))

你可能感兴趣的:(python编程,python,深度学习,机器学习)