cloud foundry之dea组件源码分析

cloud foundry的源码解析一览(cloud controller,dea) 关于cloud foundry 的源码解析的文章很多,最近我也在研究这个东西,感觉内容比较多,也相对比较复杂,我在这里做一个整合,方便大家了解。 1.CloudController 了解整个Cloud Foundry需要熟悉的内容很多,但最核心的东西是nats和event-machine. 关于nats上一篇已经做了介绍,大家可参考基于Cloud Foundry的PaaS实践(二) Clo 阅读详情

上一篇文章分析了router的运行原理,在这一篇开始分析dea组件的运行。。。,记得以前自己刚刚开始接触cloud foundry的时候就会觉得dea是最神奇的一个模块,不过看了它的代码之后它的神秘感也就渐渐的消失了。。

首先来看启动的代码:

EM.run {
  agent = DEA::Agent.new(config)
  agent.run()
}
还是在eventmachine中启动,主要的代码都在agent类中。。。

agent类的构造函数主要是进行一些基本信息的配置,例如app目录的路径,总共可用的内存大小等。。。这里就不一看他的代码了。。主要是来看run函数中的代码,因为重要的部分都在这个里面。。。

    begin   #用于创建文件夹
        FileUtils.mkdir_p(@droplet_dir)
        FileUtils.mkdir_p(@staged_dir)
        FileUtils.mkdir_p(@apps_dir)
        FileUtils.mkdir_p(@db_dir)
        if @secure # Allow traversal by secure users
          FileUtils.chmod(0711, @apps_dir)
          FileUtils.chmod(0711, @droplet_dir)
        end
      rescue => e
        @logger.fatal("Can't create support directories: #{e}")
        exit 1
      end
这部分代码用于创建dea存放app代码的文件夹,以及其他一些运行信息的代码。。。。接下来就是最为重要的部分了。。。
#启动NATS循环
      NATS.start(:uri => @nats_uri) do
        # Register ourselves with the system
        status_config = @config['status'] || {}
        VCAP::Component.register(:type => 'DEA',
                           :host => @local_ip,
                           :index => @config['index'],
                           :config => @config,
                           :port => status_config['port'],
                           :user => status_config['user'],
                           :password => status_config['password'])

        uuid = VCAP::Component.uuid
        @logger.info("DEA uuid #{uuid}")

        # Setup our identity
        @hello_message = { :id => uuid, :ip => @local_ip, :port => @file_viewer_port, :version => VERSION }.freeze
        @hello_message_json = @hello_message.to_json

        # Setup our listeners..
        NATS.subscribe('dea.status') { |msg, reply| process_dea_status(msg, reply) }    #用于报告dea的状态
        NATS.subscribe('droplet.status') { |msg, reply| process_droplet_status(msg, reply) }    #用于报告app的状态
        NATS.subscribe('dea.discover') { |msg, reply| process_dea_discover(msg, reply) }    #controller发送的查找合适的运行环境的询问
        NATS.subscribe('dea.find.droplet') { |msg, reply| process_dea_find_droplet(msg, reply) }     #在dea中寻找对应的droplet
        NATS.subscribe('dea.update') { |msg| process_dea_update(msg) }  
        NATS.subscribe('dea.stop') { |msg| process_dea_stop(msg) }
        NATS.subscribe("dea.#{uuid}.start") { |msg| process_dea_start(msg) }
        NATS.subscribe('router.start') {  |msg| process_router_start(msg) }   #相当于是router的心跳广播消息,dea收到消息后向router报告当前dea的一些基本信息
        NATS.subscribe('healthmanager.start') { |msg| process_healthmanager_start(msg) }    #healthmanger的广播消息,也是用于报告一些消息
        NATS.subscribe('dea.locate') { |msg|  process_dea_locate(msg) }    #用于通告当前dea的一些环境信息

        # Recover existing application state.
        recover_existing_droplets
        delete_untracked_instance_dirs

        EM.add_periodic_timer(@heartbeat_interval) { send_heartbeat } #10    
        EM.add_periodic_timer(@advertise_interval) { send_advertise } #5
        EM.add_timer(MONITOR_INTERVAL) { monitor_apps }                    #监视app的状态
        EM.add_periodic_timer(CRASHES_REAPER_INTERVAL) { crashes_reaper }
        EM.add_periodic_timer(VARZ_UPDATE_INTERVAL) { snapshot_varz }
        EM.add_periodic_timer(DROPLET_FS_PERCENT_USED_UPDATE_INTERVAL) { update_droplet_fs_usage }

        NATS.publish('dea.start', @hello_message_json)  #发布消息,表示当前这个dea已经启动了,告诉别人
        send_advertise
