MongoDB小课堂: 深度掌握 mongostat 与 mongotop 的监控艺术

字节开源 DeerFlow 2.0:从 Deep Research 到 Super Agent Harness 的进化之路 GitHub Trending 冠军项目,字节跳动完全开源的超级智能体框架。支持子代理、沙箱执行、长期记忆、技能扩展,可完成从几分钟到几小时的复杂任务。本文深度解析架构设计、安装实战、技能系统,并附上独家配置指南。 阅读详情

监控工具概述与权限配置


MongoDB 提供核心诊断工具 mongostat(服务器级资源监控)和 mongotop(集合级读写分析),用于实时追踪性能瓶颈

执行命令需 clusterMonitor 角色(仅授权监控接口访问,禁止数据修改)

权限配置流程

use admin
db.createUser({
  user: "monitorUser",
  pwd: "securePassword",  # 通过环境变量注入更安全
  roles: ["clusterMonitor"]  # 关键权限!
  # roles: [{ role: "clusterMonitor", db: "admin" }]
})
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
 
@Injectable()
export class UserService {
  constructor(@InjectModel('User') private userModel: Model<any>) {}
 
  async createMonitorUser() {
    await this.userModel.create({
      user: 'monitorUser',
      pwd: process.env.MONITOR_PWD,  // 环境变量注入 
      roles: [{ role: 'clusterMonitor', db: 'admin' }]
    });
  }
}

要点

  • 用户必须在 admin 库创建,覆盖集群级权限
  • 生产环境需启用 TLS 加密连接
  • 遵循最小权限原则,避免授予 find/insert 等操作权

mongostat:实时数据库状态监控


1 )基础命令与输出解析

mongostat --host localhost:27017 \
         -u monitorUser -p ${{MONITOR_PWD}} \
         --authenticationDatabase admin

输出说明(每秒刷新):

字段含义故障阈值
command每秒执行的命令数突增需排查慢查询
dirty缓存中待写入磁盘的数据比例>20% 预示 I/O 瓶颈
used缓存中活跃数据比例>90% 需扩容内存
vsize虚拟内存使用量 (MB)持续增长且 > 物理内存 200% = 内存泄漏风险
接近系统虚拟内存上限 = OOM 风险
res常驻内存使用量 (MB)>70% 物理内存总量 = 预警
>90% 物理内存总量 = 紧急扩容
conn当前开放连接数持续增长=连接泄漏

2 ) 参数定制化

参数功能示例命令
[间隔秒数]抓取频率调整mongostat ... 3
--rowcount限制抓取次数mongostat ... --rowcount 5 3
-o="字段列表"筛选输出字段mongostat -o="command,dirty,conn" ...
每3秒采样,共5次,仅显示关键字段 
mongostat -o "command,dirty,conn" 3 --rowcount 5 ...
 
输出JSON格式(适合自动化分析)
mongostat --json ...

3 )综合示例

mongostat 动态报告数据库进程的多维度状态指标。基础命令需指定连接参数:

mongostat --host localhost --port 27017 \ 
          --username monitorUser --password securePassword \
          --authenticationDatabase admin

关键特性与参数解析:

  • 默认抓取频率:1 秒/次,输出包括 command(每秒命令数)、dirty(未刷新的缓存比例)、used(已使用缓存比例)、vsize(虚拟内存用量)、res(常驻内存用量)、conn(当前连接数)及 time(时间戳)。
  • 调整抓取频率:通过追加数字参数修改间隔(单位:秒)。例如,每 3 秒抓取:
    mongostat --host localhost --port 27017 -u monitorUser -p securePassword --authenticationDatabase admin 3 
    
  • 限制报告次数:--rowcount 参数控制总抓取次数。以下命令每 3 秒抓取,共执行 5 次后自动终止:
    mongostat --host localhost --port 27017 -u monitorUser -p securePassword --authenticationDatabase admin 3 --rowcount 5
    
  • 筛选输出字段:-o 参数指定需关注的指标(逗号分隔)。例如仅显示 command、dirty、conn:
    mongostat -o "command,dirty,conn" --host localhost --port 27017 -u monitorUser -p securePassword --authenticationDatabase admin
    
    指标深度解析:
    • dirty 与 used:诊断缓存健康度的核心参数。dirty 表示待写入磁盘的缓存占比,过高可能预示 I/O 瓶颈;used 反映缓存利用率,持续高位需警惕内存压力。
    • conn:当前活跃连接数,突增可能暗示连接泄漏或负载激增

