Python日志模块学习,从这里开始...

Python学习之-logging模块及彩色日志详解 Python的logging模块是内建的、功能强大的日志系统,可通过简单的配置,就能满足基本到复杂的日志管理需求。它可以让你以各种方式记录错误、调试信息、以及其他运行时的信息,这些都是应用程序健壯性、可维护性的关键。 阅读详情
一脸懵逼
5847426-6095c08a7249c06a
一脸懵逼

一直比较喜欢在简书上写博文,主要是因为它的页面看这清爽,没有csdn那么多的广告。可周五写文章的时候就看到禁止发文章的提示,当时以为是系统维护没有注意,没想到今天看到置顶文章才知道,要整改一个月。
之前文章就吐槽过,不知道从何时开始,简书首页上每天充斥这大量的擦边小黄文,反而技术类的文章没几篇能上榜的。对于这种问题,很多人都在吐槽、投诉文章,但没什么卵用。这下好了封停一个月,好好整改下吧。期待一个月后能看到一个不一样的简书平台,那么最近,只能在csdn上发文章了。之前的csdn账号id有些晦涩,虽然用了几年了,但决定还是重开了一个博客,期待大家的关注,博客地址:
csdn博客地址: https://blog.youkuaiyun.com/BreezePython
由于新开的博客,历史的文章还没有迁移,抽空慢慢迁移过来吧...

消息与记录

刚才谈到了关于历史账号的文章与消息记录,所以今天想跟大家聊聊Python关于消息记录的模块:日志管理模块 logging。
学习python的第一课,肯定都是 print('Hello Wrold...')。但print仅仅使用与我们日常学习,当我们的程序需要部署上线时,程序必须要具备记录日志与程序输出的功能。此时print就不能满足我们的需求,而logging应运而生。
logging是python的内置模块,无需安装即可直接使用。logging模块借鉴了Apache的Log4j中很多的功能与特性,使用起来较为方便,不论你是最简单无脑输出还是定义自己的过滤器与格式,最终都能满足大家的需求,所以logging模块是你的必修课!

Logging入门
日志级别

不论是python、java还是C,日志的级别都是统一规定的:

日志级别使用范围
FATAL致命错误
CRITICAL严重的错误,如内存耗尽、磁盘空间不足等.
ERROR错误,如IO异常,文件读写异常等
WARNING警告类错误,如用户输入密码即将过期提醒等
INFO处理请求或者用户操作的状态及日常事务日志
DEBUG调试过程中使用的日志等级,可用于后台问题定位

那么logging中存在哪些?默认分为六种日志级别(括号为级别对应的数值),NOTSET(0)、DEBUG(10)、INFO(20)、WARNING(30)、ERROR(40)、CRITICAL(50)。

简单日志打印

说了半天的日志级别,那么这东西对日志记录有什么用?此时我们需要了解LogLevel。logging模块默认记录日志的级别是大于等于WARNING。那么让我们来看第一个例子:

import logging
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')
>>> WARNING:root:This is warning message
>>> ERROR:root:This is error message
>>> CRITICAL:root:This is critical message

理想中我们期望的打印结果是从debug到critical,但现实是日志从warning级别开始打印。而且这种日志的打印和print又有什么区别,我们需要丰满日志的内容,提升逼格。

配置日志输出

logging提供了basicConfig函数,用于对日志输入进行相关配置。
让我们来看看basicConfig有哪些可配置参数吧:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,
    默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(message)s', datefmt='%Y-%m-%d')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')

>>> 2019-09-01 23:56:33 LearnLogging.py[line:38] This is debug message
>>> 2019-09-01 23:56:33 LearnLogging.py[line:39] This is info message
>>> 2019-09-01 23:56:33 LearnLogging.py[line:40] This is warning message
>>> 2019-09-01 23:56:33 LearnLogging.py[line:41] This is error message
>>> 2019-09-01 23:56:33 LearnLogging.py[line:42] This is critical message

通过配置basicConfig,日志输出看起来就工整多了...当看到第一个filename的时候就想到了,现在的日志都是在控制台输出的,我们添加该参数后,就可以将日志输出到文本了,对吧?答案是肯定的,如下图:


5847426-90d5957a5ef2a5e3.png
日志保存文本

但此时出现一个问题,我们的日志都保存到了文本中,前台的控制栏不再具备日志输出功能了!这该如何是好?

Logging进阶

刚才提到的入门使用,只是针对logging的一个简单操作,如果我们想深入的去使用logging模块,就必须了解Logger,Handler,Formatter,Filter的概念:

  • Logger提供了应用程序可以直接使用的接口;
  • Handler将(logger创建的)日志记录发送到合适的目的输出;
  • Filters提供了细度设备来决定输出哪条日志记录;
  • Formatter决定日志记录的最终输出格式。
Logger

