Spark SQL笔记——技术点汇总
目录
概述
- Spark SQL是Spark的结构化数据处理模块。
- Spark SQL特点
- 数据兼容:可从Hive表、外部数据库(JDBC)、RDD、Parquet文件、JSON文件获取数据,可通过Scala方法或SQL方式操作这些数据,并把结果转回RDD。
- 组件扩展:SQL语法解析器、分析器、优化器均可重新定义。
- 性能优化:内存列存储、动态字节码生成等优化技术,内存缓存数据。
- 多语言支持:Scala、Java、Python、R。
原理
组成
- Catalyst优化:优化处理查询语句的整个过程,包括解析、绑定、优化、物理计划等,主要由关系代数(relation algebra)、表达式(expression)以及查询优化(query optimization)组成。
- Spark SQL内核:处理数据的输入输出,从不同数据源(结构化数据Parquet文件JSON文件、Hive表、外部数据库、已有RDD)获取数据,执行查询(expression of queries),并将查询结果输出成DataFrame。
- Hive支持:对Hive数据的处理,主要包括HiveQL、MetaStore、SerDes、UDFs等。
执行流程

- SqlParser对SQL语句解析,生成Unresolved逻辑计划(未提取Schema信息);
- Catalyst分析器结合数据字典(catalog)进行绑定,生成Analyzed逻辑计划,过程中Schema Catalog要提取Schema信息;
- Catalyst优化器对Analyzed逻辑计划优化,按照优化规则得到Optimized逻辑计划;
与Spark Planner交互,应用策略(strategy)到plan,使用Spark Planner将逻辑计划转换成物理计划,然后调用next函数,生成可执行物理计划。
性能
API
应用程序模板
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.hive.HiveContext
object Test {
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("Test")
val sc = new SparkContext(conf)
val sqlContext = new HiveContext(sc)
// ...
}
}
通用读写方法
- Spark SQL内置数据源短名称有json、parquet、jdbc,默认parquet(通过“spark.sql.sources.default”配置)。
- 保存模式:
| Scala/Java | Python | 说明 |
|---|---|---|
| SaveMode.ErrorIfExists | "error" | 默认,如果数据库已经存在,抛出异常 |
| SaveMode.Append | "append" | 如果数据库已经存在,追加DataFrame数据 |
| SaveMode.Overwrite | "overwrite" | 如果数据库已经存在,重写DataFrame数据 |
| SaveMode.Ignore | "ignore" | 如果数据库已经存在,忽略DataFrame数据 |
- 读写文件代码(统一使用sqlContext.read和dataFrame.write)模板:
val dataFrame = sqlContext.read.format("数据源名称").load("文件路径")
val newDataFrame = dataFrame // 操作数据得到新DataFrame
newDataFrame.write.format("数据源名称").save("文件路径")
RDD转为DataFrame
- 方法1
- 方法:使用反射机制推断RDD Schema。
- 场景:运行前知道Schema。
- 特点:代码简洁。
- 示例:
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql.SQLContext
object Test {
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("Test")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
// 将一个RDD隐式转换为一个DataFrame
import sqlContext.implicits._
// 使用case定义Schema(不能超过22个属性)
case class Person(name: String, age: Int)
// 读取文件创建MappedRDD,再将数据写入Person类,隐式转换为DataFrame
val peopleDF = sc.textFile("/test/people.csv").map(_.split(",")).map(cols => Person(cols(0), cols(1).trim.toInt)).toDF()
// DataFrame注册临时表
peopleDF.registerTempTable("table_people")
// SQL
val teenagers = sqlContext.sql("select name, age from table_people where age >= 13 and age <= 19")
teenagers.collect.foreach(println)
}
}
- 方法2
- 方法:以编程方式定义RDD Schema。
- 场景:运行前不知道Schema。
- 示例:
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StringType
import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.Row
object Test {
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("Test")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
// 将一个RDD隐式转换为一个DataFrame
import sqlContext.implicits._
// 使用case定义Schema(不能超过22个属性)
case class Person(name: String, age: Int)
// 读取文件创建MappedRDD
val peopleFile = sc.textFile("/test/people.csv")
// 运行时从某处获取的Schema结构
val schemaArray = Array("name", "age")
// 创建Schema
val schema = StructType(schemaArray.map(fieldName => StructField(fieldName, StringType, true)))
// 将文本转为RDD
val rowRDD = peopleFile.map(_.split(",")).map(cols => Row(cols(0), cols(1).trim))
// 将Schema应用于RDD
val peopleDF = sqlContext.createDataFrame(rowRDD, schema)
// DataFrame注册临时表
peopleDF.registerTempTable("table_people")
// SQL
val teenagers = sqlContext.sql("select name, age from table_people where age >= 13 and age <= 19")
teenagers.collect.foreach(println)
}
}
Parquet文件数据源
- Parquet优点:
- 高效、Parquet采用列式存储避免读入不需要的数据,具有极好的性能和GC;
- 方便的压缩和解压缩,并具有极好的压缩比例;
- 可直接读写Parquet文件,比磁盘更好的缓存效果。
- Spark SQL支持根据Parquet文件自描述自动推断Schema,生成DataFrame。
- 编程示例:
// 加载文件创建DataFrame
val peopleDF = sqlContext.read.load("/test/people.parquet")
peopleDF.printSchema
// DataFrame注册临时表
peopleDF.registerTempTable("table_people")
// SQL
val teenagers = sqlContext.sql("select name, age from table_people where age >= 13 and age <= 19")
teenagers.collect.foreach(println)
- 分区发现(partition discovery)
- 与Hive分区表类似,通过分区列的值对表设置分区目录,加载Parquet数据源可自动发现和推断分区信息。
- 示例:有一个分区列为gender和country的分区表,加载路径“/path/to/table”可自动提取分区信息
path
└── to
└── table
├── gender=male
│ ├── ...
│ │
│ ├── country=US
│ │ └── data.parquet
│ ├── country=CN
│ │ └── data.parquet
│ └── ...
└── gender=female
├── ...
│
├── country=US
│ └── data.parquet
├── country=CN
│ └── data.parquet
└── ...
创建的DataFrame的Schema:
root
|-- name: string (nullable = true)
|-- age: long (nullable = true)
|-- gender: string (nullable = true)
|-- country: string (nullable = true)
* 分区列数据类型:支持numeric和string类型的自动推断,通过“spark.sql.sources.partitionColumnTypeInference.enabled”配置开启或关闭(默认开启),关闭后分区列全为string类型。
JSON文件数据源
- Spark SQL支持根据JSON文件自描述自动推断Schema,生成DataFrame。
- 示例:
// 加载文件创建DataFrame(JSON文件自描述Schema)
val peopleDF = sqlContext.read.format("json").load("/test/people.json")
peopleDF.printSchema
// DataFrame注册临时表
peopleDF.registerTempTable("table_people")
// SQL
val teenagers = sqlContext.sql("select name, age from table_people where age >= 13 and age <= 19")
teenagers.collect.foreach(println)
Hive数据源
- HiveContext
- 操作Hive数据源须创建SQLContext的子类HiveContext对象。
- Standalone集群:添加hive-site.xml到$SPARK_HOME/conf目录。
- YARN集群:添加hive-site.xml到$YARN_CONF_DIR目录;添加Hive元数据库JDBC驱动jar文件到$HADOOP_HOME/lib目录。
- 最简单方法:通过spark-submit命令参数--file和--jar参数分别指定hive-site.xml和Hive元数据库JDBC驱动jar文件。
- 未找到hive-site.xml:当前目录下自动创建metastore_db和warehouse目录。
- 模板:
val sqlContext = new HiveContext(sc)
- 使用HiveQL
- “spark.sql.dialect”配置:SQLContext仅sql,HiveContext支持sql、hiveql(默认)。
- 模板:
sqlContext.sql("HiveQL")
- 支持Hive特性
- Hive查询语句,包括select、group by、order by、cluster by、sort by;
- Hive运算符,包括:关系运算符(=、⇔、==、<>、<、>、>=、<=等)、算术运算符(+、-、*、/、%等)、逻辑运算符(and、&&、or、||等)、复杂类型构造函数、数据函数(sign、ln、cos等)、字符串函数(instr、length、printf);
- 用户自定义函数(UDF);
- 用户自定义聚合函数(UDAF);
- 用户自定义序列化格式(SerDes);
- 连接操作,包括join、{left | right | full} outer join、left semi join、cross join;
- 联合操作(union);
- 子查询:select col from (select a + b as col from t1) t2;
- 抽样(Sampling);
- 解释(Explain);
- 分区表(Partitioned table);
- 所有Hive DDL操作函数,包括create table、create table as select、alter table;
- 大多数Hive数据类型tinyint、smallint、int、bigint、boolean、float、double、string、binary、timestamp、date、array<>、map<>、struct<>。
数据库JDBC数据源
- Spark SQL支持加载数据库表生成DataFrame。
- 模板(注意:需要相关JDBC驱动jar文件)
val jdbcOptions = Map("url" -> "", "driver" -> "", "dbtable" -> "")
sqlContext.read.format("jdbc").options(jdbcOptions).load
- JDBC参数
| 名称 | 说明 |
|---|---|
| url | The JDBC URL to connect to. |
| dbtable | The JDBC table that should be read. Note that anything that is valid in a FROM clause of a SQL query can be used. For example, instead of a full table you could also use a subquery in parentheses. |
| driver | The class name of the JDBC driver to use to connect to this URL. |
| partitionColumn, lowerBound, upperBound, numPartitions | These options must all be specified if any of them is specified. They describe how to partition the table when reading in parallel from multiple workers. partitionColumn must be a numeric column from the table in question. Notice that lowerBound and upperBound are just used to decide the partition stride, not for filtering the rows in table. So all rows in the table will be partitioned and returned. |
| fetchSize | The JDBC fetch size, which determines how many rows to fetch per round trip. This can help performance on JDBC drivers which default to low fetch size (eg. Oracle with 10 rows). |
DataFrame Operation
- 分类:
- DataFrameAction
| 名称 | 说明 |
|---|---|
| collect: Array[Row] | 以Array形式返回DataFrame的所有Row |
| collectAsList: List[Row] | 以List形式返回DataFrame的所有Row |
| count(): Long | 返回DataFrame的Row数目 |
| first(): Row | 返回第一个Row |
| head(): Row | 返回第一个Row |
| show(): Unit | 以表格形式显示DataFrame的前20个Row |
| take(n: Int): Array[Row] | 返回DataFrame前n个Row |
* 基础DataFrame函数(basic DataFrame functions)
| 名称 | 说明 |
|---|---|
| cache(): DataFrame.this.type | 缓存DataFrame |
| columns: Array[String] | 以Array形式返回全部的列名 |
| dtypes: Array[(String, String)] | 以Array形式返回全部的列名和数据类型 |
| explain: Unit | 打印physical plan到控制台 |
| isLocal: Boolean | 返回collect和take是否可以本地运行 |
| persist(newLevel: StorageLevel: DataFrame.this.type | 根据StorageLevel持久化 |
| printSchema(): Unit | 以树格式打印Schema |
| registerTempTable(tableName: String): Unit | 使用给定的名字注册DataFrame为临时表 |
| schema: StructType | 返回DataFrame的Schema |
| toDF(colNames: String*): DataFrame | 返回一个重新指定column的DataFrame |
| unpersist(): DataFrame.this.type | 移除持久化 |
* 集成语言查询(language integrated queries)
| 名称 | 说明 |
|---|---|
| agg(aggExpr: (String, String), aggExpr: (String, String)): DataFrame agg(exprs: Map[String, String]): DataFrame agg(expr: Column, exprs: Column): DataFrame |
在整体DataFrame不分组聚合 |
| apply(colName: String): Column | 以Column形式返回列名为colName的列 |
| as(alias: String): DataFrame as(alias: Symbol): DataFrame |
以一个别名集方式返回一个新DataFrame |
| col(colName: String): Column | 同apply |
| cube(col: String, cols: String*): GroupedData | 使用专门的列(以便聚合),给当前DataFrame创建一个多维数据集 |
| distinct: DataFrame | 对Row去重,返回新DataFrame |
| drop(col: Column): DataFrame | 删除一个列,返回新DataFrame |
| except(other: DataFrame): DataFrame | 集合差,返回新DataFrame |
| filter(conditionExpr: String): DataFrame filter(condition: Column): DataFrame |
使用给定的SQL表达式过滤 |
| groupBy(col: String, cols: String*): GroupedData | 使用给定的列分组DataFrame,以便能够聚合 |
| intersect(other: DataFrame): DataFrame | 交集,返回新DataFrame |
| limit(n: Int): DataFrame | 获取前n行数据,返回新DataFrame |
| join(right: DataFrame):DataFrame join(right: DataFrame, joinExprs: Column):DataFramejoin(right: DataFrame, joinExprs: Column, joinType: String):DataFrame |
Join,第1个为笛卡尔积(Cross Join),第2个为Inner Join |
| orderBy(col: String, cols: String): DataFrame orderBy(sortExprs: Columns): DataFrame |
使用给定表达式排序,返回新DataFrame |
| sample(withReplacement: Boolean, fraction: Double): DataFrame | 使用随机种子,抽样部分行返回新DataFrame |
| select(col: String, cols: String): DataFrame select(cols: Column): DataFrame selectExpr(exprs: String*): DataFrame |
选择一个列集合 |
| sort(col: String, cols: String): DataFrame sort(sortExprs: Column): DataFrame |
同orderBy |
| unionAll(other: DataFrame): DataFrame | 集合和,返回新DataFrame |
| where(conditionExpr: String): DataFrame where(condition: Column): DataFrame |
同filter |
| withColumn(colName, col: Column) | 添加新列,返回新DataFrame |
| withColumnRenamed(existingName: String, newName: String) | 重命名列,返回新DataFrame |
* 输出操作
| 名称 | 说明 |
|---|---|
| write | 保存DataFrame内容到外部文件存储、Hive表: dataFrame.write.save("路径") // 默认Parquet数据源 dataFrame.write.format("数据源名称").save("路径") dataFrame.write.saveAsTable("表名") dataFrame.write.insertInto("表名") |
* RDD Operation
DataFrame本质是一个拥有多个分区的RDD,支持RDD Operation:coalesce、flatMap、foreach、foreachPartition、javaRDD、map、mapPartitions、repartition、toJSON、toJavaRDD等。
性能调优
缓存数据
- 内存列式(in-memory columnar format)缓存:Spark SQL仅扫描需要的列,并自动调整压缩比使内存使用率和GC压力最小化。
- 相关配置:
| 名称 | 说明 |
|---|---|
| spark.sql.inMemoryColumnarStorage.compressed | true |
| spark.sql.inMemoryColumnarStorage.batchSize | 10000 |
- 缓存/移除缓存代码模板:
// 缓存方法1(lazy)
sqlContext.cacheTable("表名")
// 缓存方法2(lazy)
dataFrame.cache()
// 移除缓存(eager)
sqlContext.uncacheTable("表名")
// 注意:RDD的cache方法不是列式缓存
rdd.cache()
参数调优
| 名称 | 默认值 | 说明 |
|---|---|---|
| spark.sql.autoBroadcastJoinThreshold | 10485760 (10MB) | 当执行Join时,对一个将要被广播到所有Worker的表配置最大字节,通过设置为-1禁止广播 |
| spark.sql.tungsten.enabled | true | 配置是否开启Tungsten优化,默认开启 |
| spark.sql.shuffle.partitions | 200 | 当执行Join或Aggregation进行Shuffle时,配置可用分区数 |
案例
数据准备
- 数据结构
- 职工基本信息(people)
| 字段 | 说明 |
|---|---|
| name | 姓名 |
| id | ID |
| gender | 性别 |
| age | 年龄 |
| year | 入职年份 |
| position | 职位 |
| deptid | 所在部门ID |
* 部门基本信息(department)
| 字段 | 说明 |
|---|---|
| name | 名称 |
| deptid | ID |
* 职工考勤信息(attendance)
| 字段 | 说明 |
|---|---|
| id | 职工ID |
| year | 年 |
| month | 月 |
| overtime | 加班 |
| latetime | 迟到 |
| absenteeism | 旷工 |
| leaveearlytime | 早退小时 |
* 职工工资清单(salary)
| 字段 | 说明 |
|---|---|
| id | 职工ID |
| salary | 工资 |
- 建库、建表(spark-shell方式)
sqlContext.sql("create database hrs")
sqlContext.sql("use hrs")
sqlContext.sql("create external table if not exists people(name string, id int, gender string, age int, year int, position string, deptid int) row format delimited fields terminated by ',' lines terminated by '\n' location '/test/hrs/people'")
sqlContext.sql("create external table if not exists department(name string, deptid int) row format delimited fields terminated by ',' lines terminated by '\n' location '/test/hrs/department'")
sqlContext.sql("create external table if not exists attendance(id int, year int, month int, overtime int, latetime int, absenteeism int, leaveearlytime int) row format delimited fields terminated by ',' lines terminated by '\n' location '/test/hrs/attendance'")
sqlContext.sql("create external table if not exists salary(id int, salary int) row format delimited fields terminated by ',' lines terminated by '\n' location '/test/hrs/salary'")
- 测试数据
- 职工基本信息(people.csv)
Michael,1,male,37,2001,developer,2
Andy,2,female,33,2003,manager,1
Justin,3,female,23,2013,recruitingspecialist,3
John,4,male,22,2014,developer,2
Herry,5,male,27,2010,developer,1
Brewster,6,male,37,2001,manager,2
Brice,7,female,30,2003,manager,3
Justin,8,male,23,2013,recruitingspecialist,3
John,9,male,22,2014,developer,1
Herry,10,female,27,2010,recruitingspecialist,3
* 部门基本信息(department.csv)
manager,1
researchhanddevelopment,2
humanresources,3
* 职工考勤信息(attendance.csv)
1,2015,12,0,2,4,0
2,2015,8,5,0,5,3
3,2015,3,16,4,1,5
4,2015,3,0,0,0,0
5,2015,3,0,3,0,0
6,2015,3,32,0,0,0
7,2015,3,0,16,3,32
8,2015,19,36,0,0,0
9,2015,5,6,30,0,2
10,2015,10,6,56,40,0
1,2014,12,0,2,4,0
2,2014,8,5,0,5,3
3,2014,3,16,4,1,5
4,2014,3,0,0,0,0
5,2014,3,0,3,0,0
6,2014,3,32,0,0,0
7,2014,3,0,16,3,32
8,2014,19,36,0,0,0
9,2014,5,6,30,0,2
10,2014,10,6,56,40,0
* 职工工资清单(salary.csv)
1,5000
2,10000
3,6000
4,7000
5,5000
6,11000
7,12000
8,5500
9,6500
10,4500
- 上传数据文件至HDFS
hadoop fs -mkdir /test/hrs/people
hadoop fs -mkdir /test/hrs/department
hadoop fs -mkdir /test/hrs/attendance
hadoop fs -mkdir /test/hrs/salary
hadoop fs -put people.csv /test/hrs/people
hadoop fs -put department.csv /test/hrs/department
hadoop fs -put attendance.csv /test/hrs/attendance
hadoop fs -put salary.csv /test/hrs/salary
查询部门职工数
- HiveQL方式
sqlContext.sql("select d.name, count(p.id) from people p join department d on p.deptid = d.deptid group by d.name").show
- Scala方式
val peopleDF = sqlContext.table("people")
val departmentDF = sqlContext.table("department")
peopleDF.join(departmentDF, peopleDF("deptid") === departmentDF("deptid")).groupBy(departmentDF("name")).agg(count(peopleDF("id")).as("cnt")).select(departmentDF("name"), col("cnt")).show
- 结果

查询各部门职工工资总数,并排序
- HiveQL方式
sqlContext.sql("select d.name, sum(s.salary) as salarysum from people p join department d on p.deptid = d.deptid join salary s on p.id = s.id group by d.name order by salarysum").show
- Scala方式
val peopleDF = sqlContext.table("people")
val departmentDF = sqlContext.table("department")
val salaryDF = sqlContext.table("salary")
peopleDF.join(departmentDF, peopleDF("deptid") === departmentDF("deptid")).join(salaryDF, peopleDF("id") === salaryDF("id")).groupBy(departmentDF("name")).agg(sum(salaryDF("salary")).as("salarysum")).orderBy("salarysum").select(departmentDF("name"), col("salarysum")).show
- 结果

查询各部门职工考勤信息
- HiveQL方式
sqlContext.sql("select d.name, ai.year, sum(ai.attinfo) from (select p.id, p.deptid, a.year, a.month, (a.overtime - a.latetime - a.absenteeism - a.leaveearlytime) as attinfo from attendance a join people p on a.id = p.id) ai join department d on ai.deptid = d.deptid group by d.name, ai.year").show
- Scala方式
val attendanceDF = sqlContext.table("attendance")
val peopleDF = sqlContext.table("people")
val departmentDF = sqlContext.table("department")
val subqueryDF = attendanceDF.join(peopleDF, attendanceDF("id") === peopleDF("id")).select(peopleDF("id"), peopleDF("deptid"), attendanceDF("year"), attendanceDF("month"), (attendanceDF("overtime") - attendanceDF("latetime") - attendanceDF("absenteeism") - attendanceDF("leaveearlytime")).as("attinfo"))
subqueryDF.join(departmentDF, subqueryDF("deptid") === departmentDF("deptid")).groupBy(departmentDF("name"), subqueryDF("year")).agg(sum(subqueryDF("attinfo")).as("attinfosum")).select(departmentDF("name"), subqueryDF("year"), col("attinfosum")).show
- 结果

Spark SQL笔记——技术点汇总的更多相关文章
- Spark Streaming笔记——技术点汇总
目录 目录 概况 原理 API DStream WordCount示例 Input DStream Transformation Operation Output Operation 缓存与持久化 C ...
- Spark笔记——技术点汇总
目录 概况 手工搭建集群 引言 安装Scala 配置文件 启动与测试 应用部署 部署架构 应用程序部署 核心原理 RDD概念 RDD核心组成 RDD依赖关系 DAG图 RDD故障恢复机制 Standa ...
- Spark SQL笔记
HDFS HDFS架构 1.Master(NameNode/NN) 对应 N个Slaves(DataNode/NN)2.一个文件会被拆分成多个块(Block)默认:128M例: 130M ==> ...
- Hive sql & Spark sql笔记
记录了日常使用时遇到的特殊的查询语句.不断更新- 1. SQL查出内容输出到文件 hive -e "...Hive SQL..." > /tmp/out sparkhive ...
- Spark SQL 笔记
Spark SQL 简介 SparkSQL 的前身是 Shark, SparkSQL 产生的根本原因是其完全脱离了 Hive 的限制.(Shark 底层依赖于 Hive 的解析器, 查询优化器) Sp ...
- Hadoop笔记——技术点汇总
目录 · 概况 · Hadoop · 云计算 · 大数据 · 数据挖掘 · 手工搭建集群 · 引言 · 配置机器名 · 调整时间 · 创建用户 · 安装JDK · 配置文件 · 启动与测试 · Clo ...
- Java并发编程笔记——技术点汇总
目录 · 线程安全 · 线程安全的实现方法 · 互斥同步 · 非阻塞同步 · 无同步 · volatile关键字 · 线程间通信 · Object.wait()方法 · Object.notify() ...
- Storm笔记——技术点汇总
目录 概况 手工搭建集群 引言 安装Python 配置文件 启动与测试 应用部署 参数配置 Storm命令 原理 Storm架构 Storm组件 Stream Grouping 守护进程容错性(Dae ...
- Hive笔记——技术点汇总
目录 · 概况 · 手工安装 · 引言 · 创建HDFS目录 · 创建元数据库 · 配置文件 · 测试 · 原理 · 架构 · 与关系型数据库对比 · API · WordCount · 命令 · 数 ...
随机推荐
- Hadoop集群搭建(非HA)
1.准备Linux环境 1.0先将虚拟机的网络模式选为NAT 1.1修改主机名 vi /etc/sysconfig/network NETWORKING=yes HOSTNAME=itcast ### ...
- Coursera 机器学习笔记(八)
主要为第十周内容:大规模机器学习.案例.总结 (一)随机梯度下降法 如果有一个大规模的训练集,普通的批量梯度下降法需要计算整个训练集的误差的平方和,如果学习方法需要迭代20次,这已经是非常大的计算代价 ...
- PHP的面向对象 — 封装、继承、多态
K在上一次的基础篇中给大家介绍了一下关于PHP中数组和字符串的使用方法等,这一次,K决定一次性大放送,给大家分享一下PHP中面向对象的三大特性:封装.继承.多态三个方面的知识. 一.封装 在PHP中, ...
- 后台开发之IO缓冲区管理
Linux系统IO中write原型为 ssize_t write(int filedes, const void * buff, size_t nbytes) ; 当调用write写数据的时候,调 ...
- Spring学习(21)--- AOP之Advice应用(上)
前置通知(Before advice) 在某个连接点(join point)之前执行的通知,但不能阻止连接点前的执行(除非它抛出异常) 返回后通知(After returning advice) 在某 ...
- Grunt压缩HTML和CSS
我的小伙伴们!我明明 在压缩图片之前发过一篇,关于Grunt压缩cCSS是和HTML的!但是不知道为什么,今天再一看.迷之消失了! 没办法.只好今天在写一次,从头开始!首先.我来介绍一下为什么要用构建 ...
- python每天一个小练习-强壮的密码
强壮的密码 题目来源 checkio 需求 斯蒂芬和索菲亚对于一切都使用简单的密码,忘记了安全性.请你帮助尼古拉开发一个密码安全检查模块 如果密码的长度大于或等于10个符号,至少有一个数字,一个大写字 ...
- tomcat之 JDK8.0安装、tomcat-8.5.15安装
前言:JDK(Java Development Kit)是Sun Microsystems针对Java开发员的产品.自从Java推出以来,JDK已经成为使用最广泛的Java SDK. JDK是整个Ja ...
- 进入MVC处理通道
这一篇主要讲如何通过Asp.net处理管道把请求交给MVC进行处理的(进入MVC处理通道). 首先来看一下经典的Asp.net处理管道的生命周期. 我们知道一个ASP.NET应用程序可以有多个Http ...
- MySQL访问控制实现原理
MySQL访问控制实现原理 MySQL 访问控制实际上由两个功能模块共同组成,从第一篇的第二章架构组成中可以看到,一个是负责 “看守 MySQL 大门”的用户管理模块,另一个就是负责监控来访者每一个动 ...