mongotop:集合级读写耗时分析


1 ) 基础命令与特性

mongotop --host localhost:27017 -u monitorUser ...
  • 输出字段:ns(集合命名空间)、read(读耗时/ms)、write(写耗时/ms)
  • 隐藏集合策略:仅显示最近活跃集合,可通过 db.collection.findOne() 触发可见性

2 )参数扩展

每5秒采样,共8次 
mongotop 5 --rowcount 8 ...
 
过滤特定数据库(如prod库)
mongotop --filter '{ "ns": "/^prod./" }'

3 )综合示例

mongotop 聚焦集合维度的读写操作时间分布,要求相同 clusterMonitor 权限。基础命令:

mongotop --host localhost --port 27017 \
         --username monitorUser --password securePassword \
         --authenticationDatabase admin

核心功能与调优:

  • 活跃集合过滤:仅显示近期有操作的集合。若目标集合未出现,可通过触发操作(如 db.collection.findOne())激活监控。
  • 调整抓取频率:追加数字参数修改间隔(如每 5 秒抓取):
    mongotop --host localhost --port 27017 -u monitorUser -p securePassword --authenticationDatabase admin 5
    
  • 限制报告次数:--rowcount 参数控制输出行数。以下命令每 5 秒抓取,共 5 次后终止:
    mongotop --host localhost --port 27017 -u monitorUser -p securePassword --authenticationDatabase admin 5 --rowcount 5
    

输出示例显示各集合的 read 和 write 耗时(毫秒),idle 表示无活动状态,适用于定位慢查询或负载不均问题。

NestJS 集成实战


1 ) 封装 mongostat 监控服务

import { Injectable, Logger } from '@nestjs/common';
import { exec } from 'child_process';
 
@Injectable()
export class MongoMonitorService {
  private readonly logger = new Logger(MongoMonitorService.name);
 
  async getMongoStat(interval: number): Promise<string> {
    const command = `mongostat --json -o "conn,dirty,used" ${interval} --rowcount 1`;
    return new Promise((resolve, reject) => {
      exec(command, (error, stdout) => {
        if (error) reject(`监控失败: ${error.message}`);
        const { conn, dirty, used } = JSON.parse(stdout);
        // 动态阈值告警
        if (dirty > 20) this.logger.warn(`脏缓存过高: ${dirty}%`);
        resolve(`连接数: ${conn}, 缓存使用率: ${used}%`);
      });
    });
  }
}

或

// NestJS 服务层代码:获取 mongostat 指标  
import { Injectable, Logger } from '@nestjs/common';  
import { exec } from 'child_process';  
 
@Injectable()  
export class MongoMonitorService {  
  private readonly logger = new Logger(MongoMonitorService.name);  
 
  async getMongoStat(): Promise<string> {  
    const command = `mongostat --host localhost:27017 -u monitorUser -p securePassword --authenticationDatabase admin -o "conn,dirty,used" --rowcount 1 --noheaders`;  
    return new Promise((resolve, reject) => {  
      exec(command, (error, stdout) => {  
        if (error) reject(`监控失败: ${error.message}`);  
        const [conn, dirty, used] = stdout.split(/\s+/).filter(Boolean);  
        resolve(`当前连接数: ${conn}, 脏数据比例: ${dirty}%, 缓存使用率: ${used}%`);  
      });  
    });  
  }  
}  

2 ) 自动诊断集合读写延迟,封装 mongotop

async checkCollectionLatency(collectionName: string): Promise<void> {
  const command = `mongotop --json 5 --rowcount 1`;
  exec(command, (error, stdout) => {
    const data = JSON.parse(stdout);
    const target = data.find((item: any) => item.ns.includes(collectionName));
    if (target && (target.read > 100 || target.write > 200)) {
      this.logger.error(`集合 ${collectionName} 延迟异常!读: ${target.read}ms, 写: ${target.write}ms`);
    }
  });
}

或