首先注册该dea组件,接着要在nats中订阅以及发布消息,最后还要向整个系统发送广播消息,表示当前dea模块已经启动了。。。

这样,整个模块就已经启动了,接下来dea就开始进入消息循环了,不断的等待nats的消息,并发送一些心跳消息等。。。

这里就分析几个重要的就可以了。。。首先是:

NATS.subscribe('dea.discover') { |msg, reply| process_dea_discover(msg, reply) }    #controller发送的查找合适的运行环境的询问
该消息是cc模块发送过来的,当dea接收到这个消息之后会根据发送过来的数据进行分析,判断当前的运行环境是否满足要求,如果满足的话,那么会向cc返回消息,如果不满足的话,那么就会忽略这个消息。。。另外有一个小的插曲就是,dea会根据当前所运行的app的负载状态来推迟回复消息的时间,而cc会选择第一个回复该消息的dea运行该app。。。
#这个函数用来处理从nats收到的controller用来查找合适的运行环境的查询,如果不满足,那么dea将不会向controller返回消息
    def process_dea_discover(message, reply)
      return if @shutting_down
      @logger.debug("DEA received discovery message: #{message}")   #msg一般是需要运行的app的一些基本的信息
      message_json = JSON.parse(message)
      # Respond with where to find us if we can help.
      if @shutting_down         #dea是否已经停止了
        @logger.warn('Ignoring request, shutting down.')
      elsif @num_clients >= @max_clients || @reserved_mem > @max_memory   #判断app的数目是否已经超过了限制
        @logger.warn('Ignoring request, not enough resources.')
      elsif droplet_fs_usage_threshold_exceeded?    
        @logger.warn("Droplet FS has exceeded usage threshold, ignoring request")
      else
        # Check that we properly support the runtime requested
         unless runtime_supported? message_json['runtime_info']    #判断运行环境是否满足要求
          @logger.debug("Ignoring request, #{message_json['runtime_info']} runtime not supported.")
          return
        end
        # Ensure app's prod flag is set if DEA's prod flag is set
        if @prod && !message_json['prod']
          @logger.debug("Ignoring request, app_prod=#{message_json['prod']} isn't set, and dea_prod=#{@prod} is.")
          return
        end
        # Pull resource limits and make sure we can accomodate
        limits = message_json['limits']
        mem_needed = limits['mem']
        droplet_id = message_json['droplet'].to_s
        if (@reserved_mem + mem_needed > @max_memory)
          @logger.warn('Ignoring request, not enough resources.')
          return
        end
        delay = calculate_help_taint(droplet_id)    
        delay = ([delay, TAINT_MAX_DELAY].min)/1000.0   
        EM.add_timer(delay) { NATS.publish(reply, @hello_message_json) }   #之所以要延迟返回,时为了平衡各个dea之间的压力,因为压力较小的dea先返回
      end
    end
上述就是discovery消息的处理函数,其实也很简单,说白了就是判断当前的运行环境以及内存等情况是否满足app的需求。。。

接下来再来看一个十分重要的消息:

       NATS.subscribe("dea.#{uuid}.start") { |msg| process_dea_start(msg) }
这个是从cc发送过来的运行某个app的消息。。。该消息的处理函数首先会根据发送过来的消息生成相应的app的信息,接着会获取该app的源代码,然后再进行启动,由于代码比较长,我们就重点来看app是怎么启动的吧。。。
@logger.debug('Completed download')
        if not instance[:uris].empty?
          port = grab_port    #用于获取app的运行端口
          if port
            instance[:port] = port
          else
            @logger.warn("Unable to allocate port for instance#{instance[:log_id]}")
            stop_droplet(instance)
            return
          end
        else
          @logger.info("No URIs found for application.  Not assigning a port")
        end
        if debug
          debug_port = grab_port
          if debug_port
            instance[:debug_ip] = VCAP.local_ip
            instance[:debug_port] = debug_port
            instance[:debug_mode] = debug
          else
            @logger.warn("Unable to allocate debug port for instance#{instance[:log_id]}")
            stop_droplet(instance)
            return
          end
        end

        if console
          console_port = grab_port
          if console_port
            instance[:console_ip] = VCAP.local_ip
            instance[:console_port] = console_port
          else
            @logger.warn("Unable to allocate console port for instance#{instance[:log_id]}")
            stop_droplet(instance)
            return
          end
        end
