dubbo接口访问控制

Dubbo 指定调用固定ip+port dubbo调用指定服务 dubbo调用不随机 dubbo自定义调用服务 dubbo点对点通信 dubbo指定ip 1. 写分布式im,需要指定某一服务,调用,其他博客得都调不通,写的有问题。如果是随机端口,启动之后,dubbo有没有方法可以获取到随机端口号,或者通过代码从nacos获取随机的端口号,欢迎沟通,讨论下这个问题。上述是dubbo 的源码方法即获取ip,只要使用dubbo ,直接调用就能调用出来,注意这个是dubbo的源码方法,引用包结构别错了。1. 配置文件是随机端口。复制图片,打开微信,打开图片,也可能需要发送,然后打开图片,复制即可。如果是随机端口,则可能需要从nacos配置中心,写代码获取。 阅读详情

微服务背景下,一个web应用都可能不再service依赖,而是通过RPC调用远端服务器上的服务。这些服务里,就包括了一些不能轻易暴露的后台功能接口。暴露出去的dubbo接口注册到某一个zk上后,该dubbo接口对注册到该zk上的消费者都是可见的。对公司内部而言,通常不会有人蓄意去调用一些敏感的接口,但也存在人为误用的可能呀。为此,考虑通过白名单机制来控制dubbo接口的访问。

现在以许可ip127.0.0.1访问接口fundRecordTemplateFacade为例演示。

扩展Filter

首先,我们需要实现com.alibaba.dubbo.rpc.Filter接口:

@Activate(group = { Constants.CONSUMER, Constants.PROVIDER })
public class FacadeAccessFilter implements Filter {

    private FacadeAccessConfig facadeAccessConfig;

    public FacadeAccessConfig getFacadeAccessConfig() {
        return facadeAccessConfig;
    }

    // 通过setter方式注入白名单配置文件
    public void setFacadeAccessConfig(FacadeAccessConfig facadeAccessConfig) {
        this.facadeAccessConfig = facadeAccessConfig;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result = null;
        // 获取调用的接口名
        String reqFacade = invoker.getInterface().getSimpleName();
        try {
            // 尝试在白名单配置文件里查找定义的接口,如果找不到则catch住异常、并许可访问。
            Method method;
            try {
                method = facadeAccessConfig.getClass().getDeclaredMethod(editMethodName(reqFacade));
            } catch (NoSuchMethodException e) {
                // 无特殊限制,则许可访问
                result = invoker.invoke(invocation);
                return result;
            }
            // 走到这里,说明白名单配置文件配了对该facade的访问限制
            // 获取remoteAddress:进行访问的应用,格式ip:port
            String remoteAddress = RpcContext.getContext().getRemoteAddressString();
            // 只取ip
            String remoteIp = remoteAddress.split(":")[0];
            // 获取licensinedApplications:许可的应用列表
            String licensinedApplications = (String) method.invoke(facadeAccessConfig);
            if (StringUtils.isNotEmpty(licensinedApplications) && StringUtils.isNotEmpty(remoteIp) && licensinedApplications.contains(remoteIp)) {
                // 权限许可、进行访问
                Help.log_info(getClass(), " remoteAddress" + remoteAddress + "访问接口" + reqFacade);
                result = invoker.invoke(invocation);
                return result;
            } else {
                // 权限不许可、退出访问
                Help.log_info(getClass(), " remoteAddress" + remoteAddress + "无权访问接口" + reqFacade);
                result = new RpcResult("remoteAddress" + remoteAddress + "无权访问接口" + reqFacade);
                return result;
            }
        } catch (SecurityException e) {
            Help.log_error(getClass(), "校验remoteAddress是否有权限访问" + reqFacade + "发生异常", e);
        } catch (IllegalAccessException e) {
            Help.log_error(getClass(), "校验remoteAddress是否有权限访问" + reqFacade + "发生异常", e);
        } catch (IllegalArgumentException e) {
            Help.log_error(getClass(), "校验remoteAddress是否有权限访问" + reqFacade + "发生异常", e);
        } catch (InvocationTargetException e) {
            Help.log_error(getClass(), "校验remoteAddress是否有权限访问" + reqFacade + "发生异常", e);
        }
        return result;
    }