// 检测集合读写超时  
async checkCollectionLatency(collectionName: string): Promise<void> {  
  const command = `mongotop --host localhost:27017 -u monitorUser -p securePassword --authenticationDatabase admin 5 --rowcount 1`;  
  exec(command, (error, stdout) => {  
    const lines = stdout.split('\n');  
    const targetLine = lines.find(line => line.includes(collectionName));  
    if (targetLine) {  
      const [, , readMs, writeMs] = targetLine.split(/\s+/);  
      if (parseInt(readMs) > 100 || parseInt(writeMs) > 200) {  
        this.logger.warn(`集合 ${collectionName} 读写延迟过高!读: ${readMs}ms, 写: ${writeMs}ms`);  
      }  
    }  
  });  
}  

要点

  • 密码必须通过 process.env 注入,禁止硬编码
  • 高频监控(间隔<5秒)可能增加服务负载
  • JSON 输出便于整合 Prometheus/Grafana

3 ) 通过 child_process 模块调用 mongostat,实现自定义监控逻辑:

import { Injectable } from '@nestjs/common';
import { exec } from 'child_process';
 
@Injectable()
export class MongoDBMonitorService {
  async runMongostat(interval: number, rowCount: number): Promise<string> {
    return new Promise((resolve, reject) => {
      const command = `mongostat --host localhost --port 27017 \
                      -u monitorUser -p securePassword \
                      --authenticationDatabase admin \
                      ${interval} --rowcount ${rowCount}`;
      
      exec(command, (error, stdout, stderr) => {
        if (error) reject(`监控失败: ${error.message}`);
        if (stderr) reject(`错误输出: ${stderr}`);
        resolve(stdout);
      });
    });
  }
}
 
// 控制器调用示例
import { Controller, Get } from '@nestjs/common';
import { MongoDBMonitorService } from './monitor.service';
 
@Controller('monitor')
export class MonitorController {
  constructor(private readonly monitorService: MongoDBMonitorService) {}
 
  @Get('stat')
  async getMongoStat() {
    return this.monitorService.runMongostat(3, 5); // 每3秒抓取,共5次
  }
}

关键补充知识点:

  • 安全增强:密码应通过环境变量注入(如 process.env.MONGO_PWD),避免硬编码。
  • 错误处理:捕获 ECONNREFUSED 异常以处理数据库连接失败场景。
  • 性能影响:高频监控可能增加服务器负载,建议生产环境间隔 ≥5 秒。

故障诊断与核心指标解析


1 ) 缓存机制工作原理

读写请求
WiredTiger缓存
used 活跃数据
内存性能
dirty 待刷盘数据
磁盘 I/O 瓶颈

2 ) 关键故障场景对照表

现象诊断命令解决方案
dirty 持续 >20%db.serverStatus().wiredTiger优化磁盘 I/O 或调整刷盘间隔
conn 异常增长db.currentOp()检查连接池泄漏或 DDoS 攻击,检查连接池配置
mongotop 无目标集合db.collection.stats()触发 findOne() 激活监控
command突增db.system.profile.find()
db.currentOp()
db.getProfilingStatus()
分析慢日志
  • dirty 与 used 的故障关联:
    • dirty 持续 >20%:可能因磁盘 I/O 延迟导致写入堆积,需检查存储性能
    • used 接近 100%:表明缓存饱和,易引发查询性能下降,需扩容内存或优化索引
  • 连接数 (conn) 突增对策:
    db.currentOp()  // 查看活跃操作 
    db.serverStatus().connections  // 分析连接来源
    
  • mongotop 零读写场景:若集合无操作,可通过 db.collection.stats() 验证活跃度

3 ) 性能优化建议

  • 写入堆积:当 dirty 超标时,调整 WiredTiger 引擎配置:
    wiredTiger:
      engineConfig:
        checkpoint: (size=2GB, wait=60s)  # 增加刷盘触发阈值
    
  • 内存压力:used 接近 100% 时:
    • 扩容 RAM 或启用 zstd 压缩
    • 分析 db.runCommand({top:1}) 定位高消耗集合

构建高效监控体系


1 ) 工具定位对比

工具监控层级核心指标适用场景
mongostat服务器进程级dirty/used/conn资源饱和预警
mongotop集合操作级read/write 延迟慢查询定位

