python备份mongodb数据库全量备份

Ubuntu 14.04 下 MongoDB 备份实战:mongodump/mongorestore 可靠性解析 MongoDB 备份是保障数据安全的基础能力,其核心原理在于通过 wire protocol 客户端工具实现逻辑层数据导出,不依赖文件系统权限或运行时环境。mongodump 作为官方原生工具,以 BSON 序列化方式拉取文档,具备跨版本兼容、低依赖、高可控等技术价值,特别适用于老旧系统如 Ubuntu 14.04 和 MongoDB 3.x 的遗产环境。在运维实践中,它广泛应用于教务平台、MES 系统等无法升级的关键业务节点,支撑灾备恢复、数据迁移与合规审计等场景。本文聚焦 mongodump/mongo 阅读详情

python备份mongodb数据库全量备份

2025-12-02

import os
import json
from pymongo import MongoClient
from bson import ObjectId, datetime
from typing import Optional, Dict, List


# -------------------------- 自定义 JSON 编码器(处理 MongoDB 特殊类型)--------------------------
class MongoJSONEncoder(json.JSONEncoder):
    """解决 MongoDB 特殊数据类型(ObjectId、datetime 等)无法直接序列化的问题"""

    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)  # ObjectId 转为字符串
        elif isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")  # datetime 转为字符串
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")  # date 转为字符串
        elif isinstance(obj, bytes):
            return obj.decode("utf-8", errors="ignore")  # bytes 转为字符串
        elif isinstance(obj, (set, frozenset)):
            return list(obj)  # 集合转为列表
        # 其他类型默认处理
        return super(MongoJSONEncoder, self).default(obj)


# -------------------------- 核心导出函数 --------------------------
def export_mongodb_to_json(
    mongo_uri: str = "mongodb://localhost:27017/",
    username: Optional[str] = None,
    password: Optional[str] = None,
    auth_db: str = "admin",
    output_root: str = "./mongodb_export",
    batch_size: int = 1000,
    indent: int = 2,
) -> None:
    """
    导出 MongoDB 所有数据库和集合到 JSON 文件

    参数说明:
    - mongo_uri: MongoDB 连接地址(默认本地)
    - username: 认证用户名(可选)
    - password: 认证密码(可选)
    - auth_db: 认证数据库(默认 admin)
    - output_root: 导出根目录(默认 ./mongodb_export)
    - batch_size: 分批导出大小(避免大数据量占用过多内存)
    - indent: JSON 格式化缩进(0 为紧凑模式,默认 2 空格)
    """
    # 1. 连接 MongoDB
    try:
        client_kwargs = {}
        if username and password:
            client_kwargs["username"] = username
            client_kwargs["password"] = password
            client_kwargs["authSource"] = auth_db

        client = MongoClient(mongo_uri, **client_kwargs)
        print(f"✅ 成功连接 MongoDB: {mongo_uri}")
    except Exception as e:
        print(f"❌ MongoDB 连接失败: {str(e)}")
        return

    # 2. 创建根导出目录
    os.makedirs(output_root, exist_ok=True)
    print(f"📂 导出根目录: {os.path.abspath(output_root)}")

    # 3. 遍历所有数据库(排除系统数据库)
    system_dbs = {"admin", "local", "config"}
    all_dbs = [db for db in client.list_database_names() if db not in system_dbs]

    if not all_dbs:
        print("⚠️  未找到非系统数据库")
        client.close()
        return

    print(f"📊 发现 {len(all_dbs)} 个非系统数据库: {all_dbs}")

    # 4. 遍历每个数据库的所有集合
    for db_name in all_dbs:
        # 创建数据库对应的文件夹
        db_dir = os.path.join(output_root, db_name)
        os.makedirs(db_dir, exist_ok=True)
        print(f"\n========== 正在导出数据库: {db_name} (目录: {db_dir}) ==========")

        db = client[db_name]
        # 获取所有集合(排除系统集合,如 system.indexes)
        collections = [
            col for col in db.list_collection_names() if not col.startswith("system.")
        ]

        if not collections:
            print(f"⚠️  数据库 {db_name} 无有效集合,跳过")
            continue

        # 5. 导出每个集合到 JSON 文件
        for col_name in collections:
            col = db[col_name]
            total_count = col.count_documents({})  # 集合总文档数
            print(f"📄 集合 {col_name} (共 {total_count} 条数据)")

            # JSON 文件路径
            json_file = os.path.join(db_dir, f"{col_name}.json")

            # 分批查询并写入(避免大数据量内存溢出)
            with open(json_file, "w", encoding="utf-8") as f:
                f.write("[")  # JSON 数组开始
                first_batch = True  # 标记是否为第一批(避免末尾多余逗号)

                for skip in range(0, total_count, batch_size):
                    # 分批查询数据
                    batch_docs = list(col.find().skip(skip).limit(batch_size))

                    # 序列化并写入
                    for doc in batch_docs:
                        if not first_batch:
                            f.write(",")  # 非第一批前加逗号
                        # 使用自定义编码器序列化 MongoDB 特殊类型
                        json.dump(
                            doc,
                            f,
                            cls=MongoJSONEncoder,
                            ensure_ascii=False,
                            indent=indent,
                        )
                        first_batch = False

                        if indent == 0:
                            f.write("\n")  # 紧凑模式下换行,避免一行过长

                f.write("]")  # JSON 数组结束

            print(f"✅ 导出完成: {json_file}")

    # 6. 关闭连接
    client.close()
    print(f"\n🎉 所有数据库导出完成!根目录: {os.path.abspath(output_root)}")


