EventMesh源码解析系列之tcp的pub/sub

报错处理——org.apache.kafka.common.errors.TimeoutException: Timeout expired while fetching topic metadata 具体报错如下: ckpoints to JobManager) (checkpoints: 'hdfs://craw-node212:9000/flink-checkpoints', savepoints: 'null', asynchronous: TRUE, maxStateSize: 5242880) 2022-03-13 22:48:00.641 [Process (3/4)] INFO org.apache.flink.runtime.taskmanager.Task - Loading J 阅读详情

pub和sub的实现-tcp

Eventmesh-sdk-java作为客户端,与eventmesh-runtime通信,用于完成消息的发送和接收。

那么pub和sub作为客户端,在eventmesh中是怎么实现的?

结构

我们首先看到sdk-java中tcp这一部分的结构:common部分定义了tcp协议下广播消息、异步消息都会用到的公共方法,impl是对tcp的pub和sub的真正实现。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Lh9gNtDL-1633765330465)(../../images/blog/structure.png)]

下面来具体介绍一下三个实现类的功能,下面是对应的类图:

  • DefaultEventMeshClient:实现了EventMeshClient接口,用来定义一个具备pub和sub功能的客户端。
  • SimplePubClientImpl:实现了SimplePubClient接口,同时还继承了TcpClient ,用来定义一个具备pub功能的客户端。
  • SimpleSubClientImpl:实现了SimpleSubClient接口,同时也继承了TcpClient ,用来定义一个具备sub功能的客户端。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HvqpnLMh-1633765330467)(../../images/blog/Impl-class-diagram.png)]

代码

  • 对于client的实现,首先是要和runtime进行连接,也就是和服务器进行连接,连接的过程是:client发送心跳包给server,server对心跳包进行回应,然后client发送连接请求,接收到server的回应之后,客户端和服务器连接成功。在EventMeshClient接口中,它是这样定义连接的:
void init() throws Exception;
void heartbeat() throws Exception;
  • 在DefaultEventMeshClient中具体的实现如下:
public void init() throws Exception {
        this.subClient.init();
        this.pubClient.init();
}
public void heartbeat() throws Exception {
        this.pubClient.heartbeat();
        this.subClient.heartbeat();
}
  • 也就是说,一个客户端和服务器的连接被分成了两个部分,一个是pub客户端的连接,一个是sub客户端的连接。那我们具体来看到两个客户端的实现,因为两个客户端实现有点类似,所以我们这里以SimpleSubClientImpl为例进行说明:

    client和server的握手过程

    HELLO_REQUEST(2), //client发给server的握手请求
    HELLO_RESPONSE(3), //server回复client的握手请求

//SimpleSubClientImpl
public void init() throws Exception {
        //指向server的启动入口
        open(new Handler());
    	//设置了hello的header和body部分,client和server进行握手
        hello();
        logger.info("SimpleSubClientImpl|{}|started!", clientNo);
}

client和server的发送心跳包过程

HEARTBEAT_REQUEST(0), //client发给server的心跳包

HEARTBEAT_RESPONSE(1), //server回复client的心跳包

//SimpleSubClientImpl
public void heartbeat() throws Exception {
    task = scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                //如果不是处于活跃状态,就重新连接
                if (!isActive()) {
                    SimpleSubClientImpl.this.reconnect();
                }
                //client向server发送心跳包
                Package msg = MessageUtils.heartBeat();
                SimpleSubClientImpl.this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS);
            } catch (Exception ignore) {
            }
        }
    }, EventMeshCommon.HEARTBEAT, EventMeshCommon.HEARTBEAT, TimeUnit.MILLISECONDS);
}
  • 连接成功之后,pub可以实现发布消息,并且可以选择使用异步还是广播的方式进行发布;而sub实现对消息的订阅,并且时刻监听pub发布的消息,对pub发布的消息进行回应。在SimplePubClient和SimpleSubClient的接口中,它们是这样定义的:
