python日志配置文件_求个 python logging配置文件例子

本文介绍了一个Python项目中日志模块的配置与使用方法,包括如何创建文件日志输出和控制台输出,并通过实例展示了如何在一个具体类中使用自定义的日志记录器。

loggger.py

import logging

import sys

def init():

"""

This function only run once

create 2 log outputs : a file and console

:return:

"""

#-----------------------------------------------------

# create an instance of logging.Logger

#-----------------------------------------------------

logger=logging.getLogger("myproj")

#-----------------------------------------------------

# create an instance of FileHandler for the log file

#-----------------------------------------------------

log_file=r'C:\users\bckong\desktop\tmp\test.log'

fp=logging.FileHandler(filename=log_file, mode='a')

# output message format: [level ], [module name ],[function name ], [line number ] message

# you can change output format

fmt_string = '[%(levelname)-9s] [%(module)-20s] [%(funcName)-20s %(lineno)4d]  %(message)s'

# create an instance of logging.Formatter

formatter = logging.Formatter(fmt=fmt_string)

fp.setFormatter(formatter)

# add the log file handler to the logger

logger.addHandler(fp)

#-----------------------------------------------------

# create an instance of StreamHandler for console output

#-----------------------------------------------------

log_console=logging.StreamHandler(stream=sys.stdout)

log_console.setFormatter(formatter)

# add the console output to the logger

logger.addHandler(log_console)

using_mylogger.py

import logging

import logger

class Foo():

def __init__(self):

print "----> ", __file__

self.log=logging.getLogger("myproj.module.file02")

self.log.setLevel(logging.DEBUG)

self.log.info("instance of Foo")

def greatings(self):

self.log.debug("Welcome to logging module")

f=Foo()

f.greatings()

### 如何在 PyTorch 中计算梯度 为了更好地理解如何在 PyTorch 中计算梯度,重要的是要熟悉 `requires_grad` 属性的作用。当设置某个 Tensor 的 `.requires_grad=True` 时,PyTorch 将会追踪所有对该张量执行的操作以便后续能够应用链式法则来进行反向传播并计算梯度[^5]。 一旦定义了一个带有 `requires_grad=True` 的变量参与运算之后,在完成前向传递后可以通过调用 `.backward()` 方法启动反向传播流程。这一步骤将会根据之前记录下来的操作历史自动计算出每一个可训练参数相对于损失函数的偏导数,并把这些值存储于对应的 `.grad` 属性里[^1]。 下面给出一段简单的 Python 代码作为例子展示这一过程: ```python import torch # 创建两个随机初始化的 Tensors 并指定 requires_grad 参数为 True 表明我们需要跟踪它们的变化情况 x = torch.tensor([2.], requires_grad=True) w = torch.tensor([3.], requires_grad=True) # 定义一个简单的一元线性方程 y=wx+b (这里 b=0),其中 w 是权重而 x 则代表输入特征 y = w * x # 对输出做一次平方操作得到最终的目标值 z=w²*x² z = y ** 2 # 调用 .backward() 来触发整个网络中的梯度回传动作 z.backward() print('dz/dw:', w.grad.item()) # 输出 dz 关于 w 的一阶导数值 print('dz/dx:', x.grad.item()) # 输出 dz 关于 x 的一阶导数值 ``` 这段程序创建了两个具有 `requires_grad=True` 设置的张量 `x` 和 `w`,接着构建了一个表达式树结构表示目标函数 \(z=(wx)^{2}\) 。最后通过调用 `z.backward()` 实现了对整条路径上各节点处局部梯度信息的有效收集与汇总工作;与此同时,也完成了全局最优解方向指引的任务——即确定了各个待优化参数应朝哪个方向调整才能使得整体误差最小化[^2]。 需要注意的是,如果尝试将含有 `requires_grad=True` 标志位的对象转换成 NumPy 数组,则必须先调用 `.detach()` 或者使用上下文管理器 `with torch.no_grad():` 来阻止进一步的梯度追踪行为发生,这是因为直接转换单纯只会引发错误提示而不是真正意义上的数据复制[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值