首先是为app分配运行时端口等信息,
#启动app的函数
        exec_operation = proc do |process|
          process.send_data("cd #{instance_dir}\n")
          if @secure || @enforce_ulimit 
            process.send_data("renice 0 $$\n") 
            process.send_data("ulimit -m #{mem_kbytes} 2> /dev/null\n")  # ulimit -m takes kb, soft enforce
            process.send_data("ulimit -v 3000000 2> /dev/null\n") # virtual memory at 3G, this will be enforced
            process.send_data("ulimit -n #{num_fds} 2> /dev/null\n")   
            process.send_data("ulimit -u 512 2> /dev/null\n") # processes/threads  
            process.send_data("ulimit -f #{disk_limit} 2> /dev/null\n") # File size to complete disk usage
            process.send_data("umask 077\n")
          end
          #设置环境变量,书要是访问服务的一些环境变量
          app_env.each { |env| process.send_data("export #{env}\n") }
          if instance[:port]
            process.send_data("./startup -p #{instance[:port]}\n")
          else
            process.send_data("./startup\n")
          end
          process.send_data("exit\n")
        end

        exit_operation = proc do |_, status|
          @logger.info("#{name} completed running with status = #{status}.")
          @logger.info("#{name} uptime was #{Time.now - instance[:start]}.")
          stop_droplet(instance)
        end

        # Being a bit paranoid here and wipe all processes for the secure user
        # before we start..
        kill_all_procs_for_user(user) if @secure

#用于真正的启动
        Bundler.with_clean_env { EM.system("#{@dea_ruby} -- #{prepare_script} true #{sh_command}", exec_operation, exit_operation) }
接着调用bundler来启动app,在着了我们可以看到
 process.send_data("renice 0 $$\n") 
            process.send_data("ulimit -m #{mem_kbytes} 2> /dev/null\n")  # ulimit -m takes kb, soft enforce
            process.send_data("ulimit -v 3000000 2> /dev/null\n") # virtual memory at 3G, this will be enforced
            process.send_data("ulimit -n #{num_fds} 2> /dev/null\n")   
            process.send_data("ulimit -u 512 2> /dev/null\n") # processes/threads  
            process.send_data("ulimit -f #{disk_limit} 2> /dev/null\n") # File size to complete disk usage
            process.send_data("umask 077\n")
这些用于设置app的运行时的一些资源限制。。。。
 app_env.each { |env| process.send_data("export #{env}\n") }
这句代码用于给app设置环境变量,其实这些环境变量大多是用于访问服务的一些信息,例如访问数据库的url等信息。。在app当中就可以通过这些环境变量的信息来访问服务了。。。。
 if instance[:port]
            process.send_data("./startup -p #{instance[:port]}\n")
          else
            process.send_data("./startup\n")
          end
          process.send_data("exit\n")
最后就是调用启动脚本具体启动app了。。。
detect_app_ready(instance, manifest) do |detected|
          if detected and not instance[:stop_processed]
            @logger.info("Instance #{instance[:log_id]} is ready for connections, notifying system of status")
            instance[:state] = :RUNNING
            instance[:state_timestamp] = Time.now.to_i
            send_single_heartbeat(instance)
            register_instance_with_router(instance)   #向router注册app的信息
            schedule_snapshot
          else
            @logger.warn('Giving up on connecting app.')
            stop_droplet(instance)
          end
        end
最后分析app的运行情况,并向router发送注册刚刚启动的app的信息。。。


好了,dea最重要的部分就已经分析完成了。。。

其余的消息还有

NATS.subscribe('dea.status') { |msg, reply| process_dea_status(msg, reply) }    #用于报告dea的状态
用于报告当前dea的运行状态。。。
NATS.subscribe('droplet.status') { |msg, reply| process_droplet_status(msg, reply) }    #用于报告app的状态
用于报告droplet的状态

嗯,,还有其余的。。就不一一列举出来了。。。。


Cloud Foundry中gorouter源码分析 在Cloud Foundry v1版本中,router作为路由节点,转发所有进入Cloud Foundry的请求。由于开发语言为ruby,故router接受并处理并发请求的能力受到语言层的限制。虽然在v1版本中,router曾经有过一定的优化,采用lua脚本代替原先的ruby脚本,由lua来分析请求,使得一部分请求不再经过ruby代码,而直接去DEA访问应用,但是,效果依旧不是很理想。为了提高Cloud Foundry router的可用性,Cloud Foundry开源社区不久前推出了gorouter。g 阅读详情

