Flask项目使用Oracle数据库踩坑指南——数据库连接池配置

flask——数据库连接池、wtfroms、信号、多app应用、flask-script 数据库连接池、wtfroms、信号、多app应用、flask-script 阅读详情

概述

为了尝试快速开发,使用Flask框架构建了web项目,但因需要适配Oracle数据库,从而折腾出一堆问题。
flask项目一般使用 flask-sqlalchemy 基于 SQLAlchemy中间件实现多种类型数据库的适配,Oracle也在其中。
本文为踩坑指南的第二篇。

配置连接池创建连接的一般过程

在Flask项目的配置文件中,可通过设置常量的方式来告知SQLAlchemy连接数据库的配置参数。
配置文件示例:

import os
from sqlalchemy.pool import QueuePool

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'some complicate strings'
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ENGINE_OPTIONS = {
        'poolclass': QueuePool,
        'max_overflow': 5,   # 超过连接池大小外最多可创建的连接
        'pool_size': 20,  # 连接池大小
        'pool_timeout': 5,  # 池满后,线程的最多等待连接的时间,否则报错
        'pool_recycle': 1200,  # 多久之后对线程池中的线程进行一次连接的回收(重置)—— -1 永不回收
        'pool_pre_ping': True
    }
    
    @staticmethod
    def init_app(app):
        pass

class developmentConfig(Config):
    """开发环境配置"""
    SQLALCHEMY_DATABASE_URI = ""  # 数据库连接字符串

class ProductionConfig(Config):
    """生产环境配置"""
    SQLALCHEMY_DATABASE_URI = ""  # 数据库连接字符串

config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig
}

然后,在app中加载配置信息:

from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
conf = config['development']
app.config.from_object(conf)

db = SQLAlchemy()
db.init_app(app)

之后,即可在功能模块中通过conn = db.session()建立连接并执行增删改查操作。

一般情况下,对于MySQL、SQLite等数据库,可以通过SQLALCHEMY_ENGINE_OPTIONS 来配置数据库连接池。默认情况下,flask_sqlalchemy通过调用sqlalchemy.create_engine方法创建连接。

查阅flask_sqlalchemy源码和SQLAlchemy 官方文档,可以发现,flask_sqlalchemy 在create_engine时,有如下注释:

# flask_sqlalchemy.__init__.py 1091
    def create_engine(self, sa_url, engine_opts):
        """
            Override this method to have final say over how the SQLAlchemy engine
            is created.

            In most cases, you will want to use ``'SQLALCHEMY_ENGINE_OPTIONS'``
            config variable or set ``engine_options`` for :func:`SQLAlchemy`.
        """
        return sqlalchemy.create_engine(sa_url, **engine_opts)

注释中提到:create_engine这个方法可以被覆盖,这取决于最终如何创建SQLAlchemy engine。大部分情况下,可以通过配置变量SQLALCHEMY_ENGINE_OPTIONS来实现。其中,sa_url即连接字符串。sqlalchemy根据连接字符串,解析出数据库类型,并调用不同的方法实现数据库连接。

通过engine创建数据库连接及使用示例:

with engine.connect() as connection:
    connection.execute(text("insert into table values ('foo')"))
    connection.commit()

连接Oracle数据库时发生的问题