2 ) 最佳实践总结

  • 权限最小化:严格限制 clusterMonitor 角色范围
  • 参数动态化:生产环境采样间隔 ≥5 秒,开发环境可放宽
  • 诊断闭环:阈值告警 → 日志分析 → 引擎调优
  • 自动化整合:通过 JSON 输出对接 CI/CD 流水线

3 )引擎缓存工作原理

used
dirty
Checkpoint
读写请求
WiredTiger缓存
活跃数据块
待刷盘脏数据
磁盘持久化

4 ) 扩展建议

  • 结合 explain() 分析慢查询执行计划
  • 集成 Ops Manager 实现监控可视化
  • 定期审计 system.roles 防止权限扩散

监控的本质是预判故障而非事后补救。掌握 mongostat/mongotop 的黄金指标(dirty/used/conn/latency),可构建 MongoDB 性能的“免疫系统”

关键知识点补充

  1. 监控角色权限:

    • clusterMonitor 角色包含 serverStatus、top 等权限,禁止 find 或 insert。
    • 生产环境需通过 TLS 加密连接传输监控数据。
  2. 引擎缓存机制:

    • WiredTiger 缓存:dirty 表示待刷写数据,used 表示缓存利用率。
    • 优化建议:当 dirty 持续 >30%,需增加磁盘 I/O 或调整 wiredTigerEngineConfig。
  3. 原生命令扩展参数:

    # 输出 JSON 格式(适用于自动化分析)  
    mongostat --json -u monitorUser -p securePassword  
    # 过滤特定数据库  
    mongotop --host localhost:27017 --filter '{ "ns": "/^prod./" }'  
    

总结


通过 mongostat 和 mongotop 的组合使用,可实现:

  1. 实时性能分析:服务器进程级资源消耗监控
  2. 瓶颈定位:集合粒度读写操作耗时统计
  3. 动态调控:通过频率/次数参数适配不同监控场景
  4. 故障预警:基于 dirty/used 等核心指标预判引擎状态异常

关键提示:所有监控操作必须严格遵循最小权限原则,仅授予 clusterMonitor 角色权限以避免安全风险

mongostat 聚焦服务器级资源指标(内存/连接/命令),mongotop 定位集合级读写瓶颈。通过 动态参数调整、关键指标筛选 及 自动化集成,可构建高效监控体系

权限配置需严格遵循最小特权原则,并结合缓存指标 (dirty/used) 预判 I/O 风险

AI Agent Harness Engineering 开发效率工具:Prompt工程、调试与监控平台 随着AI Agent技术从原型探索走向企业级落地,开发者普遍面临Prompt迭代无版本管控、Agent执行黑盒无法定位错误、上线后无监控导致故障频发、多团队协作效率低下四大核心痛点,据2024年LLMOps行业报告显示,没有配套工具链的Agent开发团队平均迭代周期是有工具链团队的6倍,线上故障率高达23%,平均资源浪费超过60%。 阅读详情

相关推荐

MFC使用Websocket通讯介绍和实例(附完整源码)

踩坑点,下载了好几个boost版本编译,经常出问题,后来搜索了好久资料才发现如下评论:WebSocket++0.8.2 has been tested through Boost 1.72。WebSocketpp依赖于boost,因此在使用WebSocketpp前需要编译Boost;所以我们直接下载Boost 1.72的windows版的进行安装,安装完成还需要编译;WebSocketpp也叫WebSocket++;服务编译好之后,使用。

weixin_42530684的博客 1171

MongoDB自带的监控工具mongostat与mongotop

这两个命令来监控MongoDB的运行情况。这两个命令对于我们处理MongoDB数据库变慢等等问题非常有用,能详细的统计MongoDB当前的状态信息。mongotop用来跟踪MongoDB的实例,提供每个集合的统计数据。默认情况下,mongotop每一秒刷新一次。它每秒钟刷新一次状态值,提供良好的可读性,通过这些参数可以观察到一个整体的性能情况。、开启profile功能通过查看日志进行监控分析。time: 当前时间。...

实际工作与学习当中的随记 1511

库卡C4控制柜首次上电