# -------------------------- 执行导出 --------------------------
if __name__ == "__main__":
    # 配置参数(根据实际情况修改)
    CONFIG = {
        "mongo_uri": "mongodb://192.168.28.99:27017/",  # 本地 MongoDB 地址
        # "mongo_uri": "mongodb://192.168.1.100:27017/",  # 远程 MongoDB 地址
        "username": None,  # 无认证则设为 None
        "password": None,  # 无认证则设为 None
        # "username": "your_admin",  # 有认证时填写用户名
        # "password": "your_password",  # 有认证时填写密码
        "auth_db": "admin",  # 认证数据库(默认 admin)
        "output_root": "./mongodb_export",  # 导出根目录
        "batch_size": 1000,  # 每批导出 1000 条(可根据内存调整)
        "indent": 4,  # JSON 缩进(0=紧凑,2=美观)
    }

    # 执行导出
    export_mongodb_to_json(**CONFIG)
MongoDB Atlas CLI:云数据库自动化的核心命令行工具 MongoDB Atlas CLI 是面向现代云原生环境的命令行接口,本质是 Atlas REST API 的轻量级、可审计封装。它不替代图形界面,而是提供确定性、可脚本化、可集成的基础设施操作能力,支撑 database automation 和 infrastructure as code 实践。相比 SDK 的启动开销与 Terraform 的声明式局限,CLI 在动态运维、即时调试和 CI/CD 快速嵌入方面具备不可替代性。典型应用场景包括多集群批量管理、生产环境用户权限精细化控制、备份导出与恢复验 阅读详情

相关推荐

Ubuntu安装MongoDB官方版完整指南:避坑、配置与生产加固

MongoDB 是一款面向文档的 NoSQL 数据库,其核心原理基于 BSON 格式存储与 WiredTiger 存储引擎,具备高并发读写和灵活的水平扩展能力。技术价值体现在去中心化架构、动态模式支持及原生分片能力,广泛应用于实时分析、内容管理、IoT 数据平台等场景。但在 Ubuntu 系统中,因官方源与社区包长期混用、版本兼容性断层及 systemd/gpg 密钥机制演进,导致 `apt install mongodb` 常见失败、服务无法启动或认证异常。本文聚焦 `mongodb-org` 官方源安装

weixin_34101784的博客 701

mongo数据增量备份php,python mongodb增量备份脚本