//SimplePubClient
//对消息进行发布
Package publish(Package msg, long timeout) throws Exception;
//发送rr消息
Package rr(Package msg, long timeout) throws Exception;
//发送异步单播消息
void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws Exception;
//广播消息
void broadcast(Package msg, long timeout) throws Exception;
//SimpleSubClient
//监听
void listen() throws Exception;
//订阅管理
void subscribe(String topic, SubscriptionMode subscriptionMode, SubcriptionType subcriptionType) throws Exception;
//取消订阅
void unsubscribe() throws Exception;
  • 下面介绍它们的具体实现
//SimplePubClientImpl 
public class SimplePubClientImpl extends TcpClient implements SimplePubClient {
    ...
     /**
     * 发送事件消息, 返回值是EventMesh 给了ACK
     *
     * @param msg
     * @throws Exception
     */
    public Package publish(Package msg, long timeout) throws Exception {
        logger.info("SimplePubClientImpl|{}|publish|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg);
        //请求上下文,发送事件消息
        return io(msg, timeout);
    }
    
    /**
     * 发送RR消息
     *
     * @param msg
     * @param timeout
     * @return
     * @throws Exception
     */
    public Package rr(Package msg, long timeout) throws Exception {
        logger.info("SimplePubClientImpl|{}|rr|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg);
        return io(msg, timeout);
    }

    /**
     * 异步RR
     *
     * @param msg
     * @param callback
     * @param timeout
     * @throws Exception
     */
    @Override
    public void asyncRR(Package msg, AsyncRRCallback callback, long timeout) throws Exception {
        super.send(msg);
        this.callbackConcurrentHashMap.put((String) RequestContext._key(msg), callback);

    }

    /**
     * 发送广播消息
     *
     * @param msg
     * @param timeout
     * @throws Exception
     */
    public void broadcast(Package msg, long timeout) throws Exception {
        logger.info("SimplePubClientImpl|{}|broadcast|send|type={}|msg={}", clientNo, msg.getHeader().getCommand(), msg);
        super.send(msg);
    }

   ...
}

public class SimpleSubClientImpl extends TcpClient implements SimpleSubClient {
    ...
    //监听
    public void listen() throws Exception {
        //调用MessageUtils方法启动监听
        Package request = MessageUtils.listen();
        this.io(request, EventMeshCommon.DEFAULT_TIME_OUT_MILLS);
    }

	//订阅
    public void subscribe(String topic, SubscriptionMode subscriptionMode, SubcriptionType subcriptionType) throws Exception {
        subscriptionItems.add(new SubscriptionItem(topic, subscriptionMode, subcriptionType));
        Package request = MessageUtils.subscribe(topic, subscriptionMode, subcriptionType);
        this.io(request, EventMeshCommon.DEFAULT_TIME_OUT_MILLS);
    }
	//取消订阅
    public void unsubscribe() throws Exception {
        Package request = MessageUtils.unsubscribe();
        this.io(request, EventMeshCommon.DEFAULT_TIME_OUT_MILLS);
    }
    
  ...
}

  • 最后就是断连,具体过程就是

    CLIENT_GOODBYE_REQUEST(4), //client主动断连时通知server CLIENT_GOODBYE_RESPONSE(5), //server回复client的主动断连通知
    SERVER_GOODBYE_REQUEST(6), //server主动断连时通知client
    SERVER_GOODBYE_RESPONSE(7), //client回复server的主动断连通知

  • 在EventMeshClient接口中是这样定义的:

void close();
  • 在DefaultEventMeshClient中的具体实现:
 public void close() {        this.pubClient.close();        this.subClient.close();}
//SimplePubClientImpl
private void goodbye() throws Exception {
        Package msg = MessageUtils.goodbye();
        this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS);
}
//SimpleSubClientImpl
private void goodbye() throws Exception {
        Package msg = MessageUtils.goodbye();
        this.io(msg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS);
}

举例

在eventmesh中有一个examples模块,就是包含了tcp和http两种协议的演示,这些演示,就是对sdk-java作为客户端和runtime的server交互的一些举例,下面我们以tcp的单播消息来对上面的内容做一个举例说明

public class AsyncPublish {

    public static Logger logger = LoggerFactory.getLogger(AsyncPublish.class);

    private static EventMeshClient client;

    public static AsyncPublish handler = new AsyncPublish();