本文详细介绍了如何使新购的库卡机器人(以KRC4为例)达到正常运行状态。首先,必须正确连接机器人尾部和控制柜底部的各种线缆,包括动力线缆、编码器线、SmartPad线和安全回路线缆等。特别强调,电源线和蓄电池线的正确连接至关重要,避免硬插以防损坏。此外,机器人与控制柜之间需连接地线以防止漏电。文章还提到,开机前需检查电机保护器开关,并确保所有线路连接正确。开机后,需提升用户权限至安全维护员级别,通过系统配置激活安全相关通讯参数。最后,文章详细解释了X11安全回路的接线方式,强调双通道信号的重要性,并提醒不同

2202_75959322的博客 1846

MongoDB3.2工具---Mongostat

此工具提供关于mongod和mongos的当前运行状态概览 常用命令格式: mongostat --host 192.168.1.100:27017 -uroot -p123456 --authenticationDatabase admin 参数说明: host:指定IP地址和端口,也可以只写IP,然后使用--port参数指定端口号 -u: 如果开启了认证,则需要在其后填写用户名

逃跑的肉丸的博客 4610

维护测试监控LLM应用

LangFuse: 开源 + SaaS(免费/付费),LangSmith 平替,可集成 LangChain 也可直接对接 OpenAI API;LangSmith: LangChain 的官方平台,SaaS 服务(免费/付费),非开源,企业版支持私有部署;调试 Prompt 的 Playground测试/验证系统的相关指标数据集管理各种指标监控与统计:访问量、响应时长、Token 费等等。

SunnyRivers 1785

社工库2.0

#大题目 社工库2.0 ###环境 whoosh2.7 jieba 12306 python3.7 网上嫖来的网页模板(感谢站长之家 ###实现效果 建立的索引文件 好看的页面 更快的查找速度 ###实现过程 具体的实现过程比较简易,毕竟whoosh已经封装的很好了 第一步 建立索引并存储 schema = Schema(zhanghao=TEXT(stored=True), code=STORED, name=TEXT(stored=True, analyzer=

sdyinruichao的博客 2万+

mongodb监控工具学习之mongostat

对于nosql系列中的mongodb大家应该不陌生了。它自带了一系列监控工具,今天我们来学习第一个监控工具mongostat. 1.简介 mongostat是对当前正在运行mongod或mongos实例状态的快速概览。 mongostat在功能上类似于UNIX/Linux文件系统中的vmstat,只是提供的是关于mongod和mongos实例的数据 。 值得注意的是: mongostat

xiaoQL520的博客 4089

手机直连卫星上网,3GPP R17/R18到底做了哪些技术升级?(IoT/NR NTN详解)

本文深入解析了3GPP R17/R18标准中手机直连卫星上网的技术升级,重点介绍了IoT NTN与NR NTN两项关键技术。R17通过星历辅助补偿算法和多普勒频移控制,实现了智能手机直连卫星的突破;R18则进一步优化移动性、支持高频段和星上本地交换,提升用户体验。这些技术为物联网和5G/6G通信开辟了新可能。

weixin_33701251的博客 618

mongo笔记之监控(使用mongotop和mongostat)

