python :logging模块详细教程

SolidWorks打开STP弹窗爆炸原因与静默导入方案 STEP(STP)是一种遵循ISO 10303标准的中性三维数据交换格式,广泛用于CAD系统间模型传递。其本质是纯几何B-rep描述,不含参数化特征或历史树,因此导入时依赖接收软件的解析引擎(如SolidWorks集成的Parasolid内核)进行拓扑重建。当解析过程与UI线程耦合过紧,尤其在SolidWorks 2020+版本中,默认启用‘交互式导入确认’机制,便会将每个几何处理环节(如面合并、容差缝合、颜色映射)强行映射为独立模态窗口,引发窗口堆叠、焦点混乱等系统级交互异常。该问题并非文件损坏或硬件不足 阅读详情

logging模块

1.v1
v1版本无法指定日志的级别;无法指定日志的格式;只能往屏幕打印,无法写入文件。

日志总共分为以下五个级别:

  • logging.debug(‘调试’)
  • logging.info(‘正常’)
  • logging.critical(‘严重错误’)
  • logging.error(‘错误’)
  • logging.warning(‘警告’)

默认运行,会显示:

  • WARNING:root:警告信息
  • ERROR:root:报错信息
  • CRITICAL:root:严重错误信息
2.v2

v2版本不能指定字符编码;只能往文件中打印。

logging.basicConfig(filename='access.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)

logging.debug('调试信息')  # 10
logging.info('正常信息')  # 20
logging.warning('警告信息')  # 30
logging.error('报错信息')  # 40
logging.critical('严重错误信息')  # 50
3.v3

logging模块包含四种角色:logger、Filter、Formatter对象、Handler

  • logger:产生日志的对象
  • Filter:过滤日志的对象
  • Formatter对象:可以定制不同的日志格式对象,然后绑定给不同的Handler对象使用,以此来控制不同的Handler的日志格式
  • Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,StreamHandler用来打印到终端
# 1. 生成一个logger对象
logger = logging.getLogger('nick')

# 2. 生成格式
formmater1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                               datefmt='%Y-%m-%d %H:%M:%S %p',)
formmater2 = logging.Formatter('%(asctime)s :  %(message)s',
                               datefmt='%Y-%m-%d %H:%M:%S %p',)
formmater3 = logging.Formatter('%(name)s %(message)s',)

# 3. 生成一个文件对象
h1 = logging.FileHandler('h1.log')
h2 = logging.FileHandler('h2.log')
sm = logging.StreamHandler()


# 4. 文件绑定格式
h1.setFormatter(formmater1)
h2.setFormatter(formmater2)
sm.setFormatter(formmater3)


# 5. 绑定文件
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(sm)

# 6. 控制级别
logger.level = 50

# 7. 使用
logger.debug('调试信息')  # 10
logger.info('正常信息')  # 20
logger.warning('警告信息')  # 30
logger.error('报错信息')  # 40
logger.critical('严重错误信息')  # 50
'''
critical=50
error =40
warning =30
info = 20
debug =10
'''


import logging

# 1、logger对象:负责产生日志,然后交给Filter过滤,然后交给不同的Handler输出
logger = logging.getLogger(__file__)

# 2、Filter对象:不常用,略

# 3、Handler对象:接收logger传来的日志,然后控制输出
h1 = logging.FileHandler('t1.log')  # 打印到文件
h2 = logging.FileHandler('t2.log')  # 打印到文件
sm = logging.StreamHandler()  # 打印到终端

# 4、Formatter对象:日志格式
formmater1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                               datefmt='%Y-%m-%d %H:%M:%S %p',)

formmater2 = logging.Formatter('%(asctime)s :  %(message)s',
                               datefmt='%Y-%m-%d %H:%M:%S %p',)

formmater3 = logging.Formatter('%(name)s %(message)s',)


# 5、为Handler对象绑定格式
h1.setFormatter(formmater1)
h2.setFormatter(formmater2)
sm.setFormatter(formmater3)