Logger 对象要做三件事情。首先,它们向应用代码暴露了许多方法,这样应用可以在运行时记录消息。其次,记录器对象通过严重程度(默认的过滤设施)或者过滤器对象来决定哪些日志消息需要记录下来。第三,记录器对象将相关的日志消息传递给所有感兴趣的日志处理器。

常用的记录器对象的方法分为两类:配置和发送消息。

这些是最常用的配置方法:

Logger.setLevel()指定logger将会处理的最低的安全等级日志信息, debug是最低的内置安全等级,critical是最高的内建安全等级。例如,如果严重程度为INFO,记录器将只处理INFO,WARNING,ERROR和CRITICAL消息,DEBUG消息被忽略。
Logger.addHandler()和Logger.removeHandler()从记录器对象中添加和删除处理程序对象。处理器详见Handlers。
Logger.addFilter()和Logger.removeFilter()从记录器对象添加和删除过滤器对象。

Handlers

处理程序对象负责将适当的日志消息(基于日志消息的严重性)分派到处理程序的指定目标。Logger 对象可以通过addHandler()方法增加零个或多个handler对象。举个例子,一个应用可以将所有的日志消息发送至日志文件,所有的错误级别(error)及以上的日志消息发送至标准输出,所有的严重级别(critical)日志消息发送至某个电子邮箱。在这个例子中需要三个独立的处理器,每一个负责将特定级别的消息发送至特定的位置。
其中常用的有4种:

  • logging.StreamHandler -> 控制台输出
  • logging.FileHandler -> 文件输出
  • logging.handlers.RotatingFileHandler
  • logging.handlers.TimedRotatingFileHandler
Formatter

Formatter对象设置日志信息最后的规则、结构和内容,默认的时间格式为%Y-%m-%d %H:%M:%S,下面是Formatter常用的一些信息

参数说明
%(name)sLogger的名字
%(levelno)s数字形式的日志级别
%(levelname)s文本形式的日志级别
%(pathname)s调用日志输出函数的模块的完整路径名,可能没有
%(filename)s调用日志输出函数的模块的文件名
%(module)s调用日志输出函数的模块名
%(funcName)s调用日志输出函数的函数名
%(lineno)d调用日志输出函数的语句所在的代码行
%(created)f当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d线程ID。可能没有
%(threadName)s线程名。可能没有
%(process)d进程ID。可能没有
%(message)s用户输出的消息

此时我们就可以实现日志的前后台输出了:

import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)

logger.addHandler(handler)
logger.addHandler(console)

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
logger.error('This is error message')
logger.critical('This is critical message')

>>> 2019-09-02 00:49:58 LearnLogging.py[line:62] This is info message
>>> 2019-09-02 00:49:58 LearnLogging.py[line:63] This is warning message
>>> 2019-09-02 00:49:58 LearnLogging.py[line:64] This is error message
>>> 2019-09-02 00:49:58 LearnLogging.py[line:65] This is critical message

此时,前后台均输出了相关的日志信息。

Logging特别操作
日志切片

有时候,系统后台的日志会输出的比较频繁,那么我们如何将日志按照大小或者时间进行切片呢?这里就要用到刚才介绍的:

  • logging.handlers.RotatingFileHandler
  • logging.handlers.TimedRotatingFileHandler

每隔 1000 Byte 划分一个日志文件,备份文件为 3 个
file_handler = logging.handlers.RotatingFileHandler("test.log", mode="w", maxBytes=1000, backupCount=3, encoding="utf-8")

每隔 1小时 划分一个日志文件,interval 是时间间隔,备份文件为 10 个
handler2 = logging.handlers.TimedRotatingFileHandler("test.log", when="H", interval=1, backupCount=10)

我们以RotatingFileHandler为例,为了演示方便,我设置文件大小为3kb:

import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')
handler = RotatingFileHandler("log.txt", maxBytes=1024*3, backupCount=3)
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)

logger.addHandler(handler)
logger.addHandler(console)

for i in range(10):
    logger.info(i)
    logger.debug('This is debug message')
    logger.info('This is info message')
    logger.warning('This is warning message')
    logger.error('This is error message')
    logger.critical('This is critical message')

最终实现:


5847426-f969bccb87cddcc6.png
日志记录
关于异常日志

logging模块在对异常获取时,进行了相关的优化操作,来看下这个例子:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(console)

try:
    1/0
except Exception as error:
    logger.error(error)

    logger.error(error, exc_info=True)

    logger.exception(error)

>>> 2019-09-02 01:06:15 LearnLogging.py[line:87] division by zero

>>> 2019-09-02 01:06:15 LearnLogging.py[line:89] division by zero
    Traceback (most recent call last):
      File "D:/Codes_Repository/Python/PythonTests/37.Python日志模块/LearnLogging.py", line 85, in <module>
        1/0
    ZeroDivisionError: division by zero