    private String editMethodName(String fieldName) {
        return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

配置文件

  1. 在resources目录下添加纯文本文件META-INF/dubbo/com.alibaba.dubbo.rpc.Filter,内容如下: 
    这里写图片描述

  2. 修改配置文件dubbo-common.xml,在dubbo:provider属性中添加配置的filter,内容如下: 
    在dubbo:provider中添加配置的filter

  3. 扩展Filter时,我们是通过setter方法将访问白名单FacadeAccessConfig注册到FacadeAccessFilter类中的,那么在配置文件(譬如:applicationContext.xml)里还需要对bean实例化。

    <!-- 将facade访问白名单注册到FacadeAccessFilter类中 -->
    <bean id="facadeAccessFilter" class="com.roger.account.provider.filter.FacadeAccessFilter">
        <property name="facadeAccessConfig" ref="facadeAccessConfig" />
    </bean>
    <bean id="facadeAccessConfig" class="com.roger.account.provider.filter.FacadeAccessConfig" />
  • 1
  • 2
  • 3
  • 4
  • 5

访问白名单文件

我们看一下白名单文件的设计格式。本意希望能配置成”接口名=调用接口的应用名”,因为部署应用的ip变化可能性远高于应用本身的名称修改。但是在Invoker和Invocation对象中找不到客户端的应用名,无奈之下,就设计成了”接口名=调用接口的ip”。 
白名单

下面是FacadeAccessConfig类,定义的私有属性都是需要控制权限的dubbo接口名,getter方法从配置平台disconf上找到对应配置文件的对应属性值。

@Component(value = "facadeAccessConfig")
@DisconfFile(filename = "facadeAccessConfig.properties")
public class FacadeAccessConfig {

    // 定义可以访问fundRecordTemplateFacade的应用
    private String fundRecordTemplateFacade;

    @DisconfFileItem(associateField = "fundRecordTemplateFacade", name = "fundRecordTemplateFacade")
    public String getFundRecordTemplateFacade() {
        return fundRecordTemplateFacade;
    }

    public void setFundRecordTemplateFacade(String fundRecordTemplateFacade) {
        this.fundRecordTemplateFacade = fundRecordTemplateFacade;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

这样,对于已经配置的一个接口,新增可访问的应用只需要添加ip。对于一个新配置的接口,只需要在配置文件facadeAccessConfig.properties里添加”接口名=调用接口的应用名”,然后在FacadeAccessConfig类中新增私有属性即可。

Dubbo04【Zookeeper存储数据的数据信息】,mybatis对象关系映射原理 Consumers 存储服务消费者信息 | 属性 | 描述 | | — | :-- | | application | 应用名 | | category | 类型 | | check | 检查 | | dubbo | dubbo版本 | | interface | 接口名称 | | methods | 接口方法名 | | pid | 进程号 | | side | 消费端或服务端 | | timestamp | 时间戳 | Providers 存储服务提供者 [zk: localhost:2181(CO 阅读详情

相关推荐

Apache Dubbo Admin 未授权访问绕过漏洞 (CNVD-2023-96546)

# Apache Dubbo Admin 未授权访问绕过漏洞 (CNVD-2023-96546)

weixin_51486050的博客 614

Dubbo的三种调用方式

1、reference调用 @Reference(version = “1.0.0”) private UserFacade userFacade; 2、指定dubbo服务端口进行调用 String url = “dubbo://192.168.2.95:20403/cn.lehome.api.business.cache.IMerchantRedisCacheversion=1.0.0”;//更改不同的Dubbo服务暴露的ip地址&端口 ReferenceBean referenceBean =

m0_67402823的博客 2426

dubbo系列--Filter实现白名单功能

平时开发接口的时候可能会涉及到安全问题,比如说我们只对某部分ip提供调用,即就是ip白名单,本文就是实现dubbo服务调用之白名单 直接上代码比较爽快: 注意这里的Filter是dubbo下的,顺带着看看它的源码 看到了此接口上有个注解@SPI。说明我们这里实现此类那么就得使用SPI实现方式来做,更多了解SPI 除了实现接口以外还得配置 建目录:META-INF.dubbo....

田维常 1977

dubbo接口访问控制 - 白名单

微服务背景下,一个web应用都可能不再service依赖,而是通过RPC调用远端服务器上的服务。这些服务里,就包括了一些不能轻易暴露的后台功能接口。暴露出去的dubbo接口注册到某一个zk上后,该dubbo接口对注册到该zk上的消费者都是可见的。对公司内部而言,通常不会有人蓄意去调用一些敏感的接口,但也存在人为误用的可能呀。为此,考虑通过白名单机制来控制dubbo接口的访问。 现在以许可ip12

qq_33440246的博客 4717

dubbo 自定义过滤器

dubbo 自定义过滤器

congge 1万+

Java通用权限管理系统:后台配置与DUBBO接口设计

Java通用权限管理系统是一套为应用软件提供统一权限控制的解决方案,通过集中式管理,能够有效简化授权流程,提高系统的安全性。本章将首先介绍Java权限管理系统的基本概念与重要性。角色是权限管理系统中的核心概念,它代表了一组权限的集合,可以赋予用户或用户组,从而简化权限管理过程。在设计角色时,首先要定义角色的类型,包括但不限于系统预定义角色、业务角色和临时角色。系统预定义角色:通常是系统内置的基本角色,如管理员、普通用户等,这些角色包含的权限通常与系统功能紧密相关。业务角色。

weixin_35370061的博客 1009

基于PelicanDT实现dubbo断网验证

具体介绍 Dubbo-example,是基于PelicanDT实现dubbo环境准备,禁止端口网络访问,执行接口调用验证端口是否禁用示例 前期准备 本示例程序是基于阿里云ECS或远程Linux服务器完成,只需购买阿里云机器,或者选定已准备好的远程服务器即可 下载Dubbo-example代码 快速入门 修改配置 打开dubbo.properties...

weixin_33895516的博客 130

VSCode+Pyside6开发环境配置全攻略:从安装到实战UI设计

本文提供了一份详细的VSCode与Pyside6集成开发环境配置指南。从创建Python虚拟环境、安装必备VSCode插件,到深度配置PYQT Integration插件以打通Qt Designer与代码编译,最后通过一个待办事项应用实战演示了从UI设计到业务逻辑绑定的完整工作流,旨在帮助开发者建立高效、可维护的GUI开发环境。

qq_27496129的博客 983

Zookeeper 保存的Dubbo信息详解

Consumers: /dubbo/com.example.dubbo.service.CityService/consumers/consumer://192.168.198.1/com.example.dubbo.service.CityService?application=consumer&category=consumers&check=false&dub...

沙门空海 2522

C语言实战:最小二乘法在传感器数据校准中的应用(附完整代码)

本文详细介绍了如何使用C语言实现最小二乘法,对传感器数据进行线性校准。通过模拟带噪声的传感器数据,手把手演示了从核心算法实现、参数计算到效果验证的完整流程,并提供了可直接编译运行的完整源码,帮助嵌入式开发者解决传感器数据不准的常见问题,提升系统测量精度。

weixin_28025327的博客 519

电力现货市场出清机制与节点电价计算实战解析

本文深入解析了电力现货市场的出清机制,特别是节点边际电价的计算原理与实战应用。通过一个基于Matlab和IEEE30节点系统的完整案例,详细演示了如何利用最优潮流模型求解市场出清价格,并提取节点电价,揭示了电网阻塞如何影响实时电价的形成。

weixin_29061425的博客 954

Dubbo——服务治理(dubbo-Admin)平台

摘要 本章将详细探讨Dubbo配置的设计模型、服务暴露的原理、服务消费的原理和优雅停机的原理。首先,学习优雅的分层配置设计,能够帮助我们更好地理解框架的启动配置逻辑,不管是注解还是XML 配置都需要配置对象来承载。然后探讨服务暴露和服务消费的细节。最后研究优雅停机特性,能够保证线上服务和消费方平滑地退出。 Dubbo配置解析; 基于schema设计解析 Spring框架对Java产生了深远的影响,Dubbo 框架也直接集成了Spring 的能力,利用Spring配置文件扩展出自定义的解析方式。Dub

庄小焱 1191

Python量化交易入门:天勤量化TqSdk保姆级教程(含避坑指南)

本文提供Python量化交易入门指南,重点介绍天勤量化TqSdk的使用方法,包括环境配置、核心API实战、策略开发技巧及实盘部署。教程涵盖中国期货市场,帮助个人投资者快速掌握量化交易技术,避开常见陷阱。

weixin_29065791的博客 837

通过dubbo白名单来控制dubbo接口的访问

微服务背景下,一个web应用都可能不再service依赖,而是通过RPC调用远端服务器上的服务。这些服务里,就包括了一些不能轻易暴露的后台功能接口。暴露出去的dubbo接口注册到某一个zk上后,该dubbo接口对注册到该zk上的消费者都是可见的。对公司内部而言,通常不会有人蓄意去调用一些敏感的接口,但也存在人为误用的可能呀。为此,考虑通过白名单机制来控制dubbo接口的访问。 现在以许可ip12...

qq_36881106的博客 536

Kubeflow系统性学习教程:从入门到高级实践

Kubeflow学习教程摘要(150字): Kubeflow是基于Kubernetes的云原生MLOps平台,提供端到端机器学习解决方案。核心功能包括Jupyter Notebooks开发环境、Pipelines工作流编排、分布式训练支持和模型服务部署。教程采用三阶段学习路径:初学者搭建Kind集群体验Notebooks;中级开发自定义Pipeline组件;高级实现企业级应用。通过容器化和K8s CRD深度集成,解决环境一致性、实验跟踪和资源调度等MLOps痛点,相比MLflow/Airflow更适合大规模

自可乐的博客 888

超详细的springboot整合dubbo+mybatis

之前也找了很多关于springboot整合dubbo的案例,但是总是会有一些问题,总的来说这个是相对比较完整的,这个我是根据每层来分的,而不是根据功能模块,适合基础学习,废话不多说先看整体架构 步骤 1.创建一个普通的项目 这里使用的idea工具创建普通的maven项目,这一步需要注意的是什么模板都不用选直接next 对于创建好的项目第一步当然就是它的pom文件的配置,这里需要注意的是modu...

weixin_42963566的博客 1925

高通camx hal进程dump日志分析四:Node DumpDebugInfo原理分析

摘要: 本文讲解了高通Camx架构中DumpDebugInfo的原理,重点分析了Node组件的DumpDebugInfo()方法。该方法会输出Node自身调试信息,并调用DumpFenceErrors()接口输出Fence错误信息。具体包括:检查请求队列状态、输出未完成请求的元数据/完成状态/未处理Fence数量等关键信息,以及Fence错误原因(如延迟、未触发、结果失败等)。通过代码注释详细解析了各字段含义,为后续分析Dump异常日志提供理论基础。

787

思维导图四(SpringBoot、SpringSecurity、SpringCloud Netflix、Swagger、Dubbo、zookeeper)

一 SpringBoot2.0框架 (更新:思维导图主题字打错了,但内容是正确的,晕) 1 框架作用:简化Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置 二 SpringSecurity框架 1 框架作用:是一个功能强大且高度可定制的身份验证和访问控制框架,侧重于为Java应用程序提供身份验证和授权。 三 SpringCloud Netflix框架 1 作用:一套分布式微服务的技术解决方案,包含服务发现注册、配置中..

qq_39144436的博客 1811

【K8S系列】Kubernetes Pod节点CrashLoopBackOff 状态及解决方案详解【已解决】

在 Kubernetes 中,Pod 的状态为 **`CrashLoopBackOff`** 表示某个容器在启动后崩溃,Kubernetes > 尝试重启该容器,但由于持续崩溃,重启的间隔时间逐渐增加。下面将详细介绍 `CrashLoopBackOff > `状态的原因、解决方案及相关命令的输出解释。

颜淡慕潇 8381

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Dubbo分布式服务框架简单介绍+代码

Dubbo是阿里巴巴SOA服务化治理方案的核心框架。 核心:远程通讯,集群容错,自动发现 Dubbo采用spring配置方式,无api侵入, 挡在多个tomcat部署不同系统时,TomcatA 想调用 TomcatB 这是就需要用到Dubbo(有点像webservice)。 provider:服务提供方 consumer:服务消费方 registry:服务注册中心 monitor:统计服务 r...

qq_24075991的博客 294

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

上一篇: SecureCRT 用ssh key登录配置方法
下一篇: Disconf使用简单Demo
hxpjava1
博客等级 码龄19年 1365粉丝 511原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值