python mongodb增量备份脚本首先,需要搭建mongodb副本集,才能进行增量备份,此过程略过本人的构想是每天进行一次备份,这次备份是全量备份还是增量备份取决于最后一次全量备份的时间节点的日志是否已被覆盖(因为oplog的大小是有上限的,所以新的操作会覆盖旧的),如果已被覆盖,则进行全量备份,否则从该时间节点开始进行增量备份。为了方便,每次全量备份完成后会将oplog.bson放到固定的...

weixin_35245427的博客 319

Ubuntu 20.04 下 MongoDB 导入导出实战:备份恢复与数据一致性保障

MongoDB 数据库导入导出是保障数据安全与系统可维护性的基础能力,其核心在于理解 BSON/JSON 格式转换原理、权限控制链路及跨平台兼容性机制。在 Linux 服务器环境中,尤其 Ubuntu 20.04 这类 LTS 发行版,需兼顾 systemd 资源限制、AppArmor 安全策略、locale 编码设置等底层约束,才能实现可靠的数据迁移与故障回滚。技术价值体现在支持生产级定时备份、CI/CD 初始化、增量同步及类型保真恢复;典型应用场景包括线上故障快速回滚、测试环境数据注入、多集群间无损迁移

weixin_33866037的博客 380

mongodb增量或全量备份脚本