相关推荐

dea的基本MATLAB程序

用于一般DEA的MATLAB编辑,主要包含BCC和CCR模型。

dea架构分析

一、DEA整体架构 图1 DEA和其他组件 图2 DEA和warden   二、DEA和外部组件 1、DEA和NATS在CF内部,各个组件相互配合来完成某项功能,都是通过nats的消息机制来完成的; 2、DEA和cloud controller1)dea启动时,生成唯一的uuid来标识自身    dea将自身信息发布到 staging.advertise 和 dea.adve...

iteye_6700的博客 970

基于STM32电压检测和电流检测

1.可测量直流电压0~36V,适用于低电压电子电路中。 2.可测量直流电0~5A范围内,目前采用的ACS712测量量程为5A,该模块有多个量程,可测量到20A 3.实时功率监测 4.电池电量监测(采用电压压降方式计算)

weixin_44453694的博客 6万+

Cloud Foundry中DEA组件内应用的启动与资源监控

Cloud Foundry中所有的应用都运行在一个称为DEA的组件中,DEA的全称是Droplet Execution Agent。 DEA的主要功能可以分为两个部分:运行所有的应用,监控所有的应用。本文主要讲解Cloud Foundry v1版本中DEA如何启动一个应用,以及DEA如何监控应用的资源使用。虽然DEA两个功能的实现远不止这么多,但是笔者认为启动应用和监控应用资源是DEA的精髓所在,很多其他的内容都是在这两个点上进行封装或者强化。

木精灵的技术博客 4443

300个fpga练手项目推荐

• 按键设置BPM,LED和蜂鸣器同步打拍(支持4/4、3/4拍)• 例:先实现DDR3控制器(基础),再构建视频处理流水线(集成)◦ 驱动小型e-Paper显示日期/时间(SPI接口,静态刷新)◦ 音频输入经FFT后,用LED柱状显示频率能量(8频段简化)◦ 通过HC-05模块接收手机指令,控制电机方向(前进/后退)• 随机点亮LED,用按钮响应,数码管显示反应时间(毫秒级)• 8个LED旋转闪烁,按钮停止后显示中奖编号(带减速动画)• 用4方向按键输入手势(如→→←↑),正确后点亮绿色LED。

qq_62784677的博客 7640

DRV2605L触觉驱动芯片实战指南:从自动校准到音频转触觉应用

触觉反馈技术是现代人机交互的核心组成部分,它通过精确控制振动马达来模拟物理触感,广泛应用于智能手机、游戏手柄和汽车触摸屏等领域。其原理在于将电信号转化为机械振动,关键在于如何高效、精准地驱动不同类型的马达(如ERM和LRA)。这项技术的核心价值在于提升交互的真实感和沉浸感。在工程实践中,集成驱动芯片如DRV2605L通过内置智能反馈引擎和自动校准功能,解决了传统驱动方式响应慢、效果不一致的难题。它特别适用于需要高质量触觉反馈的应用场景,例如消费电子、游戏外设和车载信息娱乐系统。其中,自动校准能自适应优化驱动

weixin_42631411的博客 341

CloudFoundry之DEA源码分析

DEA启动分析 ruby的代码结构一般都是一样的: bin目录是执行文件 conf是配置文件 lib则是ruby source spec放置一些测试的文件 Gemfile+Gemfile.lock为bundler服务,让dea可以找到正确的gem依赖 Rakefile是用来做测试的 先看下dea的目录结构,bin 放的是脚本,等同shell的

K_James的专栏 2428

RT-DETR的AIF模块+YOLOv8:融合注意力与特征交互,打造实时检测的科研级进阶方案

从理解AIF模块“细粒度注意力+跨尺度交互”的核心设计,到亲手将其嵌入YOLOv8并验证在复杂场景的表现,再到基于此探索属于自己的科研与工程方向——这个过程能让你深刻理解“注意力机制与CNN融合”在实时检测中的核心价值。现在就开始行动,相信你会在实时目标检测的“智能进化”之路上,走出一条属于自己的技术路径。从实验对比图可见,集成AIF模块的YOLOv8,其mAP(平均精度)在多个阈值下均有提升,尤其是mAP50-95(高IoU阈值下的精度)提升更为显著,充分证明了AIF对细粒度特征的捕捉能力。