    public static void main(String[] agrs) throws Exception {
        // 从application.properties配置文件中获取eventmesh.ip和eventmesh.tcp.port
        Properties properties = Utils.readPropertiesFile("application.properties");
        final String eventMeshIp = properties.getProperty("eventmesh.ip");
        final int eventMeshTcpPort = Integer.parseInt(properties.getProperty("eventmesh.tcp.port"));
        try {
            // 获取用户代理1
            UserAgent userAgent = EventMeshTestUtils.generateClient1();
            // 获取一个默认的eventmesh客户端
            client = new DefaultEventMeshClient(eventMeshIp, eventMeshTcpPort, userAgent);
            // 初始化
            client.init();
            // 心跳
            client.heartbeat();
			// 连续发送五条数据
            for (int i = 0; i < 5; i++) {
                Package asyncMsg = EventMeshTestUtils.asyncMessage();
                logger.info("begin send async msg[{}]==================={}", i, asyncMsg);
                // 消息发布
                client.publish(asyncMsg, EventMeshCommon.DEFAULT_TIME_OUT_MILLS);

                Thread.sleep(1000);
            }

            Thread.sleep(2000);
            //退出,销毁资源
//            client.close();
        } catch (Exception e) {
            logger.warn("AsyncPublish failed", e);
        }
    }
}
public class AsyncSubscribe implements ReceiveMsgHook {

    public static Logger logger = LoggerFactory.getLogger(AsyncSubscribe.class);

    private static EventMeshClient client;

    public static AsyncSubscribe handler = new AsyncSubscribe();

    public static void main(String[] agrs) throws Exception {
        // 从application.properties配置文件中获取eventmesh.ip和eventmesh.tcp.port
        Properties properties = Utils.readPropertiesFile("application.properties");
        final String eventMeshIp = properties.getProperty("eventmesh.ip");
        final int eventMeshTcpPort = Integer.parseInt(properties.getProperty("eventmesh.tcp.port"));
        try {
            // 获取用户代理2
            UserAgent userAgent = EventMeshTestUtils.generateClient2();
            // 获取一个默认的eventmesh客户端
            client = new DefaultEventMeshClient(eventMeshIp, eventMeshTcpPort, userAgent);
            // 初始化
            client.init();
            // 心跳包
            client.heartbeat();
			// 订阅一个主题,给定好订阅的模式和类型
            client.subscribe("TEST-TOPIC-TCP-ASYNC", SubscriptionMode.CLUSTERING, SubcriptionType.ASYNC);
            client.registerSubBusiHandler(handler);
			// 监听
            client.listen();

            //client.unsubscribe();

            //退出,销毁资源
//            client.close();
        } catch (Exception e) {
            logger.warn("AsyncSubscribe failed", e);
        }
    }