1.使用mongostat(参考:http://www.2cto.com/database/201302/191013.html) mongostat是mongdb自带的状态检测工具,在命令行下使用. 它会间隔固定时间获取mongodb的当前运行状态,并输出 如果你发现数据库突然变慢或者有其他问题的话,你第一手的操作就考虑采用mongostat来查看mongo的状态 使用方式

hubeilihao的专栏 905

Unity抖音小游戏上架实战:从零到一,详解流程与避坑指南

本文详细介绍了Unity抖音小游戏上架的全流程,包括环境准备、SDK集成、开发者账号注册、软著申请、打包提交流程及常见问题解决方案。重点解析了抖音小游戏平台特有的配置细节和避坑技巧,帮助开发者高效完成游戏上架并优化用户体验。

weixin_33704234的博客 261

国密SSL通信的调试技巧

前面写了几篇国密开发相关的文章:解读国密非对称加密算法SM2啥?双证书?详解国密SM2的加密和解密详解国密SSL ECC_SM4_SM3套件详解国密SM2的数字签名这篇文章来聊一聊国密S...

云水木石 3206

Mongodb监控、性能排查工具mongostat

mongostat是mongodb自带的状态检测工具,在命令行下使用,会间隔固定时间获取mongodb的当前运行状态,并输出。 常用命令格式: mongostat --host 192.168.1.100:27017 -u root -p123456 --authenticationDatabase admin 参数说明: host:指定IP地址和端口,也可以只写IP,然后使用--port参数指定端口号 -u: 如果开启了认证,则需要在其后填写用户名 -p: 不用多少,肯定是密码 --aut

Circle-C的博客 1211

YOLO 系列专栏(二十九)YOLO26 × StarNet 轻量化涨点方案(CVPR 2024)轻量化、主干改进篇 | 星星卷积虽小,却蕴藏着巨大的高效潜力

StarNet 出自 CVPR 2024 轻量化主干网络工作,核心创新是,依靠逐元素乘法实现高阶特征融合,在几乎不增加参数量与 FLOPs 的前提下,大幅提升特征表达能力,天然适合等多任务统一建模。本文将 StarNet 完整替换 YOLO26 原有主干,保留 YOLO26 无 NMS 检测头与轻量化结构,实现,并提供。

qq_36130719的博客 410

mongo的两个检测工具mongotop和mongostat

之前发现线上发mongo服务,四核的cpu,全都达到了99% 然后使用下面的两个命令,定位到是有一张表,一直在批量更新操作。 最后给这张表添加了复合索引,解决问题。 /root/mongodb-linux-x86_64-rhel70-3.6.21/bin/mongotop --host 127.0.0.1 --port 27017 -u admin -p admin --authenticationDatabase “admin” 第一个命令,可以直观看到列表是耗时倒叙的,可以知道那张表最耗时,耗时原因是r

qazwsx081的专栏 475

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

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

MongoDB mongostat、mongotop和实时监控工具motop

MongoDB自带了mongostat 和 mongotop 这两个命令来监控MongoDB的运行情况。这两个命令对于我们处理MongoDB数据库变慢等等问题非常有用,能详细的统计MongoDB当前的状态信息。除此之外,还可以用db.serverStatus()、db.stats()、开启profile功能通过查看日志进行监控分析。

任何技能都是从模仿开始,逐步升华。 1万+

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

mongostat和mongotop对mongodb数据库运行状态进行监控

--mongostat工具是mongdb自带的监控工具,可以用来监控mongodb当前状态下的运行情况: [root@slave2 ~]# /usr/local/mongodb341/bin/mongostat 2insert query update delete getmore command dirty used flushes vsize   res qrw arw net_in net...

weixin_34278190的博客 333

计算机控制技术及应用

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

Mac下MySQL的配置和修改密码以及忘记密码后的重置密码

1 ) Mac下MySQL的配置和修改密码 2 ) 忘记并重置密码 启动MySQL服务,通过 $ps aux | grep mysql 判断是否启动该服务,若未启动,则到 系统偏好设置/MySQL面板 启动服务 软件默认会安装到:/usr/local/mysql 目录,进入这个目录下的bin目录:$cd /usr/local/mysql/bin 执行 $./mysql -u root -p 通过初始密码登录MySQL 通...

Wang的专栏 6259

mysql数据库的一些简单的sql语句 内连接 - 表的关联查询

# 创建一个user表 create table users( id int primary key auto_increment, name varchar(20), dpt_id int ); # 向user表中插入数据 insert into users values (null,'刘备',1), (null,'关羽',2), (null,'赵

Wang的专栏 4264

数据库、数据库类型、RDBMS以及MySQL

什么是数据库 数据库 就是按一定的结构来组织、存储和管理数据的仓库 可以很方便的进行crud, 能提供多个用户共享、具有尽可能小的冗余度、与应用程序批次独立的数据集合。 其他持久储存缺点:文件操作(不灵活) 数据库类型 包括 : 关系型 和 非关系型 【关系型】 MySQL MariaDB PostgreSQL Microsoft SQL Server Oracle数据库 Sybase 【...

Wang的专栏 4039

Eggjs笔记:Eggjs集成ElasticSearch及CRUD操作

相关文档 https://www.elastic.co/guide/index.html https://www.elastic.co/guide/en/elasticsearch/client https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/configuration.html https://www.elastic.co/guide/en/elasticsearch/client/javascrip