m0_64661770的博客 188

cloud foundry dea源码解析

准确的讲,不全是原创,参考了一些blog,主要是对源代码进行整理。 在CF上部署Tuscany应用时,纠结很久,因此,将自己之前整理的文档先发布出来。 欢迎大家讨论,批评指正! 1. dea介绍 DEA(DropletExecution Agent)   DEA manages anapplication instance’slifecycle, instructed by

ndzj981479673的专栏 3495

OpenLayers6入门,快速搭建Vue+OpenLayers地图脚手架项目

本章针对Vue初学者,对Vue不熟悉,甚至还不会Vue的入门学生读者。本章会详细讲解从环境到环境的各个步骤,再到使用脚手架快速生成项目,以及添加地图库依赖,编写简单的高德地图显示页面的。如果已有VUE项目或者熟悉VUE的读者可以不用看本章,直接添加ol依赖到VUE项目中即可。

GIS技术方向,GIS地图技术分享(GIS入门、Openlayers教程、Leaflet教程),做最好的GIS地图开发教程。关注博主公众号:eguid 5440

【AUTOSAR-E2E】-1.4-详述E2E Transformer解决方案

共13页精讲 目录 1“Data Transformation”介绍 1.1 基于SOME/IP Transformer 1.2 基于COM Based Transformer 2 ComXf(COM Based Transformer)介绍 2.1 ComXf(COM Based Transformer)功能规范 2.2 ComXf(COM Based Transformer)提供的服务 2.3 配置注意事项 3 E2EXf(E2E Transformer)介绍 3.1 E2EX...

「汽车电子助手」的博客 4700

CloudFoundry DEA运作源码分析

这篇文章结构比较糟,我在http://lory-yang.com/2012/09/09/cloud-foundry-dea/中做了一些改进,可以去那里看看。另外我的博客整体搬迁到独立地址了:lory-yang.com,欢迎大家来访问 本文是对Cloud Foundry中的DEA组件源码的一些分析。有点流水帐的感觉,就事论事吧,同时因为本人能力有限,而且研究不深,错误在所难免。诸位就随便看看,

cherry_sun的专栏 5998

1、深入解析OTA/gm - C滤波器架构与设计

本文深入探讨了OTA/gm-C滤波器的架构与设计方法,涵盖了从基本构建模块到高阶滤波器实现的多种技术。重点分析了双积分器环路结构(如Tow-Thomas和KHN滤波器)的工作原理、性能特点及OTA非理想特性对滤波器的影响,并介绍了降低寄生效应、提升动态范围的方法。文章还讨论了基于LC梯形仿真、多环反馈和电流模式的gm-C滤波器设计,以及自动调谐技术在频率稳定性中的应用。最后总结了不同类型gm-C滤波器的优缺点及其适用场景,为高频集成连续时间滤波器的设计提供了全面的技术参考。

fanta的博客 185

Cloud Foundry Service Node源码分析及实现【附下载】

从Word拷贝过来结果好多都变形了,附加下载地址:http://download.youkuaiyun.com/detail/wearenoth/5060429 Cloud Foundry Services源码分析之Node 引言 Service结构 在Cloud Foundry中Service的结构不是太复杂,由两个组件组成——Gateway、Node。如图1展示

明何 6770

电池模拟器【 电化学模型深度解析:PNGV模型原理与应用(专业科普版)】

1. 模型起源PNGV(Partnership for a New Generation of Vehicles)模型诞生于1993年美国“新一代汽车合作计划”,旨在提升混合动力汽车电池系统的建模精度。该模型最初针对铅酸电池设计,后经改进广泛用于锂离子电池、镍氢电池等动态特性仿真。2. 模型定位PNGV属于**等效电路模型(ECM)**的进阶版本,介于简单Rint模型与复杂电化学模型(如P2D模型)之间,兼顾计算效率与精度,是BMS(电池管理系统)中SOC/SOH估算的主流选择。PNGV模型凭借。

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

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

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

Cloud Foundry中Stager组件的源码分析

Cloud Foundry中有一个组件,名为Stager,它主要负责的工作就是将用户部署进Cloud Foundry的源代码打包成一个DEA可以解压执行的droplet。 关于droplet的制作,Cloud Foundry v1中一个完整的流程为:1.用户将应用源代码上传至Cloud Controller;2.Cloud Controller通过NATS发送请求至Stager,要求制作dropet;3.Stager从Cloud Controller下载压缩后的应用源码,并解压;4.Stager将解压后的