    @Override
    // 接收到消息的处理机制
    public void handle(Package msg, ChannelHandlerContext ctx) {
        EventMeshMessage eventMeshMessage = (EventMeshMessage) msg.getBody();
        logger.info("receive async msg====================={}", eventMeshMessage);
    }
}
SAP Event Mesh 简介 Get Started with Messaging for Decoupled Communication Step 1: What is the SAP Event Mesh service? SAP Event Mesh 是一种完全托管的服务,用于连接应用程序、服务和系统,以便它们可以通过消息和事件相互交互。 它通过引入中央消息代理取代了传统的点对点通信。 虽然点对点通信适用于在有限数量的发送方和接收方之间共享数据,但可扩展性很快就会成为一个问题。 SAP Event Mesh 解决了这个问题,并确保 阅读详情

相关推荐

MsgHook 消息截取控件

MsgHook,是一个专用于截取windows消息,并交由自定义过程处理的一个控件。 属性 1、HwndHook:MsgHook控件要截取消息的对象的句柄。如果你要为Form1截取消息,那么MsgHook1.HwndHook=Form1.hWnd 2、Message:这是一个逻辑型的数组,它的下标为你要控制的消息编号。如果你想处理WM_SYSCOMMAND消息、WM_CONTEXTMENU消息,那么可以这样定义: Msghook1.Message(WM_SYSCOMMAND) = True Msghook1.Message(WM_CONTEXTMENU) = True 事件 Msghook控件只有一个事件,定义如下: Sub Msghook1_Message(msg As Long, wp As Long, lp As Long, result As Long) msg参数为消息编号,如果你有多个消息要处理,可以用Select Case语句控制 方法 Msghook控件只有一个方法,定义如下: Long result = [form.][control.]InvokeWindowProc(msg As Long, wp As Long, lp As Long) 这个方法使你可以调用对象默认的处理过程处理消息

EventMesh源码解析系列之TCP源码

TCP 处理逻辑 启动 bootstrap组装好组件之后绑定到tcp的端口,并初始化处理器,时刻监听是否有客户端请求连接。 private void startServer() throws Exception { Runnable r = () -> { ServerBootstrap bootstrap = new ServerBootstrap(); // 定义一些管道属性 bootstrap.

@@老胡的博客 487

EventMesh:云原生事件驱动的运行时

什么是事件网格? 该图显示了事件网格相对于应用程序框架中其他类似技术(例如服务网格)的定位。 Event Mesh是用于将应用程序和中间件层分离的动态插件式云原生基本服务层。 它提供了灵活,可靠和快速的事件分发,并且可以进行管理。 云原生事件网格: 事件网格允许将来自一个应用程序的事件动态路由到任何其他应用程序。 事件网格的一般功能: 事件驱动; 事件治理; 动态路由; 云原生 流量控制; 负载均衡 支持连接事件存储: DeFiBus :一种分布式消息传递平台,具有低延迟,高性能和可靠性以及灵活的可伸缩性。 火箭MQ 关键部件: eventmesh-runtime :一

EventMesh源码解析系列之http处理

http处理 上次讲到,当channel被注册之后,这个类中的initChannel方法就会被调用,就会实现在管道后面加入handlers。那具体的,我们的http是怎样处理消息的? class HttpsServerInitializer extends ChannelInitializer<SocketChannel> { ... // 在管道后面加入handlers pipeline.addLast(new HttpRequestDe

@@老胡的博客 522

产业园区如何高效对接企业技术需求与高校科研成果?.docx

科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。

LabVIEW+数据库应用系列保姆级教程,第一篇数据库连接

目录LabVIEW连接数据库的方法连接MySQL连接Oracle,SQL Server,Access等 LabVIEW连接数据库的方法 1、创建udl(Universal Data Link)是通用数据连接文件。界面操作,简单快捷。 2、编写连接字符串。需要熟悉连接字符串的结构,容易出错。 3、其他… 本教程教你使用第1种方法,也是最简单、最常用的方法。 连接MySQL 1、在MySQL Installer内安装MySQL Connector/ODBC,建议安装32位(X86),如下图: 2、创建ODBC

wwplh5520370的博客 1万+

EventDemo——演示事件流

package { import flash.display.DisplayObject; import flash.display.Shape; import flash.display.Sprite; import flash.events.MouseEvent; import flash.text.TextField; public class EventDemo e

一个Flash程序员的自我修养 262

基于DFT的scanshift sdc模板(DFT)

摘要:本文详细介绍了DFT测试模式下的SDC约束方法。

murphyrong的博客 886

EventMesh源码解析系列之HTTP的启动

HTTP的启动 首先我们先将一下启动前的准备工作,也就是HTTPServer的初始化。 在EventMeshServer初始化的时候,会连带这初始化EventMeshHTTPServer,下面我就几点做出说明: 在初始化的时候,会初始化多个线程池,这个线程池中会有许多的阻塞的线程队列,当某一种事件发生的时候,就会根据事件来使用线程池工厂来为事件创建线程。【下面是源代码】 public void initThreadPool() throws Exception { // 批处理消息

@@老胡的博客 827

ERA5 hourly data批量下载与cdo处理(一)

本篇文章主要介绍了ERA数据的批量下载

qq_40511689的博客 3872

知识图谱_知识图谱 | 知识图谱做用户画像

导读:最近一直在思考怎么用知识图谱做推荐,但是目前能知道的内容都是基于路径的推荐和基于图特征的推荐,所以能不能换一个角度,探究一下用知识图谱怎么做用户画像,因为画像也是推荐系统重要的一部分。现在的知识图谱+推荐怎么做的传统的用户画像怎么做现在的知识图谱+推荐怎么做的?基于路径:可以理解成基于图谱的多路径召回,或者多路径推荐,然后根据路径的转移概率进行排序从而达到推荐的效果,基于路径比较适合简单的推...

weixin_28801659的博客 1460

Apache EventMesh 文档指南

Apache EventMesh 文档指南 Apache EventMesh 是一个用于构建分布式事件驱动应用程序的新一代无服务器事件中间件。本指南将带你了解其基本结构、关键文件及其用途,以便于开发者能够快速上手并进行项目部署。 1. 项目目录结构及介绍 Apache EventMesh 的 GitHub 存储库展示了其官方网站的源代码而非核心框架的内部结构,但我们可以基于一般开源项目惯例和提供的...

gitblog_00257的博客 546

遇到一个诡异的WiFi网络问题:同一个办公室苹果电脑上不了网,其他电脑都可以

先来把问题掰开揉碎地看清楚:在一个普通的办公室WiFi网络中,所有设备——Windows电脑、安卓手机、甚至是那台老旧的Linux服务器——都能正常联网,唯独苹果电脑(可能是MacBook、iMac或者Mac mini)像被下了魔咒一样,连不上网。这种情况不仅让人抓狂,还透着一股神秘感。为什么偏偏是苹果电脑?难道WiFi路由器对苹果有“偏见”?这些症状都指向一个核心问题:苹果电脑与办公室WiFi之间,似乎存在某种“沟通障碍”。但这障碍到底出在哪里呢?是苹果电脑自己的问题,还是网络设置在“针对”它?

网络技术联盟站 842

Apache EventMesh 项目教程

Apache EventMesh 项目教程 1. 项目的目录结构及介绍 Apache EventMesh 是一个用于构建分布式事件驱动应用的新一代无服务器事件中间件。项目的目录结构如下: eventmesh/ ├── eventmesh-admin-server/ ├── eventmesh-common/ ├── eventmesh-connectors/ ├── eventmesh-examp...

gitblog_00470的博客 476

2026年OPPO嵌入式岗位面试题带详细答案

本文总结了OPPO嵌入式岗位面试的核心考点,涵盖硬件驱动、系统启动、Linux内核开发等7大模块共34道典型题目。重点解析了SPI通信协议、中断处理、U-Boot启动流程、Linux驱动开发等关键技术,突出硬件调试与工程实践能力考核。题目设置贴合实际岗位需求,适合校招与社招驱动开发岗位应聘者系统复习,帮助掌握嵌入式开发的核心知识与面试要点。

Open 489

【SAP ME 3】JAVA 调用SAP PO WebService

Java调用SAP PO/PI WebService接口

探索 Java 编程的技巧、最佳实践和解决方案。本博客提供针对 Java 开发者的实用指南,涵盖从基础到高级话题,旨在提升编程效率和技能。 847

zmq学习中的问题

现象: pub/sub使用tcp通信,sub订阅了所有消息,开始正常 ,一段时间后收不到消息。 原因:因为pub是bind, sub是connect, pub与sub之间网络中断过,可能中断以后, pub连续发送消息都不成功,底层套节字关闭。由于中间网络不通,FIN没到到达对方,sub的底层套节字并没有收到,也就没有重连,当网络恢复后,sub仍然认为没有异常,所以也就没有消息被接收到。(如果底...

Gelare的博客 1720

PCL 加权局部最优投影(WLOP)简化算法

WLOP算法是一种点云重采样方法,通过迭代优化实现点云均匀化和特征保留。算法包含数据项(加权平均位置保持几何特征)和正则化项(排斥邻近点实现均匀分布)两部分。代码实现基于PCL库,通过KD树加速邻域搜索,使用高斯权重函数计算点位置更新。参数包括输出点比例、邻域半径、正则化权重和迭代次数。该算法不依赖网格信息,适合处理大规模扫描数据的预处理优化。

点云侠的博客 631

eventMesh 本地搭建记录

(作为整体了解 可以先看看架构)按照官方文档需要搭建服务。

zr的博客 1058

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

Apache EventMesh 使用教程

Apache EventMesh 使用教程 eventmeshEventMesh is a new generation serverless event middleware for building distributed event-driven applications.项目地址:https://gitcode.com/gh_mirrors/ev/eventmesh 项目介绍 Apach...

gitblog_00650的博客 1203

计算机控制技术及应用

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

WhiteSur-icon-theme与GTK/KDE主题搭配指南:实现完美MacOS风格桌面

WhiteSur-icon-theme是一款专为Linux桌面打造的MacOS Big Sur风格图标主题,它能让你的Linux系统瞬间拥有精致优雅的苹果风格视觉体验。本文将详细介绍如何将WhiteSur-icon-theme与GTK/KDE主题完美搭配,轻松打造令人惊艳的类MacOS桌面环境。 ## 准备工作:获取WhiteSur-icon-theme 首先需要将项目克隆到本地,打开终端执行

gitblog_00031的博客 412

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

【亲测免费】 Apache EventMesh 常见问题解决方案

Apache EventMesh 是一个新一代的无服务器事件中间件,旨在构建分布式事件驱动应用程序。它提供了一个可扩展的架构,支持多种事件存储和连接器,适用于各种云服务和数据库。EventMesh 的主要编程语言是 Java,但也支持其他语言的 SDK。 ## 新手使用注意事项及解决方案 ### 1. 环境配置问题 **问题描述**:新手在配置 EventMesh 运行环境时,可能会遇到依赖

gitblog_00047的博客 610

深入容器之可观测性稳定性实践

前言   随着k8s集群在集团的大规模应用,k8s集群在集团大大小小几十个,有的分布在IDC机房,有的使用云上资源。了解过k8s的老师应该知道k8s发现问题主要使用事件进行发现,但是统一收集事件就变得困难重重。针对这种现状集群的统一管理和稳定性建设变得极为棘手,IaaS团队着手研发了一套事件中心。事件中心除传统Kubernetes事件外,还采集主机硬件错误、内核错误、docker错误等。从事件中心上线后收集80+线上线下集群问题,定位硬件问题数十起,每日发现应用问题数百起。  

c-rain 1137

EventMesh 1.5.0发布!支持联邦治理,探索Data Mesh!

EventMesh 1.5.0 介绍昨天我们的 EventMesh 1.5.0 版本正式发布,本次版本是 EventMesh 进入Apache孵化以来一次较大规模的更新。1.5.0 实现了三大新特性:一是提供 Mesh Bridge 的特性能力,支持 Mesh 之间根据订阅信息自动发现与数据流转,可供探索更广泛的业务场景;二是提供了golang sdk,全面支持 Go语言;三是支持 Nacos registry,增强治理能力。除此之外,我们还完成了大量的代码优化和问题修复,进一步提高了应用的可用性、安全性和

weixin_39709847的博客 864

深度剖析 Apache EventMesh 云原生分布式事件驱动架构

近年来,随着微服务、云原生和 Serverless 概念的普及以及容器化技术的发展,事件驱动也再次成为热点,引起 IT 界广泛的关注。事件驱动架构是一种用于设计应用的软件架构和模型。对于事件驱动系统而言,事件的捕获、通信、处理和持久保留是解决方案的核心结构。事件驱动架构可以最大程度减少耦合度,很好地扩展与适配不同类型的服务组件,因此是现代化分布式应用架构的理想之选。什么是 EventMesh云原生生态下的事件驱动架构模型EventMesh 架构EventMesh 的相关特性以及应用场景。...

riemann_的博客 3635

java消息路由_微信第三方平台消息回调处理优化:从工厂到消息路由

一: 微信第三方平台回调消息是啥当微信小程序或公众号运营者授权给第三方平台管理后,微信服务器会将粉丝发给公众号的消息,以及各种小程序和公众号上产生的事件推送(如小程序审核事件、自定义菜单点击事件、粉丝取消关注通知等),以回调的形式发给开发者服务器。开发者在接到上述消息和事件以后需要进行处理。下面是一个粉丝在关注了公众号以后,微信服务器向开发者服务器推送的事件消息。MsgType显示这是一个事件推送...

weixin_39996798的博客 702
上一篇: EventMesh源码解析系列之TCP源码
下一篇: SSM框架开发文档
@@老胡
博客等级 码龄7年 291粉丝 184原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值