# 6、将Handler添加给logger并设置日志级别
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(sm)

# 设置日志级别,可以在两个关卡进行设置logger与handler
# logger是第一级过滤,然后才能到handler
logger.setLevel(30)
h1.setLevel(10)
h2.setLevel(10)
sm.setLevel(10)

# 7、测试
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')

高配logging

1 配置日志文件

以上三个版本的日志只是为了引出我们下面的日志配置文件

import os
import logging.config

# 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'  # 其中name为getLogger()指定的名字;lineno为调用日志输出函数的语句所在的代码行
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
# 定义日志输出格式 结束

logfile_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # log文件的目录,需要自定义文件路径 # atm
logfile_dir = os.path.join(logfile_dir, 'log')  # C:\Users\oldboy\Desktop\atm\log

logfile_name = 'log.log'  # log文件名,需要自定义路径名

# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):  # C:\Users\oldboy\Desktop\atm\log
    os.mkdir(logfile_dir)

# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)  # C:\Users\oldboy\Desktop\atm\log\log.log
# 定义日志路径 结束

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},  # filter可以不定义
    'handlers': {
        # 打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        # 打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M  (*****)
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
        # logging.getLogger(__name__)拿到的logger配置。如果''设置为固定值logger1,则下次导入必须设置成logging.getLogger('logger1')
        '': {
            # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'handlers': ['default', 'console'],
            'level': 'DEBUG',
            'propagate': False,  # 向上(更高level的logger)传递
        },
    },
}



def load_my_logging_cfg():
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger(__name__)  # 生成一个log实例
    logger.info('It works!')  # 记录该文件的运行状态
    
    return logger


if __name__ == '__main__':
    load_my_logging_cfg()
2 使用日志
import time
import logging
import my_logging  # 导入自定义的logging配置

logger = logging.getLogger(__name__)  # 生成logger实例


def demo():
    logger.debug("start range... time:{}".format(time.time()))
    logger.info("中文测试开始。。。")
    for i in range(10):python
        logger.debug("i:{}".format(i))
        time.sleep(0.2)
    else:
        logger.debug("over range... time:{}".format(time.time()))
    logger.info("中文测试结束。。。")


if __name__ == "__main__":
    my_logging.load_my_logging_cfg()  # 在你程序文件的入口加载自定义logging配置
    demo()

三、Django日志配置文件

# logging_config.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
                      '[%(levelname)s][%(message)s]'
        },
        'simple': {
            'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
        },
        'collect': {
            'format': '%(message)s'
        }
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        # 打印到终端的日志
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        # 打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"),  # 日志文件
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M
            'backupCount': 3,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        # 打印到文件的日志:收集错误及以上的日志
        'error': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"),  # 日志文件
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M
            'backupCount': 5,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        # 打印到文件的日志
        'collect': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M
            'backupCount': 5,
            'formatter': 'collect',
            'encoding': "utf-8"
        }
    },
    'loggers': {
        # logging.getLogger(__name__)拿到的logger配置
        '': {
            'handlers': ['default', 'console', 'error'],
            'level': 'DEBUG',
            'propagate': True,
        },
        # logging.getLogger('collect')拿到的logger配置
        'collect': {
            'handlers': ['console', 'collect'],
            'level': 'INFO',
        }
    },
}


# -----------
# 用法:拿到俩个logger

logger = logging.getLogger(__name__)  # 线上正常的日志
collect_logger = logging.getLogger("collect")  # 领导说,需要为领导们单独定制领导们看的日志
基于STM32的红外测温系统设计 为了实现本次的毕业设计,我搜集了大量的文献与资料,通过这些资料了解到红外测温的优点,与实现所需的基本器件,并设计了几个方案,最终选择了STM32作为主控芯片,为此还查阅了关于STM32的资料,在此次设计中采用的是MLX90614医用红外测温模块,通过查阅其数据手册了解其测量精度高且自带温度补偿,所以选择了该传感器作为红外测温模块,本次设计到此已经基本完成,硬件部分和软件部分的设计已基本完成。 阅读详情