木精灵的技术博客 2755

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

cloud foundry之router源码分析

前面的文章已经介绍了整个cloud foundry的源码的启动过程,这篇文章介绍一下router方面的细节,毕竟外界访问cloud foundry的入口就是router。。 首先来看router的启动:/home/fjs/cloudfoundry/vcap/router/bin/router -c /home/fjs/cloudfoundry/.deployments/devbox/config

fjs的专栏 2118

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

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Cloud Foundry Service Node源码分析及实现

Cloud Foundry Services源码分析之Node 引言 Service结构 在Cloud Foundry中Service的结构不是太复杂,由两个组件组成——Gateway、Node。如图1展示了Service相关的几个主要组件,每个组件有十分明确的分工: 图 1 Service相关主要组件 Gateway 其它组件(Cloud

kent45的专栏 1648

Cloud Foundry中collector组件的源码分析

在Cloud Foundry中有一个叫collector的组件,该组件的功能是通过消息总线发现在Cloud Foundry中注册过的各个组件的信息,然后通过varz和healthz接口来查询它们的信息,最后再将各个组件收集过来的数据发送到指定的存储位置。 本文从collector的功能出发,主要讲述以上三个功能的源码实现。

木精灵的技术博客 3424

CloudFoundry源码分析:DEA

DEA(Droplet Execution Agent),主要流程都在agent.rb文件中实现。 由于CloudFoundry平台是以NATS为中心的,只要弄清楚了这个组件能够处理的NATS消息,也就清楚了这个组件的基本流程。DEA也不例外。 Agent主要注册了以下几种事件,下面分别介绍这些方法的实现流程 。 NATS.subscribe('dea.s

Tony的专栏 1461

Cloud Foundry技术全貌及核心组件分析

本文在从架构组成、核心模块功能、源代码分析等角度来全面剖析Cloud Foundry,同时会结合各行业的典型案例来讲解Cloud Foudry在具体应用场景中的表现。 架构设计及核心组件 从总体上看,Cloud Foundry的架构如图1所示。 图1 Cloud Foundry架构图 经过一年多的发展,Cloud Foundry的组件增加了很多。但核...

weixin_33709219的博客 362

CloudFoundry组件之间通信NATS MESSAGES

Cloud Foundry是业界领先的开源PaaS平台,它的内核采用Ruby开发。设计上使用以NATS消息系统为核心的松耦合组件架构,强调以NATS消息系统为核心的松耦合组件架构所带来的弹性。 NATS 一个轻量级的 发布-订阅, 分布式队列消息系统,基于EventMachine开发。 本文重点将列出CF系统中,都有哪些 "NATS MESSAGES",并且对其功能做简单介绍。

restkuan的专栏 1660

CloudFoundry源码分析:vcap-tool

概述vcap-tool,顾名思义,是vcap平台的一个工具。这个工具将vcap平台的运行数据整合进OpenTSDB。OpenTSDB是一个基于HBase的、分布式的、可扩展的Time Series Database (TSDB)。OpenTSDB was written to address a common need: store, index and serve metrics collect

Tony的专栏 1543

CloudFoundry dea实践经验

CloudFoundry dea实践经验分享下使用CF过程中一些经验:查询所有dea的容器个数curl router:c1oudc0w@ROUTER_IP:PORT/routes | python -mjson.tool | grep DEA_IP | wc -l ++note:其中ROUTER_IP是gorouter的Ip,PORT是gorouter查询状态的那个端口,DEA_IP是待查询的dea

wenhao的专栏 598

DEA(数据包络分析)程序模板

在人们的生产活动和社会活动中常常会遇到这样的问题:经过一段时间之后,需要对具有相同类型的部门或单位(称为决策单元)进行评价,其评价的依据是决策单元的“输入”数据和“输出”数据,输入数据是指决策单元在某种活动中需要消耗的某些量,例如投入的资金总额,投入的总劳动力数,占地面积等等;输出数据是决策单元经过一定的输入之后,产生的表明该活动成效的某些信息量,例如不同类型的产品数量,产品的质量,经济效益等等.再

LSEC小陆的博客 1万+
上一篇: cloud foundry之router源码分析
下一篇: nginx的filter调用
fjs_cloud
博客等级 码龄15年 248粉丝 192原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值