但是假如使用Oracle数据库及cx_Oracle方式(数据库连接字符串以oracle+cx_oracle://开头),则以上配置方法往往无法使得数据库连接池生效,导致经过一段时间后,session失效,项目请求后台无响应。报错信息如下:

ERROR 2022-01-11 21:04:03 base.py[240]: Exception closing connection <cx_Oracle.Connection to ...db_connect_string>
Traceback (most recent call last):
  File "/.../flask_admin/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 238, in _close_connection
    self._dialect.do_close(connection)
  File "/.../flask_admin/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 673, in do_close
    dbapi_connection.close()
cx_Oracle.DatabaseError: DPI-1080: connection was closed by ORA-3113

报错的代码:

    def _close_connection(self, connection):
        self.logger.debug("Closing connection %r", connection)

        try:
            self._dialect.do_close(connection)  # 报错代码行,在关闭连接时抛出异常
        except Exception:
            self.logger.error(
                "Exception closing connection %r", connection, exc_info=True
            )

推测为Oracle数据库连接已中断,但sqlalchemy在超过pool_recycle配置的时间时试图关闭连接,从而发生异常。
无论如何调整 SQLALCHEMY_ENGINE_OPTIONS配置项,都无法解决此问题。

改用cx_oracle.SessionPool自有连接池

然后,阅读sqlalchemy源码,并从中找到了如下注释:

# sqlalchemy/dialects/oracle/cx_oracle.py 98
"""
Using cx_Oracle SessionPool
---------------------------

The cx_Oracle library provides its own connectivity services that may be
used in place of SQLAlchemy's pooling functionality.    This can be achieved
by using the :paramref:`_sa.create_engine.creator` parameter to provide a
function that returns a new connection, along with setting
:paramref:`_sa.create_engine.pool_class` to ``NullPool`` to disable
SQLAlchemy's pooling::

    import cx_Oracle
    from sqlalchemy import create_engine
    from sqlalchemy.pool import NullPool

    pool = cx_Oracle.SessionPool(
        user="scott", password="tiger", dsn="oracle1120",
        min=2, max=5, increment=1, threaded=True
    )

    engine = create_engine("oracle://", creator=pool.acquire, poolclass=NullPool)

The above engine may then be used normally where cx_Oracle's pool handles
connection pooling::

    with engine.connect() as conn:
        print(conn.scalar("select 1 FROM dual"))

"""

其中提到了cx_oracle 自有连接池功能,并给出了示例代码。同时,若使用其自有连接池功能,应设置sqlalchemy的poolclass为NullPool,即无连接池模式。简单来说,就是不使用sqlalchemy的连接池,转而使用cx_oracle.SessionPool连接池。

因此,通过覆盖 create_engine方法,可实现此功能:

class OracleSqlAlchemy(SQLAlchemy):
    def create_engine(self, sa_url, engine_opts):
        import cx_Oracle
        from sqlalchemy import create_engine
        from sqlalchemy.pool import NullPool
        from sqlalchemy.engine import url as _url

        # create url.URL object
        u = _url.make_url(sa_url)
        pool = cx_Oracle.SessionPool(
            user=u.username, password=u.password, dsn=f'{u.host}:{u.port}/{u.database}',
            min=2, max=5, increment=1,
            timeout=1200,  # 闲置会话关闭前的等待时间
            getmode=cx_Oracle.SPOOL_ATTRVAL_TIMEDWAIT,
            wait_timeout=5,  # 池满后创建新会话的等待时间
            threaded=True
        )

        engine = create_engine("oracle://", creator=pool.acquire, poolclass=NullPool)
        return engine

然后,在app初始化时,用如下方式初始化db连接:

db = OracleSqlAlchemy()
db.init_app(app)

经过实际测试,flask项目不再发生后台无响应的情况。

Python绑定变量操作Oracle数据库连接池 # -*- coding: utf-8 -*- # @Time : 2020/8/13 5:28 下午 # @Author : ml # @modify : wjh # @FileName: OraclePool.py # @Software: PyCharm # 基于cx_Oracle自带SessionPool连接池, 线程中使用, 则配置threaded=True # 官方文档摘要: # Oracle Real-World Performance Group的建议是使用固定大小的连接池。mi. 阅读详情

相关推荐

Python后端开发实战指南:Django/Flask/FastAPI部署与数据库配置

Python后端开发是构建现代Web服务的核心能力,其本质是将HTTP协议、应用框架、数据库交互与系统部署有机整合的技术实践。理解Django的MTV模式、Flask的应用工厂机制或FastAPI的类型驱动路由,只是起点;真正决定项目成败的是虚拟环境隔离、多环境配置管理、数据库连接池调优及Gunicorn+Nginx进程协作等底层原理。这些技术价值体现在提升开发一致性、保障生产稳定性、降低运维复杂度,并直接支撑API服务、内部管理系统、中小型企业后台等典型应用场景。本指南聚焦真实工程现场,覆盖Python后

weixin_30314813的博客 492

CX_ORACLE SESSIONPOOL

import cx_OracleoraPool=cx_Oracle.SessionPool(user='crystal',password='crystal',dsn='10.14.250.29/oratest',min=1,max=500,increment=1)def oraConn(oraSql):    conn=oraPool.acquire()    cursor=conn.curso

danevc的博客 2607

Flask入门与实战:从零构建可部署的Python Web应用

Flask是一个轻量级Python Web框架,以显式设计、低侵入性和高可控性著称,其核心原理是将WSGI应用封装为可扩展的路由系统,不强制约定、不隐藏中间件,使开发者能直面HTTP请求生命周期。这种设计赋予它极强的技术价值:快速验证MVP、适配前后端分离架构、便于调试与教学实践。典型应用场景包括内部工具系统、数据看板、Vue/React后端API服务及教学平台(如头歌)的Web开发实验。本文围绕Flask环境搭建、路由机制、模板渲染、数据库操作与生产部署五大关键环节,结合conda虚拟环境、原生SQLAl

abcyan1235的博客 449

Flask连接ORACLE数据库

1.安装数据库 2.创建账号 3.赋予权限 grant create session to chj; grant connect,resource,dba to chj; grant all privileges to chj; from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__...

神仙哥哥 4784

Python连接MySQL生产实战:连接池、字符集、事务与批量插入避坑指南

Python连接MySQL是Web开发和数据工程的基础能力,但真实生产环境远非‘pip install + 三行代码’所能覆盖。其核心涉及数据库连接管理、字符编码统一、事务一致性控制、时区处理及批量操作性能优化等关键环节。尤其在高并发、长周期服务(如Django/Flask后端、Celery任务)中,PyMySQL与mysql-connector-python的选型差异、连接池参数误配、utf8mb4未全链路生效、datetime时区错位等问题极易引发凌晨告警、数据乱码或事务丢失。本文基于金融、电商等高可用

weixin_34391445的博客 401

掌握Flask后端的数据库连接池管理

在Flask后端开发中,数据库操作是非常常见的需求。每次请求都创建和销毁数据库连接会带来较大的开销,影响应用的性能。数据库连接池可以有效解决这个问题,它预先创建一定数量的数据库连接,当有请求需要数据库操作时,直接从连接池中获取连接,使用完毕后归还到连接池,避免了频繁创建和销毁连接的开销。本文的目的就是帮助开发者掌握在Flask中如何管理数据库连接池,包括连接池的创建、使用和维护,以及如何优化连接池的性能。范围涵盖了常见的数据库如MySQL、PostgreSQL等在Flask中的连接池实现。

架构师的AI之路,分享AI应用开发架构的学习与实践。 754

基于 oracle 的 flask 项目(一)——配置项目

一般印象,flask 项目适合做一些短小精悍的项目,特别是与 sqlite、mysql 等数据库结合很是般配。但是在一些大公司,特别是一些金融行业等国企公司,还是以 oracle 居多,那么,这个小辣椒(flask)就无用武之地了吗?No, No, No… 下面将以 flask_oracle 项目为例,对 flask 的功能进行一个详细的讲解。 项目描述 实现登录功能,基...

藕丝空间 3421

flask-oracle:使用oracle进行连接测试

烧瓶Oracle 使用oracle进行连接测试 安装和使用 Requer Python 3.4 e Pipenv 虚拟环境python3 -m venv .venv 虚拟环境 Windows .venv\Scripts\activate Linux或Mac source .venv\bin\activate pipenv install Crie o arquivo .env ( ) Rodeaplicaçãopython python src/processo_automatico.py 在SO上安装Oracle驱动程序 下载InstantClient-basic-linux.x64-12.2.0.1.0.zip 将其解压缩到/ opt / oracle目录: sudo mkdir -p /opt/oracle cd /opt/oracle unzip ~/Downl

Flask应用篇-数据库:SQLAlchemy 与 Flask_Sqlalchemy

目录 一、简介 二、使用 (一)采用sqlalchemy方式 1. 基本:通过SQLAlchemy连接数据库并取数据 2. ORM介绍(SQLAlchemy强大的地方) (二)、采用Flask-SQLAlchemy方式 一、简介 SQLAlchemy是一个基于Python实现的ORM框架。该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是...

bluebloodye的专栏 2734

GAMES101:MacOS作业环境搭建

查看gcc/clang的位置产看gcc/clang的版本1.1.2 安装cmake。

weixin_38844255的博客 715

OKCC呼叫中心部署实战指南:从零搭建高效外呼系统

本文提供OKCC呼叫中心系统的完整部署实战指南,从服务器选型、操作系统准备到详细安装步骤和性能优化,帮助企业从零搭建高效外呼系统。重点介绍FreeSWITCH核心组件的安装配置技巧,以及常见问题排查方法,助力企业提升客户服务效率。

weixin_29275257的博客 163

Flask --(25)Flask 中数据库的配置

安装 flask-sqlalchemy pip install flask-sqlalchemy 如果连接的是 mysql 数据库,需要安装 mysql pip install flask-mysqldb 使用 Flask-sqlalchemy 管理数据库 在Flask-SQLAlchemy中,数据库使用URL指定,而且程序使用的数据库必须保存到Flask配置对象的SQLALCHEMY_DAT...

Enjolras_fuu的博客 1288

深入解析Incapsula reese84的生成机制与绕过策略

本文深入解析了Incapsula reese84的生成机制与绕过策略。reese84是一种基于客户端JavaScript挑战的Web安全防护,通过动态算法收集浏览器指纹并生成令牌Cookie。文章详细拆解了其两步验证流程,并提供了使用无头浏览器、逆向JS模拟请求以及Token维护等实战绕过方法,帮助开发者和安全研究人员应对自动化访问拦截。

weixin_29256771的博客 443

Spring Boot 集成 JWT 实战:从签发校验到安全加固的完整指南

JWT(JSON Web Token)是一种无状态的令牌规范,通过 Header、Payload、Signature 三段式结构实现签名防篡改。其核心原理是服务端不存储会话状态,所有用户信息编码在 Token 中,由客户端携带并在服务端验签解析。在 Spring Boot 项目中,JWT 常用于接口认证与授权,结合拦截器可实现请求级用户上下文管理。实际落地时需关注密钥管理、过期时间、刷新机制及算法混淆攻击防范。本文围绕 Spring Boot 集成 JWT 的完整流程,从 Token 签发、校验、续签,到生

weixin_34348174的博客 236

从《新程序员》系列看程序员职业发展趋势与成长路径

在信息技术日新月异的当下,软件开发行业蓬勃发展,程序员作为行业的核心力量,其成长与发展路径备受瞩目。《新程序员》系列杂志应运而生,以其前瞻性的视角、丰富多元的内容,为广大程序员尤其是新程序员提供了洞察行业趋势、学习前沿技术、汲取前辈经验的宝贵窗口。该系列杂志由优快云精心打造,自推出以来,便在开发者群体中引发了强烈反响。《新程序员》系列内容涵盖了从基础技术知识的深入解读,到行业前沿趋势的精准预测;从优秀开发者的成长历程分享,到各大企业数字化转型的实践案例剖析等多个维度。

AllenLV的博客 2257

资金穿透分析

我们把准备好的银行数据导入到软件中,导入具体步骤这里不做详解,大家可以通过“清林情报分析师”公众号,查看操作视频第二节

清林情报分析师 3489

flask项目之SQLAlchemy映射构建(3)

目录1 简介2 安装3 数据库连接设置4 模型类字段与选项5 构建模型类映射5.1 首先需要创建SQLAlchemy对象:5.2 定义模型类 1 简介 SQLAlchemy是Python编程语言下的一款开源软件。提供了SQL工具包及对象关系映射(ORM)工具,使用MIT许可证发行。 SQLAlchemy“采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型”。 ...

汪云辉的博客 959

从养虾到退坑:OpenClaw 卸载不留残留,一步到位

文章摘要: 本文提供OpenClaw软件的完整卸载指南,适用于Windows、macOS和Linux系统。内容包含卸载前的数据备份步骤(配置文件、日志、插件列表),以及详细的卸载脚本。Windows版通过批处理文件删除程序文件、注册表项和环境变量;macOS/Linux版则提供shell脚本,涵盖服务停止、软件包卸载、配置清理等步骤。特别强调要删除所有用户数据(包括多用户环境),确保系统无残留。文末建议重启计算机以使更改生效,实现"一步到位"的彻底卸载。

一键难忘的博客 298

快马AI编程实战:5分钟用自然语言生成Oracle数据库管理系统

最近在做一个企业级员工管理系统的项目,需要用到Oracle数据库。作为全球领先的企业级数据库,Oracle的高性能和可靠性确实没得说,但传统开发中连接配置和CRUD操作总让人头疼。整个项目从设计到上线只用了不到1小时,特别是处理Oracle这种专业数据库时,不用再翻文档查各种参数配置,AI生成的代码开箱即用。对于需要快速验证Oracle项目可行性的场景特别有帮助。,不用搭建本地环境就能完成企业级应用开发,部署过程比传统方式省心太多。,用自然语言就能生成全套代码,分享下我的实战经验。

SnowflakeJaguar14的博客 844

Dify平台隐患url:/console/api/remote-files/upload暴露高危漏洞,配置nginx htpasswd模块认证机制屏蔽解决

内部网络探测: 攻击者可通过SSRF扫描内网服务云元数据访问: 可能访问AWS/Aliyun/腾讯云等元数据服务服务端请求伪造: 以服务器身份发起任意HTTP请求。

CN_Eden 1317

YOLOv11改进 | 特殊场景检测篇 | 低照度图像增强网络SCINet改进黑暗目标检测(全网独家首发)

本文给大家带来的改进机制是低照度图像增强网络SCINet,SCINet(自校正照明网络)是一种专为低光照图像增强设计的框架。它通过级联照明学习过程和权重共享机制来处理图像,优化了照明部分以提升图像质量。我将该网络集成在YOLOv11的主干上针对于图像的输入进行增强,同时该网络的并不会增加参数和计算量,基本和普通的网络结构保持一致,同时该结构支持自定义调节层数,来控制图像增强的效果 ,非常适合想要在黑夜目标检测领域发表文章的读者,该基本网络不会影响模型的速度。欢迎大家订阅我的专栏一起学习YOLO!

Snu77的博客 2207

05-Flask数据库集成ORM与迁移管理深度解析

"""抽象基类模型"""__abstract__ = True # 声明为抽象基类,不创建表"""保存模型实例""""""删除模型实例""""""根据ID查询""""""查询所有记录""""""转换为字典""""""约束演示模型"""# 表级主键约束(复合主键)# )# 表级唯一约束# 单列唯一约束(也可以在Column中使用unique=True)# 复合唯一约束# 检查约束# 索引定义。

oZiDingXiang的博客 584

计算机控制技术及应用

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

python db end-of-file记录

1.异常信息 sqlalchemy.exc.OperationalError: (cx_Oracle.OperationalError) ORA-03113: end-of-file on communication channel sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-03150: end-of-file on communication channel for database link 2.涉及的module Fl.

Jalen备忘录 644

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

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

flask ORM操作

我们后面会把模型创建到单独的文件中,但是现在我们先把模型类写在manager.py文件中。

blank_memory_的博客 981

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

SQLAlchemy终极指南:5个技巧构建高性能Python数据库应用

SQLAlchemy是Python生态中最强大的数据库工具包,为开发者提供了完整的ORM和SQL表达式语言解决方案。作为Python数据库编程的瑞士军刀,它支持多种数据库后端,提供灵活的查询构建和高效的数据映射功能,帮助开发者快速构建可扩展的企业级应用。无论你是构建Web应用、数据分析工具还是自动化系统,SQLAlchemy都能显著提升数据库操作的效率和代码质量。 ## 项目概述与核心价值 S

gitblog_00577的博客 895
上一篇: Flask项目使用Oracle数据库踩坑指南——ID自增与Cast自动类型转换
下一篇: 基于 Jasypt对 Springboot 配置信息进行加密
Pierre_
博客等级 码龄19年 2262粉丝 89原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pierre_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值