SPARK中 DS V2 push down(下推)的一些说明

Spark DataSource 源码解析 文章目录SparkSession.read()DataFrameReaderformatschemaoptionjson、csv、text...loadDataSource.lookupDataSourceDataFrameReader.loadV1SourceDataSource.resolveRelationSparkSession.baseRelationToDataFrame数据源有关的StrategyFileSourceStrategyFileSourceScanExecDataSourceStr 阅读详情

背景

本文基于 SPARK 3.3.0
在之前的文章 SPARK中的FileSourceStrategy,DataSourceStrategy以及DataSourceV2Strategy规则 我们有提到 DS V2 push down的功能,如JDBC 复杂下推,以及Parquet的聚合下推等等。其实这里面有个比较大的背景–就是TableCatalog类。

结论

先说结论,这些聚合下推的大前提是,在spark中已经配置了对应的catalog,如下:

spark.sql.catalog.h2=org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog

分析

在Rule V2ScanRelationPushDown一系列的规则中,第一个规则createScanBuilder:

private def createScanBuilder(plan: LogicalPlan) = plan.transform {
    case r: DataSourceV2Relation =>
      ScanBuilderHolder(r.output, r, r.table.asReadable.newScanBuilder(r.options))
  }

只有是DataSourceV2Relation类型,也就是 DS v2,才会转换为 ScanBuilderHolder, 而后续的pushDownFilters,pushDownAggregates规则则是基于ScanBuilderHolder来做转换的(如果有遇到ScanBuilderHolder类型才会进行DS v2特有的规则转换),所以DataSourceV2Relation是从哪里来的是关键。
直接说重点:
在RULE ResolveRelations中会进行 UnresolvedRelation到DataSourceV2Relation或是UnresolvedCatalogRelation的转换:

object ResolveRelations extends Rule[LogicalPlan] {
  ...
def apply(plan: LogicalPlan)
        : LogicalPlan = plan.resolveOperatorsUpWithPruning(AlwaysProcess.fn, ruleId) {
      case i @ InsertIntoStatement(table, _, _, _, _, _) if i.query.resolved =>
        val relation = table match {
          case u: UnresolvedRelation if !u.isStreaming =>
            lookupRelation(u).getOrElse(u)
          case other => other
        }

这里的lookupRelation会根据是否有对应的Catalog的注册来判断是DS V1还是DS V2:

private def lookupRelation(
        u: UnresolvedRelation,
        timeTravelSpec: Option[TimeTravelSpec] = None): Option[LogicalPlan] = {
      lookupTempView(u.multipartIdentifier, u.isStreaming, timeTravelSpec.isDefined).orElse {
        expandIdentifier(u.multipartIdentifier) match {
          case CatalogAndIdentifier(catalog, ident) =>
            val key = catalog.name +: ident.namespace :+ ident.name
            AnalysisContext.get.relationCache.get(key).map(_.transform {
              case multi: MultiInstanceRelation =>
                val newRelation = multi.newInstance()
                newRelation.copyTagsFrom(multi)
                newRelation
            }).orElse {
              val table = CatalogV2Util.loadTable(catalog, ident, timeTravelSpec)
              val loaded = createRelation(catalog, ident, table, u.options, u.isStreaming)
              loaded.foreach(AnalysisContext.get.relationCache.update(key, _))
              loaded
            }
          case _ => None
        }
      }
    }
    ...
private def expandIdentifier(nameParts: Seq[String]): Seq[String] = {
    if (!isResolvingView || isReferredTempViewName(nameParts)) return nameParts

    if (nameParts.length == 1) {
      AnalysisContext.get.catalogAndNamespace :+ nameParts.head
    } else if (catalogManager.isCatalogRegistered(nameParts.head)) {
      nameParts
    } else {
      AnalysisContext.get.catalogAndNamespace.head +: nameParts
    }
  }
object CatalogAndIdentifier {
    import org.apache.spark.sql.connector.catalog.CatalogV2Implicits.MultipartIdentifierHelper

    private val globalTempDB = SQLConf.get.getConf(StaticSQLConf.GLOBAL_TEMP_DATABASE)

    def unapply(nameParts: Seq[String]): Option[(CatalogPlugin, Identifier)] = {
      assert(nameParts.nonEmpty)
      if (nameParts.length == 1) {
        Some((currentCatalog, Identifier.of(catalogManager.currentNamespace, nameParts.head)))
      } else if (nameParts.head.equalsIgnoreCase(globalTempDB)) {
        // Conceptually global temp views are in a special reserved catalog. However, the v2 catalog
        // API does not support view yet, and we have to use v1 commands to deal with global temp
        // views. To simplify the implementation, we put global temp views in a special namespace
        // in the session catalog. The special namespace has higher priority during name resolution.
        // For example, if the name of a custom catalog is the same with `GLOBAL_TEMP_DATABASE`,
        // this custom catalog can't be accessed.
        Some((catalogManager.v2SessionCatalog, nameParts.asIdentifier))
      } else {
        try {
          Some((catalogManager.catalog(nameParts.head), nameParts.tail.asIdentifier))
        } catch {
          case _: CatalogNotFoundException =>
            Some((currentCatalog, nameParts.asIdentifier))
        }
      }
    }
  }

expandIdentifier方法结合CatalogAndIdentifier.unapply方法,判断:

  • 1.如果没有指定catalog,则 默认catalog 为v2SessionCatalog,catalog的名称为"spark_catalog",这也是spark默认的sessionCatalog 名称,跳到步骤3
    如以下SQL: select a from table
  • 2.如果指定了catalog,且catalog已经注册了(如以spark.sql.catalog.h2=org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog),则catalog为指定的(如为JDBCTableCatalog,catalog的名称为"h2",跳到步骤3
    如以下SQL:select a from h2.table
  • 3.调用CatalogV2Util.loadTable方法也就是对应的Catalog的loadTable方法来获取对应的Table:
    1. V2SessionCatalog catalog返回是的V1Table
    2. JDBCTableCatalog catalog 返回的是JDBCTable

这样在下一步的createRelation 方法中就会根据不同的case转换为不同的relation:

private def createRelation(
        catalog: CatalogPlugin,
        ident: Identifier,
        table: Option[Table],
        options: CaseInsensitiveStringMap,
        isStreaming: Boolean): Option[LogicalPlan] = {
      ...
      case v1Table: V1Table if CatalogV2Util.isSessionCatalog(catalog) =>
          if (isStreaming) {
            if (v1Table.v1Table.tableType == CatalogTableType.VIEW) {
              throw QueryCompilationErrors.permanentViewNotSupportedByStreamingReadingAPIError(
                ident.quoted)
            }
            SubqueryAlias(
              catalog.name +: ident.asMultipartIdentifier,
              UnresolvedCatalogRelation(v1Table.v1Table, options, isStreaming = true))
          } else {
            v1SessionCatalog.getRelation(v1Table.v1Table, options)
          }
      ...
      case table =>
        ...
         } else {
            SubqueryAlias(
              catalog.name +: ident.asMultipartIdentifier,
              DataSourceV2Relation.create(table, Some(catalog), Some(ident), options))
          
  • 如果是V1Table,则会转换为UnresolvedCatalogRelation,继而在 Rule FindDataSourceTable中转为LogicalRelation,这里就会涉及lookupDataSource,也就是注册的datasource(如:“org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider” 或者 "org.apache.spark.sql.execution.datasources.v2.parquet.ParquetDataSourceV2”(目前没有进行cast匹配))发生作用了(在providingInstance()方法中实现)
  • 如果是其他的,则会转换为DataSourceV2Relation,继而在Rule V2ScanRelationPushDown中做一系列的下推优化

所以说 对于JDBC的catalog来说,想要进行DS V2的优化,就得配置:

spark.sql.catalog.h2=org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog

如果想要对于其他DS v2的优化,如Parquet,就得实现对应的TableCatalog,再进行配置:

spark.sql.catalog.parquet=org.apache.spark.sql.execution.datasources.v2.jdbc.xxxx

关于TableCatalog

目前 jdbc的datasource和TableCatalog 在spark都是已经实现了:

## datasource
org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider
## TableCatalog
org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog

如果想实现其他的datasource以及catalog,可以参考JDBC的实现(目前的JDBC的source实现还是基于 DS V1,最好是基于DS V2实现,如参考:ParquetDataSourceV2)。

在SPARK-28396也有这方面的讨论。
更进一步DS V2 Push Down的特性,参考技术前沿|Spark 3.3.0 中 DS V2 Push-down 的重构与新特性

SparkSQL基于DataSourceV2自定义数据源 SparkSQL基于DataSourceV2自定义数据源 版本说明:Spark 2.3 前言:之前在SparkSQL数据源操作文章中整理了一些SparkSQL内置数据源的使用,总的来说SparkSQL支持的数据源还是挺丰富的,但业务上可能不拘束于这几种数据源,比如将HBase作为SparkSQL的数据源,REST数据源等。这里主要讲一下在Spark2.3版本之后推出的DataSourceV2,基于DataSourceV2实现自定义数据源 1 DataSourceV1 VS DataSourceV2 自S 阅读详情

相关推荐

SparkSQL问题汇总

实验使用环境为spark-3.0.0-preview2,教程观看的版本为spark1.6,spark2.0开始对sql进行改进,用sparksession实现hivecontext和sqlcontext统一,合并dataframe和datasets等,按照老的教程会引起问题。 一. SQLContext报红,找不到依赖包。 解决办法:在pom中添加依赖: <!--导入spark sql依赖--> <dependency> <groupId>org.apache.sp

loveforeverDC的博客 772

sparksql 自动DataSourceV2源

明细模型底层使用 LSM Tree 数据结构进行存储,我们都知道 LSM Tree 是一 个写友好的数据结构,在 StarRocks 数据存储层,选择了一个两层结构的 LSM Tree,减少了 compaction 对系统的压力,也减少了 write stall 的影响。在分析统计和汇总数据时,聚合模型能够减少查询时所需要处理的数据,提升查询效率。建表时,支持定义主键和指标列,查询时返回主键相同的一组数据中的最新数据。在性能方面,从全内存的主键索引升级为持久化的主键索引,解决主键模型内存占用的问题。

MDZ_1122333322的博客 659

【信息科学与工程学】计算机科学与自动化——第三百零五篇 计算机系统中的各类运算操作01

编号类型领域运算操作运算类型算法算法的详细设计及数学分析参数列表及参数的数值设计应用场景 (100+条)集合运算​1集合运算关系代数并集 (Union)集合运算归并排序去重合并两个集合,去除重复元素。时间复杂度 O(n+m),n,m为两集合大小。输入:集合A, B。输出:A∪B。数据集成、多表结果合并、去重后的全量数据提取。2集合运算关系代数交集 (Intersection)集合运算哈希交集找出同时属于两个集合的元素。平均时间复杂度 O(min(n,m)),最坏 O(n*m)。输入:集合A, B。输出:A∩

weixin_49199313的博客 1388

SPARK中的FileSourceStrategy,DataSourceStrategy以及DataSourceV2Strategy规则

本文基于SPARK 3.3.0 用于记录Spark中V1和V2的Datasource以及FileSource的作用以及区别,以及在Spark 3.3.0出现的更强的Datasource v2 JDBC的下推在spark 3.3.0中 出现了DS V2 push down的功能,该功能是能够更好的进行下推,比如说更加复杂的聚合下推和过滤下推。 涉及到filter过滤的地方为partitionKeyFilters 和dataFilters,partitionKeyFilters针对的是分区级别的过滤,比如说只选

monkeyboy_tech的博客 1224

【信息科学与工程学】计算机科学与技术——第七十七篇 系统架构设计02

编号类型模型配方企业资本运作的方法/规则/条件/依据及所有的步骤(​风险处理/异常处理/危机应对关联知识法律法规和裁决依据​​由发起人(通常是知名投资人、投行或产业资本)先设立一个只有现金、无实际业务的特殊目的收购公司(SPAC),通过IPO募集资金并在交易所上市。然后在规定时间内(通常24个月)寻找一家非上市公司进行合并(De-SPAC),使目标公司迅速实现上市,规避传统IPO的复杂流程和不确定性。1.:在开曼或特拉华注册空壳公司,注入少量种子资金。2.

weixin_49199313的博客 306

【信息科学与工程学】【通信工程】第一百五十五篇 网络拓扑学09

聚焦云数据中心(多region多AZ+多边缘DC)与城域网5G/6G网络一体化的拓扑学编号类型领域问题问题的数学分析(拓扑学+其他)参数列表及参数的数值范围关联知识A166图论/组合优化云原生数据湖如何用Apache Hudi的Timeline拓扑优化增量查询?​1. 拓扑学分析(详细): - 拓扑结构:Apache Hudi使用Timeline管理表的历史变更,Timeline是一个时间轴上的DAG。每个Instant(提交、 compaction、 cleaning等)是一个节点,节点之间按时间顺

weixin_49199313的博客 220

spark sql使用jdbc读取数据库的过程

spark jdbc读取数据库过程

chanyue123的博客 2219

实现 spark DataSourceV2 的几个环节

继承 DataSourceV2 class SimpleWritableDataSource extends DataSourceV2 with ReadSupport with WriteSupport { override def createReader() override def createWriter() } 构造 Reader class Reader(path: St...

zhixingheyi_tian的博客 897

技术前沿|Spark 3.3.0 中 DS V2 Push-down 的重构与新特性

在本文中,作者将对 Spark 3.2 DS V2 Push-down 框架进行深入分析,并分享 Kyligence 开源团队是如何在 Spark 3.3.0 中完成对 DS V2 Push-down 的重构与改进的,欢迎大家在评论区分享你的看法。

Kyligence 1199

Simplicity Studio V5与EFR32BG22蓝牙开发环境实战指南

本文详细介绍了Simplicity Studio V5集成开发环境与EFR32BG22蓝牙芯片的开发实战指南。内容涵盖开发环境安装、SDK配置、项目创建、调试烧录、外设驱动集成及常见问题解决方案,帮助开发者快速上手物联网蓝牙应用开发,并充分利用EFR32BG22的低功耗与高集成度特性。

v5w6x的博客 320

基于carsim与Simulink联合仿真的车辆换道轨迹规划与轨迹跟踪模型

PID_反步控制_滑膜控制三种四旋翼无人机轨迹跟踪控制算法仿真 附带对应的说明文档,提供建模过程与仿真结果文献(英文)➕PPT 描述:采用的同一种参考轨迹,都是三维仿真 三种控制方法: [1]PID控制、[2]反步控制、[3]滑膜控制(三个仿真模型) 每个仿真均应用了同一种轨迹路径,直接运行即可出三维图,可以实现四旋翼无人机轨迹的跟踪

2501_90804007的博客 1083

Spark 数据源jdbc2新增upsert功能

在spark的数据源中,只支持Append, Overwrite, ErrorIfExists, Ignore,这几种模式,但是我们在线上的业务几乎全是需要upsert功能的,就是已存在的数据肯定不能覆盖,在mysql中实现就是采用:ON DUPLICATE KEY UPDATE,有没有这样一种实现?官方:不好意思,不提供,dounine:我这有呀,你来用吧。哈哈,为了方便大家的使用我已经把项目...

多一份贡献,多一份环保 3201

告别切换烦恼!用Parallels Desktop的Host-Only网卡,在macOS上直接访问虚拟机里的公司内网

本文详细介绍了如何在macOS上使用Parallels Desktop的Host-Only网卡直接访问虚拟机内的公司内网,告别频繁切换操作系统的烦恼。通过配置Host-Only网络模式,实现主机与虚拟机的安全高效通信,特别适合需要频繁访问内网资源的IT从业者。文章包含分步指南、自动化脚本和常见问题解决方案,帮助用户优化工作流程。

weixin_28739079的博客 362

Spark DataSource V1 & V2 API 一文理解

1. Spark Connector 介绍 Spark Connector 是一个 Spark 的数据连接器,可以通过该连接器进行外部数据系统的读写操作。Spark Connector 包含两部分,分别是 Reader 和 Writer。 DataSource的API的代码位于spark_sql【如spark-sql_2.11-2.4.4.jar】 模块中的org.apache.spark.sql.sources包下,定义了如何从存储系统进行读写的相关 API API分为v1、v2两个版本,v2的代码

penriver的博客 4305

ptrade量化策略之沪深300指数增强

本策略的核心是在沪深300股票池中选股,选择的股票都是市值比较大,业绩比较好的白马股,根据市场相对位置以及基本面因子来选择股票

qq_29301281的博客 1190

[官方培训]19-物理模拟 Epic 肖月 笔记

物理引擎全局解算精度的设置,帧率越高,子步越多得到的模拟结果就越精确。引擎默认情况下是以变化的帧率运行的,但是对于Chaos物理引擎来说。一般子步越小,帧率越固定,效果就会更好更稳定一些。图示的分步选项就是依据下方的最长子步时长和最大步数对动态变化的帧率,进一步的做拆分来保证物理效果。对于影视项目建议都开启分步选项。红色框内有三个迭代次数的设置,这是Chaos基于位置的约束求解算法专用的一个设置,可以简单理解为迭代次数越高,当前帧一个子步内得到的结果就越精确。

Tcohneyn的博客 1545

Multiple sources found for parquet 错误解决

解决:org.apache.spark.sql.AnalysisException: Multiple sources found for parquet (org.apache.spark.sql.execution.datasources.v2.parquet.ParquetDataSourceV2, org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat)

随手积累,典型bug解决。技术栈的系统介绍。 1957

C++cgal库配置+VS2017

Cgal几何图形库在VS2017上的下载、安装与配置。想要一口气下载完所有安装配件的,可以去文章末尾的链接。httpshttpshttpshttpshttpshttpshttpshttpshttpshttpshttpshttpshttpshttpshttps。

dsn3S的博客 1488

Hive 中如何解决多字符分割场景?

前言 本文隶属于专栏《1000个问题搞定大数据技术体系》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢! 本专栏目录结构和参考文献请见1000个问题搞定大数据技术体系 正文 通过 MultiDelimitSerDe 解决多字符分割场景 1、创建表 create table t1 (id String, name string) row format SerDe 'org.apache.hadoop.hive.contrib.SerDe2.MultiDelimitSerD

Shockang的博客 1万+

CATIA二次开发CAA安装

安装资料在网盘里 Win7 64位 以下软件均已管理员身份运行: 1.安装vs2008->自定义安装->选择要安装的功能->Visual C+±>x64编译器和工具 1.2安装SP1 2.安装CATIA V5 R21->win7_XP->CATIA.P3.V5R21.Win64->setup.exe 2.1安装目录改为D盘 2.2环境目录位置默认 3.安装...

qq_39311458的博客 4631

090、Sensor上电时序与帧同步的驱动级实现——以索尼IMX766为例的AVDD/DVDD/IOVDD时序调优

摘要: 本文以索尼IMX766传感器为例,深入探讨了传感器上电时序与帧同步的驱动级实现问题。通过分析某车载项目量产中的高温黑屏故障,揭示了AVDD/DVDD/IOVDD时序偏差导致传感器内部状态机异常的根源。文章详细解读了IMX766三路电源的时序约束(如AVDD与DVDD需在1ms内同步至90%),并提供了驱动代码级实现方案,包括电源使能顺序、延时控制及帧同步配置。针对多摄同步场景,强调了曝光时间寄存器写入一致性的重要性。最后结合产线问题定位经验,提出通过示波器抓取电源波形验证时序合规性的方法。全文聚焦硬

zzfmlxs的博客 258

Apache Spark DataSource V2 介绍及入门编程指南

Apache Spark DataSource V2 介绍及入门编程指南(1) Apache Spark DataSource V2 介绍及入门编程指南(2)

Amazingjadewu 770

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

spark datasourceV1和v2

spark datasource

better_mouse的博客 787

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

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

Spark Paimon 中为什么我指定的分区没有下推

针对于错误的写法,也就是导致读取全量数据的写法,我们分析一下,首先是类型转换阶段,在Spark中,对于类型不匹配的问题,spark会用规则进行转换,具体的规则是。最近在使用 Paimon 的时候遇到了一件很有意思的事情,写的 SQL 居然读取的数据不下推,明明是分区表,但是却全量扫描了。这种情况下,对于文件的读取IO会增大,但是对于shuffle等操作是不会有性能的影响的。对于分区字段来说,我们在写SQL对分区字段进行过滤的时候,保持和分区字段类型一致。可以看到经过了规则转换 所有的过滤条件都下推到了。

monkeyboy_tech的博客 1163

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

学习笔记 --- Spark SparkSQL下Parquet中PushDown的实现

PushDown是一种SQL优化方式,通常用在查询。应用场景: 假设通过DataFrame,df.select(a,b,c).filter(by a).filter(by b).select(c).filter(by c)这样的查询,在optimizer阶段,需要合并多个filters(CombineFilters),并调整算子间的顺序,例如将部分filter移到select等前面(PushPr...

tianyeshiye 581
上一篇: SPARK k8s backend中Executor Rolling(Executor的自动化滚动驱逐)
下一篇: DATA AI Summit 2022提及到的对 aggregate 的优化
鸿乃江边鸟
博客等级 码龄6年 3746粉丝 235原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值