mongodb备份脚本,可以全量或增量进行备份,两年前所写,目前网上mongodb备份相关的脚本也还是很少。 功能 定期对mongodb数据库数据进行全量备份或增量备份(副本集架构),并可以压缩上传到阿里云oss(本地会先生成压缩包,可以设置不上传oss)。 脚本运行环境 使用python语言编写,需安装python,pymongo和mongodb shell客户端(测试时使用...

weixin_30565199的博客 648

Ubuntu 20.04下MongoDB导入导出生产级实践指南

MongoDB导入导出不仅是命令执行,更是数据模型、序列化机制与系统环境的协同工程。其核心在于理解mongodump/mongorestore(BSON逻辑备份,保真ObjectId/Date/索引)与mongoexport/mongoimport(JSON/CSV结构交换,牺牲语义换通用性)的本质差异。在Ubuntu 20.04环境中,systemd服务管理、ulimit文件描述符限制、locale编码设置等底层约束,会静默破坏数据一致性与完整性。掌握工具选型决策树、权限认证配置、oplog增量支持及UT

weixin_33738982的博客 294

MongoDB数据库的备份策略制定

MongoDB作为一款广泛使用的NoSQL数据库,在众多应用场景中存储着关键业务数据。制定合理的备份策略对于保障数据的安全性、完整性和可恢复性至关重要。本文的目的在于为MongoDB用户提供全面的备份策略制定指导,涵盖了备份的各种方法、原理、实际操作以及应用场景等方面,帮助用户根据自身需求选择合适的备份方案,确保数据在面临各种风险时能够快速恢复。本文将按照以下结构进行组织:首先介绍MongoDB备份的核心概念和它们之间的联系,通过文本示意图和流程图进行清晰展示;

2502_91592937的博客 830

不停机mongo2向mongo3迁移同步

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33963189的博客 253

Python 爬虫实战:爬虫数据的备份与恢复机制

本文针对爬虫数据安全需求,提出"分级备份+多介质存储+自动化校验"的综合备份方案。以豆瓣读书TOP250数据为例,详细设计了MySQL结构化数据的全量/增量备份、MongoDB非结构化数据的快照备份以及本地文件的定时备份机制。通过mysqldump、mongodump等工具实现不同数据类型的备份与恢复,并建立自动化调度、完整性校验和过期清理机制。方案解决了备份冗余、恢复效率低等常见问题,为爬虫数据安全提供了包含全流程校验的完整解决方案,确保数据丢失时可快速恢复。核心价值在于实现数据&qu

2503_91057718的博客 1109

mongodb 备份压缩_mongodb增量/全量备份脚本的实现详解

前言mongodb备份脚本,可以全量或增量进行备份,两年前所写,目前网上mongodb备份相关的脚本也还是很少。下面话不多说了,来一起看看详细的介绍吧功能定期对mongodb数据库数据进行全量备份或增量备份(副本集架构),并可以压缩上传到阿里云oss(本地会先生成压缩包,可以设置不上传oss)。脚本运行环境使用python语言编写,需安装python,pymongo和mongodb shell客户...

weixin_39797393的博客 357

Golang 领域 MongoDB 客户端的备份与恢复方法

在当今数字化时代,数据是企业和应用的核心资产。MongoDB 作为一款广泛使用的 NoSQL 数据库,在众多项目中承担着存储重要数据的任务。在 Golang 开发中,为了确保数据的安全性和可恢复性,需要掌握有效的 MongoDB 客户端备份与恢复方法。本文的目的在于为 Golang 开发者提供全面、深入的指导,使其能够在实际项目中正确运用这些方法。范围涵盖了从基本概念到具体实现,从理论原理到实际应用的各个方面。

AI Agent Harness Engineering 1015

Elasticsearch 8.17.1 JAVA工具类

整理了Elasticsearch8.17最新版的API工具类

weixin_39555954的博客 1125

mongodb备份oplog_mongodb的备份

转载请附原文链接:http://www.cnblogs.com/wingsless/p/5672057.htmlmongodb现在为止还是没有像XtraBackup这样好用的备份工具,因此一般来说会有两种备份办法:拷贝文件和mongodump。拷贝文件这招在MySQL里经常用,但是必须要停掉写入服务,这种办法一般只会用于要进行机器迁移之类的情景,或者停机维护声明发表以后。那么mongodump算是...

weixin_39639965的博客 166

Windows下Cppcheck静态测试全流程:从安装到生成HTML报告的避坑指南

本文详细介绍了在Windows平台下使用Cppcheck进行静态代码分析的全流程,包括环境搭建、插件配置、自动化脚本编写及HTML报告生成。重点解析了MISRA插件集成、常见问题排查以及性能优化技巧,帮助C/C++开发者高效提升代码质量。文章特别针对Windows环境下的路径处理、空格问题等细节提供了实用解决方案。

weixin_29313547的博客 200

mongodb4.2全量定时增量备份python脚本

脚本地址 github https://github.com/thinking24k/mongoscript.git 码云 https://gitee.com/dawn-a/mongoscript.git 功能 脚本启动后立即对mongodb数据库进行本地全量备份,获取oplog时间戳,然后每天定时进行增量备份,脚本已内置定时器,只需要把脚本加入开机启动。所有配置都在脚本内更改,脚本支持跨平台...

1060

【Linux命令大全】006.网络通讯之write命令(实操篇)

Linux write命令摘要 write是Linux系统中用于用户间实时通讯的命令工具,允许向其他登录用户的终端发送消息。主要功能包括: 基本使用:通过write username向指定用户发送消息,Ctrl+D结束输入 终端指定:当用户登录多个终端时,可用write username tty指定目标终端 实用技巧: 使用who查看在线用户 通过管道发送单行消息:echo "内容" | write user 支持多行消息发送和简单聊天会话。

yuhuasheng1997的博客 214

图机器学习(1)——图论基础

图 (Graph) 是一种描述实体间关系的数学结构,几乎在各个领域都有应用。例如,社交网络就是图,其中用户之间的连接取决于一个用户是否“关注”另一个用户。图论,即对图的研究,一直以来广受关注,包含了大量算法、性质分析方法和数学模型,以解析复杂系统的行为特征。本节将介绍图数据结构的核心概念,通过理论阐述与实例演示相结合的方式,理解基础理论用以实践应用。重点介绍用于创建、操作和研究复杂网络结构与功能的 Python 库。

盼小辉丶的博客 9113

MongoDB 增量备份方案

MongoDB本身不支持增量备份,所以这里介绍几种我找到的,或者是自己使用代码实现的方法: 我的环境:集群环境, 如果是分片集群,只好各【分片集群】和【配置服务器集群】分开备份处理,因为使用了Oplog 所以不适合单机环境 一、 Delay server + Oplog replay(延迟节点+Oplog 重现) 二、使用mongosync 同步工具,    它的功能有:

好记忆也需烂博客 1万+

18006.STM32通过SPI读取LAN9253数据

【代码】18006.STM32通过SPI读取LAN9253数据。

写给自己的笔记 556

mongodb的备份

    转载请附原文链接:http://www.cnblogs.com/wingsless/p/5672057.html     mongodb现在为止还是没有像XtraBackup这样好用的备份工具,因此一般来说会有两种备份办法:拷贝文件和mongodump。拷贝文件这招在MySQL里经常用,但是必须要停掉写入服务,这种办法一般只会用于要进行机器迁移之类的情景,或者停机维护声明发表以后。那么m...

weixin_34406061的博客 142

15、远程操作水下航行器(ROV)的非线性控制系统设计

本文探讨了远程操作水下航行器(ROV)的非线性控制系统设计,重点介绍了多变量PID控制、改进的PD控制和滑模控制三种方法。详细阐述了各控制策略的原理、建模与仿真过程,并通过对比分析其在稳态误差、振荡、抖振及跟踪效果等方面的性能表现。文章还提出了针对不同控制方法的优化建议,并给出了选择合适控制策略的决策流程,为ROV高精度运动控制提供了系统性解决方案。

sun99的博客 157

新能源汽车动力总成研发测试技术全景深度报告(2025版)

本文所有企业案例数据均来自上市公司财报、工信部备案信息及权威媒体报道,技术参数经第三方检测报告交叉验证。研发测试人员能力矩阵重构(T型人才进阶路径)[10] 全球动力总成市场2035年预测报告。[9] NI电动汽车HIL测试架构技术文档。[3] 东风汽车智能化研发体系深度报告。[5] 混合动力测功机发明专利技术细节。[1] 领克动力总成试验中心技术解析。[7] 新能源汽车产业迭代趋势白皮书。测试架构师-数字工程。测试架构师-安全合规。测试架构师-人工智能。

优快云-新能源汽车研发测试专业博主 777

C/C++科学计数法全解析:从%g到strtod的实战避坑指南

浮点数是计算机中表示实数的基本方式,其精度范围和格式化规则常常成为开发者的隐性陷阱。科学计数法作为沟通人类语言与机器内部表示的有效工具,能显著提升数值表达的可读性与准确性。在C/C++中,无论是字面量定义、printf家族格式化,还是字符串与浮点数的相互转换,科学计数法都扮演着关键角色。理解%e、%g等格式符的默认行为,掌握strtod、std::stod等解析函数的边界判断,以及注意不同编译器在尾零、指数位数上的平台差异,是工程实践中避免数据错乱、线上事故的必备技能。在算法竞赛、数据处理、日志输出和配置解

weixin_34367257的博客 359

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

数据库的自我修炼——阿里云MongoDB备份恢复功能说明和原理介绍

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33809981的博客 309

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

MongoDB健康检查三维度:复制、性能与备份的生产级实践

MongoDB健康检查是保障高可用与数据一致性的基础能力,其核心在于对复制状态、运行性能和备份有效性三大技术维度的持续观测与干预。复制健康决定故障切换可靠性,依赖oplog窗口、节点间延迟及心跳连通性等可量化指标;性能健康影响用户响应体验,需结合操作节奏、慢查询执行计划、内存页错误与锁竞争综合诊断;备份健康则直接关联RPO/RTO达成能力,必须通过真实恢复验证而非仅确认备份文件存在。本文基于金融、电商等严苛场景提炼出可落地的检查逻辑、阈值设定与根因排查路径,覆盖rs.status深度解析、mongostat

weixin_33726313的博客 595

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

别再只懂基础命令了!MongoDB备份恢复的5个高阶场景与自动化脚本编写

本文深入探讨MongoDB备份恢复的5个高阶场景,包括自动化脚本编写、容器化环境备份、云原生集成、分片集群管理及企业级备份系统构建。通过实战案例和脚本示例,帮助开发者掌握mongodump和mongorestore的高级用法,实现数据备份的自动化与容灾能力提升。

weixin_33698823的博客 336
上一篇: scrapy核心组件工作流程
下一篇: MiMo-V2-Flash
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值