>>> 2019-09-02 01:06:15 LearnLogging.py[line:91] division by zero
    Traceback (most recent call last):
      File "D:/Codes_Repository/Python/PythonTests/37.Python日志模块/LearnLogging.py", line 85, in <module>
        1/0
    ZeroDivisionError: division by zero

由此可见,当我们在对异常结果进行日志输出时,最好使用logger.exception。
其实logging模块的内容还有很多,比如封装与继承,今天就先介绍到这里,有空了继续为大家补充。

The End

OK,今天的内容就到这里,如果觉得内容对你有所帮助,欢迎点击文章右下角的“在看”。
期待你关注我的公众号 清风Python,如果觉得不错,希望能动动手指转发给你身边的朋友们。
希望每周一至五清晨的7点10分,都能让清风Python的知识文章叫醒大家!谢谢……

5847426-345eeedfd6765027
清风Python

从零开始学 Python 之 logging 模块详解 This module defines functions and classes which implement a flexible event logging system for applications and libraries. Python logging 模块定义了为应用程序和库实现灵活的事件日志记录的函数和类。 程序开发过程中,很多程序都有记录日志的需求,并且日志包含的信息有正常的程序访问日志还可能有错误、警告等信息输出,Python 的 logging 模块提供了标准的日志接口,可. 阅读详情

相关推荐

Python常用模块 之 logging:日志模块

Python常用模块 之 logging:日志模块

孤寒者的博客 17万+

使用logging模块将屏幕打印的日志同时保存到本地

复制即可用 import logging logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')

小王同学的博客 1048

〖Python零基础入门篇(57)〗- Python中的日志模块

OK,今天我们来学习一下 python 中的日志模块,日志模块也是我们日后的开发工作中使用率很高的模块之一,接下来们就看一看今天具体要学习日志模块中的那些内容吧。

易编橙 · 终身成长社群,相遇已是上上签! 4万+

python的logging使用

‘’’ 日志级别 DEBUG Python 标准库 logging 用作记录日志,默认分为六种日志级别(括号为级别对应的数值), NOTSET(0)、DEBUG(10)、INFO(20)、WARNING(30)、ERROR(40)、CRITICAL(50)。 logging 执行时输出大于等于设置的日志级别的日志信息,如设置日志级别是 INFO,则 INFO、WARNING、ERROR、CRITICAL 级别的日志都会输出。 ‘’’ import logging logger = logging.getLo

小白的笔记 2286

DDR Study - LPDDR5 Power-Up and Initialization Sequence

本文深入解析LPDDR5内存的上电初始化流程,涵盖电源斜坡、复位信号释放和初始化训练等关键阶段。通过实际案例分享,详细探讨了电源轨时序、RESET信号处理、ZQ校准和CA总线训练等核心技术要点,帮助硬件工程师规避常见设计陷阱,确保DDR内存稳定运行。

weixin_42523792的博客 304

PCB板质量测试和PCB板

PCB板质量测试和板厂

weixin_51370842的博客 515

java开发中的5种日志级别

JAVA中常见的日志级别

LeonYang 1967

Windows用户必看:如何在WSL中完美安装CosyVoice的ttsfrd依赖(附避坑指南)

本文为Windows用户提供了在WSL中部署CosyVoice语音合成模型并解决其关键依赖ttsfrd的完整指南。文章详细介绍了从WSL环境配置、Python环境搭建、模型下载到ttsfrd深度安装与问题排查的全流程,并针对WSL特有的文件系统、权限和GPU支持问题提供了解决方案,帮助开发者高效攻克部署难题。

dell8的博客 248

Flask中的 logging 使用

一、日志等级说明 等级: DEBUG < INFO < WARNING < ERROR < CRITICAL DEBUG : 最详细的日志信息,主要的应用场景问题的诊断,只限于开发人员使用的,用来在开发过程中进行调试 INFO : 详细程度仅次于debug模式,主要来记录关键节点的信息,确定程序是否正常如预期完成,一般的使用场景是重要的业务处理已经结束,我们通过这些INF...

渣渣的夏天 1万+

python爬取巨潮资讯网所有股票年报数据

爬虫获取巨潮资讯网数据

qq_42752524的博客 6117

工业仪表读数识别:YOLO目标检测 + OCR混合方案实战

仪表整体(meter):粗定位整只仪表,用于快速裁剪、排除背景干扰表盘区域(dial):精确的圆形/方形表盘区域,用于后续矫正和读数数字区域(display)/指针(pointer):数显表定位数码管区域,指针表可辅助定位指针为什么要分三级?因为现场仪表安装角度、距离、光照差异极大。先粗检再精检,比一步到位的准确率高很多,也方便后续做透视变换。工业仪表读数识别,技术路线的选择比算法精度更重要。选对了路线,事半功倍;选错了,怎么调都达不到验收标准。几条落地建议:指针表优先传统算法。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 96