相关推荐

企业和个人 AI 编程工具怎么选?2025 年 12 款主流工具(Claude/Cursor 等)核心能力 + 收费对比

2025 年最火的 12 款 AI 编程工具,像 Claude、Cursor 这些热门款,我把它们的核心能力、收费标准全扒得明明白白,看完这篇你不用再瞎琢磨,直接就能挑到对的!再说说 Cursor,美国 Cursor Labs 做的,还拿过红杉资本投资,2022 年推出后,2024 年收入直接涨了 6400%,势头很猛。总之,不管你是企业技术管理者、程序员,还是刚入门的 AI 小白,按自己的需求(语言、合规、预算)挑,保准能找到最适合的 AI 编程工具!最后给大家划重点,不同需求直接对号入座:?

hundred98的博客 2813

Python日志logging实战教程

Python日志logging实战教程,从一个简单的日志记录实战,一步一步实现了自定义日志格式、写日志文件、抽出公共日志模块让其他模块用、同时写多个日志文件并进行日志文件切割、通过配置文件实现日志参数的定义、解决日志中文显示问题。基本覆盖了真实应用场景日志的使用。

学而思(xiejava的blog) 3854

PredFormer实战:用Transformer搞定交通流量预测(附TaxiBJ数据集代码)

本文详细介绍了如何利用PredFormer这一基于Transformer的先进模型进行交通流量预测,特别针对TaxiBJ数据集提供了完整的实战代码和优化策略。PredFormer通过门控Transformer块(GTB)的创新设计,在时空预测任务中展现出显著优势,相比传统方法将MSE降低33.1%,推理速度提升4.4倍。文章还涵盖了模型轻量化、部署优化等实用技巧,为智慧城市建设中的交通预测提供了高效解决方案。

weixin_29194817的博客 451

【python】详解logging日志模块

最近看了崔庆才的网站,个人认为博主的写的非常的好,本文基于博主的文章Python中logging模块的基本用法进行学习和改造。 1、日志记录的重要性 在开发过程中,如果程序运行出现了问题,我们是可以使用我们自己的 Debug 工具来检测到到底是哪一步出现了问题,如果出现了问题的话,是很容易排查的。但程序开发完成之后,我们会将它部署到生产环境中去,这时候代码相当于是在一个黑盒环境下运行的,我们只能看...

brucewong0516的博客 4492

加法器设计—— 原理图与VHDL设计初步

1、在DE2-115开发板上,完成4位全加器系统的设计、下载和功能演示,并在FPGA上实现1位全加器;2、完成3-8译码器的设计、下载和功能演示(利用板上的8段数码管)本次实验在组合逻辑电路的基础上,运用Verilog编程实现了四位全加器和3-8译码器的设计,同时实现了在DE2-115开发板上的下载和功能演示。整个过程加深了我对电路设计和Verilog编程的理解,同时也锻炼了解决问题的能力。

m0_74749526的博客 1249

避坑指南:解决‘Logical volume contains a filesystem in use’错误,顺利完成LVM根目录扩容

本文详细解析了Linux系统中LVM根目录扩容时遇到的‘Logical volume contains a filesystem in use’错误,提供了从错误诊断到实战解决方案的完整指南。通过动态扩容技术、单用户模式操作和LVM快照等方案,帮助管理员顺利完成根目录扩容,避免数据丢失和系统崩溃。

weixin_28702105的博客 234

Python logging 模块实用教程

logging 是 Python 标准库中用于记录日志的模块,它提供了灵活的日志记录系统,可以满足从简单脚本到复杂应用程序的各种日志需求。

qq_17275369的博客 925

二阶FLL辅助三阶PLL环路的代码解读