Wang的专栏 3530

Redis: 集群高可用之故障转移和集群迁移

若要检查源和目标是否数据统一,还可选择阿里配套工具RedisFullCheck。3.4 使用 RedisFullCheck 工具检查。下载官方编译好的工具包,直接解压后就能使用。故障转移,包括自动故障转移和手动故障转移。运行之后,就给一个反馈结果,如果是。1.2 原集群与目标集群结构不一致。1.1 原集群与目标集群结构一致。2 ) 手动故障转移。

Wang的专栏 2918

Python笔记:基于Django框架的数据库设计

概述 需要根据《项目建议书》、《需求说明书》、界面原型、各种标准规范对数据库进行设计, 我们目前先参考这一设计图 结构设计 1 ) 找实体 实体是实体-关系模型的基本对象, 是现实世界中各种事物的抽象。 凡是可以相互区 开并可以被识 的事、物、概念等对象均可认为是实体。 基本的实体列表如下: 会员 类别 商品 订单 订单详情 收货地址 商品评论 商品图片 友情链接 站内公告 … ...

Wang的专栏 2772

Elastic Stack梳理:集群搭建指南之高可用架构与实战部署

本文介绍了Elasticsearch分布式架构和Cerebro监控工具的部署策略。主要内容包括: ES集群角色划分(主节点、数据节点、协调节点)及功能说明 Cerebro监控工具的独立部署方法和访问方式 集群拓扑规划示例,包含节点IP分配和架构拓扑图 各类型节点的配置原则和数量计算公式 高可用主节点配置要点及示例配置 生产环境优化建议,包括分片规划、硬件配置和安全措施 文章提供了完整的集群部署方案,涵盖从基础概念到具体实施的各个环节,适用于不同规模的ES集群建设。

Wang的专栏 2545

Redis: 集群环境搭建,集群状态检查,分析主从日志,查看集群信息

当从节点获得足够多的选票时,它就会成为新的主节点,并增加自己的configEpoch来更新槽位配置。在Redis集群中,纪元的更新通常是由节点间的通信和状态变更触发的。例如,当某个节点接收到来自其他节点的状态变更通知时,它会比较通知中的纪元与自己的纪元。如果通知中的纪元更大,则更新自己的纪元。确保集群状态的一致性:通过递增的纪元,集群中的节点可以确保它们对集群状态的认知是一致的。通过递增的纪元版本号,集群中的节点可以确保它们对集群状态的认知是一致的,并解决可能出现的配置冲突问题。4 )纪元的更新机制。

Wang的专栏 2466

MySQL: 数据库性能的决定性因素之从双十一大促高并发场景看系统瓶颈与优化路径

电商大促期间,数据库面临高并发写入、连接数暴增、慢查询积压等核心挑战。本文分析了锁竞争、主从延迟等关键性能瓶颈,并提出多种优化方案:1)使用乐观锁通过版本号控制库存超卖;2)CAS机制实现无锁并发;3)分布式锁协调多节点操作。这些方案在保证数据一致性的同时提升吞吐量,适用于库存扣减、订单创建等典型场景,有效解决数据库扩展难题。

Wang的专栏 2426

Redis: Sentinel哨兵监控架构及环境搭建

在主从模式下,我们通过从节点只读模式提高了系统的并发能力并发不断增加,只需要扩展从节点即可,只要主从服务器之间,网络连接正常主服务器就会将写入自己的数据同步更新给从服务器,从而保证主从服务器的数据相同在这种架构下,它仍然是有一些缺点的,比如说它的可靠性保证不是很好,因为主从模式下,主节点故障了便无法提供写入的服务现在,我们通过哨兵来解决这个问题然后,主节点其实写的压力也是并没有被释放的包括主从之间的数据是相同的,它还有数据冗余一个问题后面集群也会解决这个问题。

Wang的专栏 2181
上一篇: MongoDB小课堂:精通数据迁移工具 mongoexport 与 mongoimport 的终极指南
下一篇: MongoDB小课堂: 深度诊断与优化——响应时间、内存压力及连接数故障全方位解决指南
Wang's Blog
博客等级 码龄12年 7438粉丝 2421原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

Wang's Blog

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

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

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

打赏作者

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

抵扣说明:

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

余额充值