[Python学习日记-54] Python 中的日志模块 —— logging

在程序的运行过程中会执行很多操作或者进行很多的交互,也有的时候可能你开发出来的网站会遭到黑客的攻击,这样你就需要去翻程序记录的日志进行朔源,那我们应该要如何记录日志呢?自己编写?如果自己编写就会面临日志格式是否标准、日志信息是否齐全、日志记录功能开发周期长等一系列问题,这显然不太现实,那我们应该怎么办呢?这就要用到 Python 中的 logging 模块了。

JovaZou的成长之路 1041

杰理SDK入门教程(六):自定义按键事件

这篇教程介绍了在杰理AC695N芯片上实现自定义按键功能的完整流程,包含三个核心步骤:首先在key_event_deal.h文件中添加按键枚举定义;然后在adkey_table.c配置按键映射表,按模式和行为类型设置按键值;最后在app_common.c的消息处理函数中添加自定义按键逻辑。教程强调需注意不同模式按键表的列定义差异,并提供了具体代码示例,最后指导完成编译测试验证。全文结构清晰,配有关键代码截图,适合开发者快速上手自定义按键功能开发。

qq_42014563的博客 1018

python 的日志logging模块学习

1.可以直接在脚本中显示,不过意义不大: import logging logging.debug(''This message should go to the log file') logging.warning('Watch out!') # will print a

Yatere的天平秤 3万+

雨雾天YOLOv8检测拉胯?暗通道去雾+上下文注意力双优化,mAP从58%飙到79%,暴雨也能看清车牌

室外交通监控:高速、省道的雨雾天检测,重点解决小车、货车漏检;车载ADAS系统:雨天行车时的前方车辆、行人识别,需实时性(<40ms);隧道出入口:明暗交界+雾天的复杂场景,暗通道能平衡亮度。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1380

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Python 的日志学习——logger模块

转自:https://www.cnblogs.com/yyds/p/6901864.html Python之日志处理(logging模块) 本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging四大组件记录日志 配置logging的几种方式 向日志输出中添加上下文信息 参考文档 一、日...

lxin_liu的博客 695

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

python日志模块_使用Python打印日志-日志记录模块

python日志模块In this tutorial, we will learn what is logging? (basics of logging), how we can print logs in python and the different log levels that should be used while printing logs. 在本教程中,我们将学习什么是日志记...

cunfen6312的博客 2032

深度学习工具包 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")

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Python常用模块 之 logging:日志模块_python中日志模块longging 难不难学

软件开发中通过日志记录程序的运行情况是一个开发的好习惯,对于错误排查和系统运维都有很大帮助。Python标准库自带日志模块,程序的日志功能直接调用标准库的日志模块即可通过日志,开发者可以清楚的了解发生了哪些事件,包括出现了哪些错误。

m0_61408947的博客 1369

Python 中的日志(logging)模块基础与实战

在软件开发过程中,日志是一项至关重要的功能,它可以帮助我们追踪程序的执行过程、排查问题并记录关键信息。Python 提供了一个强大且灵活的日志模块,即 `logging` 模块,它允许我们以结构化的方式管理和记录日志信息。在本文中,我们将深入了解 `logging` 模块的基础知识,并通过实际代码示例演示其用法。

一键难忘的博客 6250

Python常用模块 之 logging:日志模块_python中日志模块longging 难不难学(1)

result1 = ‘第一个函数运行OK’result2 = ‘第二个函数运行OK’result4 = ‘第四个函数运行OK’result5 = ‘第五个函数运行OK’result1 = ‘第一个函数运行OK’result2 = ‘第二个函数运行OK’result4 = ‘第四个函数运行OK’result5 = ‘第五个函数运行OK’result1 = ‘第一个函数运行OK’result2 = ‘第二个函数运行OK’result4 = ‘第四个函数运行OK’result5 = ‘第五个函数运行OK’

817

Python 日志模块学习-logging模块使用

一.为什么需要使用日志Logging模块,而不用print函数直接输出调试信息? 1.如用print函数输出日志信息,调试结束后需要一个个去注释删除,工作量很大,很容易出错 2.分不清哪些是调试输出,哪些是程序输出,清理日志输出容易搞错程序结构 日志消息的好处在于,你可以随心所欲地在程序中想加多少就加多少,稍 后只要加入一次logging.disable(logging.CRITICAL)调用,就可以禁止日志。 二.如何使用日志模块,输出到屏幕,输出到文件 输出到文件 logging.b.

kingsai2012的博客 992
上一篇: Python面试的一些心得,与Python练习题分享
下一篇: 关于Python中的错误与异常,你是否了解的够仔细?
清风Python
博客等级 码龄7年 406粉丝 267原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值