今天对GNSS接收机里面的载波跟踪环路代码进行了解读 以下是个人的一点见解 % 载波环第二步:环路滤波器 二阶FLL辅助三阶PLL环路 carrLoopS0 = lastCarrLoopS0 + (phaseErr*tau0PLL + freqErr*tau1FLL) * PDIcarr; carrLoopS1 = lastCarrLoopS1 + (tau1PLL*phaseErr + carrLoopS0 + tau2FLL*freqErr) * PD

LWN7321的博客 2641

Python-logging详解(彩色日志扩展,多进程安全等)

目录 简介 日志级别 记录器 处理器 格式器 多线程与多进程安全 代码 导入及全局变量 函数 实验及结果 参考 简介 日志是工程中不可缺少的一部分,国家等保2.0也规定,至少保留日志180天。对于程序员来说,日志也方便进行记录及排错。 logging是Python自带的日志模块,主要有以下几个部分: 记录器暴露了应用程序代码直接使用的接口。 处理器将日志记录(由记录器创建)发送到适当的目标。 过滤器提供了更细粒度的功能,用于确定要输出的日志记录。

关注网络安全、云原生安全 1万+

CloudCompare里那个CSF地面滤波插件,到底怎么用?手把手教你分离点云里的地面

本文详细介绍了如何在CloudCompare中使用CSF地面滤波插件分离点云中的地面数据。通过解析布料模拟滤波算法的核心参数,如布料刚度和网格分辨率,并提供不同地形(城市、丘陵、山地)的适配策略,帮助用户高效处理复杂点云数据。文章还包含实战案例和优化技巧,确保滤波结果的精度和可靠性。

weixin_42548708的博客 230

智能枕头

睡觉和吃饭是一样重要的,一个人想要健康的体魄,不仅要饮食得当,更需要有一个好的睡眠质量。随着人们生活品质的提高,人们对于睡眠的要求越来越高,那么就非常需要一款舒适的枕头。为了适应市场的需求,我爱物联网推出了智能枕头。因为智能枕头可以给头部及颈椎一个良好的承托力,舒适、柔软、放松,让人更好的进入睡眠。 目录 一、智能枕头方案介绍 二、智能枕头的优点 三、智能枕头功能介绍 四、智能枕头APP开发 五、...

6108我爱物联网方案开发CSDN博客 3661

Python—logging模块使用教程

Python—logging模块使用教程 简单用法 日志等级 级别 何时使用 DEBUG 细节信息,仅当诊断问题时适用。 INFO 确认程序按预期运行 WARNING 表明有已经或即将发生的意外(例如:磁盘空间不足)。程序仍按预期进行 ERROR 由于严重的问题,程序的某些功能已经不能正常执行 CRITICAL 严重的错误,表明程序已不能继续执行 控制台输出日志...

刘小义的博客 349

使用podspec创建iOS插件

概述 在WWDC 2014全球开发者大会上,苹果开放了动态库、App Extension等全新的功能,这为iOS插件化开发带来了可能。在iOS开发中,动态库是iOS提供的一种资源打包方式,可以将代码文件、头文件、资源文件和说明文档等集中在一起,并且可以在运行时进行动态加载。 目前,很多应用越做越复杂,应用程序也显得越来越臃肿。试想一下,如果将一些不常用的功能做成一个插件,然后根据用户的需求从网络中...

xiangzhihong8的专栏 995

Python入门:Python3 logging模块全面学习教程

本文围绕 Python logging 模块展开全面讲解,先对比其相较于 print 语句的优势,如灵活性高、可扩展性强、支持结构化日志及性能更优,接着介绍基础用法,包括导入模块、配置日志级别(含 DEBUG 到 CRITICAL 五级)、记录不同级别日志、自定义输出格式及将日志输出到文件,随后深入高级用法,解析 Logger、Handler、Formatter、Filter 四大核心组件关系,阐述为不同模块创建独立 Logger、用过滤器筛选日志及通过 RotatingFileHandler……

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 7794

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Python logging模块完整教程

Python logging模块是标准库中强大的日志记录工具,支持多级别日志记录、灵活配置和多种输出方式。本教程从基础概念开始,详细介绍了Logger、Handler和Formatter三大核心组件,以及它们之间的关系。内容包括日志级别控制、基本配置方法、高级配置技巧和实际应用场景,帮助开发者快速掌握日志系统的使用。通过示例代码演示了从简单日志输出到复杂日志处理的完整流程,并提供了性能优化和最佳实践建议,适合Python开发者系统学习日志记录技术。

cuber膜拜的博客 953

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

python logging模块之handlers的使用教程

一、handlers是什么? logging模块中包含的类 用来自定义日志对象的规则(比如:设置日志输出格式、等级等) 常用3个子类:StreamHandler、FileHandler、TimedRotatingFileHandler 二、handlers基础应用 2.1 StreamHandler 控制台输出日志 ''' 遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! ''' import l

Python热爱者的博客 4234

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Python3教程: logging 模块用法

Python logging 模块定义了为应用程序和库实现灵活的事件日志记录的函数和类。程序开发过程中,很多程序都有记录日志的需求,并且日志包含的信息有正常的程序访问日志还可能有错误、警告等信息输出,Python 的 logging 模块提供了标准的日志接口,可以通过它存储各种格式的日志,日志记录提供了一组便利功能,用于简单的日志记录用法。...

Python热爱者的博客 6157

Python实用教程系列——Logging日志模块

上篇文章讲述了Python中的相关异常的知识——Python实用教程系列——异常处理,包括异常的种类以及异常的处理方式,以及使用实例的方式说明了一些常用异常的处理。这次,我们来讲述一下Python中的另一个实用的教程,日志相关的知识。 很多的小伙伴在平时写代码的时候,基本上使用的都是使用print()函数来进行一些日志的打印,使用print()来进行一些代码的调试,在较小的程序中这样做是可以的。但是在实际的工程项目中,我们需要保存程序运行的日志,以排查程序在某一个时候崩溃的具体原因,以便及...

th1522856954的博客 849

python logging模块使用教程

简单使用 #!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') logging.info('info message') logging.warn('warn message') logging.error('error message') logging.critical('critical message') 输出: WARNING:root:warn.

Dove_1234的博客 325

Python logging 模块基础教程

Python logging 模块基础 基础 简单使用 logging 模块有与日志级别对应的函数,可以直接输出日志 import logging logging.warning("warn") 输出: WARNING:root:warn 没有任何配置之前, 默认使用 the root logger 发送日志, 这就是为什么输出中包含 root , 日志默认被发送至标准错误输出 stderr (终端显示红色字体) 日志级别 Level 重要程度 logging.DEBUG 调试 lo

jianghuixin 891

记录程序写入日志_python日志记录系列教程,内置logging模块(一),直接使用logging模块的基础日志记录...

前言:成熟的软件开发不可避免的要进行日志记录,python内置模块logging提供了强大的日志记录能力,本文将从多个角度,由浅入深的介绍logging的常见使用方法和一些基本概念,本此系列文章分为两篇,本文为系列文章第一篇,介绍实用logging模块进行基本的日志记录操作。本文主要都是直接使用 logging.xxxx() 的方式,这是最简单初步的日志记录,不涉及任何复杂的类和对象,这些将会在...

weixin_42570296的博客 256

【Python】logging日志模块简明教程

logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点: 可以通过设置不同的日志等级,在release版本中只输出重要信息,而不必显示大量的调试信息; print将所有信息都输出到标准输出中,严重影响开发者从标准输出中查看其它数据;logging则可以由开发者决定将信息输出到什么地方,以及怎么输出。 基本设置: from datetime import datetime import l

LeonJin的博客 518

python--logging模块使用教程

简单使用 #!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') logging.info('info message') logging.warn('warn message') logging.error('error message') logging.crit...

大发的博客 607
上一篇: python:pandas模块最全最详细的教程
下一篇: Python:hashlid模块详细用法教程
Python热爱者
博客等级 码龄7年 3082粉丝 1330原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值