MlLib--逻辑回归笔记

批量梯度下降的逻辑回归可以参考这篇文章:http://blog.csdn.net/pakko/article/details/37878837

看了一些Scala语法后,打算看看MlLib的机器学习算法的并行化,那就是逻辑回归,找到package org.apache.spark.mllib.classification下的LogisticRegressionWithSGD这个类,直接搜train()函数。

  def train(input: RDD[LabeledPoint],numIterations: Int,stepSize: Double,miniBatchFraction: Double,initialWeights: Vector): LogisticRegressionModel = {new LogisticRegressionWithSGD(stepSize, numIterations, 0.0, miniBatchFraction).run(input, initialWeights)}

发现它调用了GeneralizedLinearAlgorithm下的一个run函数,这个类GeneralizedLinearAlgorithm是个抽象类,并且在GeneralizedLinearAlgorithm.scala文件下,并且类LogisticRegressionWithSGD是继承了GeneralizedLinearAlgorithm

  def run(input: RDD[LabeledPoint], initialWeights: Vector): M = {if (numFeatures < 0) {numFeatures = input.map(_.features.size).first()}if (input.getStorageLevel == StorageLevel.NONE) {logWarning("The input data is not directly cached, which may hurt performance if its"+ " parent RDDs are also uncached.")}// Check the data properties before running the optimizerif (validateData && !validators.forall(func => func(input))) {throw new SparkException("Input validation failed.")}/*** Scaling columns to unit variance as a heuristic to reduce the condition number:** During the optimization process, the convergence (rate) depends on the condition number of* the training dataset. Scaling the variables often reduces this condition number* heuristically, thus improving the convergence rate. Without reducing the condition number,* some training datasets mixing the columns with different scales may not be able to converge.** GLMNET and LIBSVM packages perform the scaling to reduce the condition number, and return* the weights in the original scale.* See page 9 in http://cran.r-project.org/web/packages/glmnet/glmnet.pdf** Here, if useFeatureScaling is enabled, we will standardize the training features by dividing* the variance of each column (without subtracting the mean), and train the model in the* scaled space. Then we transform the coefficients from the scaled space to the original scale* as GLMNET and LIBSVM do.** Currently, it's only enabled in LogisticRegressionWithLBFGS*/val scaler = if (useFeatureScaling) {new StandardScaler(withStd = true, withMean = false).fit(input.map(_.features))} else {null}// Prepend an extra variable consisting of all 1.0's for the intercept.// TODO: Apply feature scaling to the weight vector instead of input data.val data =if (addIntercept) {if (useFeatureScaling) {input.map(lp => (lp.label, appendBias(scaler.transform(lp.features)))).cache()} else {input.map(lp => (lp.label, appendBias(lp.features))).cache()}} else {if (useFeatureScaling) {input.map(lp => (lp.label, scaler.transform(lp.features))).cache()} else {input.map(lp => (lp.label, lp.features))}}/*** TODO: For better convergence, in logistic regression, the intercepts should be computed* from the prior probability distribution of the outcomes; for linear regression,* the intercept should be set as the average of response.*/val initialWeightsWithIntercept = if (addIntercept && numOfLinearPredictor == 1) {appendBias(initialWeights)} else {/** If `numOfLinearPredictor > 1`, initialWeights already contains intercepts. */initialWeights}val weightsWithIntercept = optimizer.optimize(data, initialWeightsWithIntercept) //这里进入优化val intercept = if (addIntercept && numOfLinearPredictor == 1) {weightsWithIntercept(weightsWithIntercept.size - 1)} else {0.0}var weights = if (addIntercept && numOfLinearPredictor == 1) {Vectors.dense(weightsWithIntercept.toArray.slice(0, weightsWithIntercept.size - 1))} else {weightsWithIntercept}/*** The weights and intercept are trained in the scaled space; we're converting them back to* the original scale.** Math shows that if we only perform standardization without subtracting means, the intercept* will not be changed. w_i = w_i' / v_i where w_i' is the coefficient in the scaled space, w_i* is the coefficient in the original space, and v_i is the variance of the column i.*/if (useFeatureScaling) {if (numOfLinearPredictor == 1) {weights = scaler.transform(weights)} else {/*** For `numOfLinearPredictor > 1`, we have to transform the weights back to the original* scale for each set of linear predictor. Note that the intercepts have to be explicitly* excluded when `addIntercept == true` since the intercepts are part of weights now.*/var i = 0val n = weights.size / numOfLinearPredictorval weightsArray = weights.toArraywhile (i < numOfLinearPredictor) {val start = i * nval end = (i + 1) * n - { if (addIntercept) 1 else 0 }val partialWeightsArray = scaler.transform(Vectors.dense(weightsArray.slice(start, end))).toArraySystem.arraycopy(partialWeightsArray, 0, weightsArray, start, partialWeightsArray.size)i += 1}weights = Vectors.dense(weightsArray)}}// Warn at the end of the run as well, for increased visibility.if (input.getStorageLevel == StorageLevel.NONE) {logWarning("The input data was not directly cached, which may hurt performance if its"+ " parent RDDs are also uncached.")}// Unpersist cached dataif (data.getStorageLevel != StorageLevel.NONE) {data.unpersist(false)}createModel(weights, intercept)}

 在上面代码中的optimizer.optimize,传入了数据data和初始化的theta,然后optimizer在LogisticRegressionWithSGD中被初始化为:

class LogisticRegressionWithSGD private[mllib] (private var stepSize: Double,private var numIterations: Int,private var regParam: Double,private var miniBatchFraction: Double)extends GeneralizedLinearAlgorithm[LogisticRegressionModel] with Serializable {private val gradient = new LogisticGradient()private val updater = new SquaredL2Updater()@Since("0.8.0")override val optimizer = new GradientDescent(gradient, updater).setStepSize(stepSize).setNumIterations(numIterations).setRegParam(regParam).setMiniBatchFraction(miniBatchFraction)override protected val validators = List(DataValidators.binaryLabelValidator)/*** Construct a LogisticRegression object with default parameters: {stepSize: 1.0,* numIterations: 100, regParm: 0.01, miniBatchFraction: 1.0}.*/@Since("0.8.0")def this() = this(1.0, 100, 0.01, 1.0)override protected[mllib] def createModel(weights: Vector, intercept: Double) = {new LogisticRegressionModel(weights, intercept)}
}

 optimizer被赋值为GradientDescent(gradient, updater),然后又看GradientDescent这个类:

class GradientDescent private[spark] (private var gradient: Gradient, private var updater: Updater)extends Optimizer with Logging {private var stepSize: Double = 1.0private var numIterations: Int = 100private var regParam: Double = 0.0private var miniBatchFraction: Double = 1.0private var convergenceTol: Double = 0.001...@DeveloperApidef optimize(data: RDD[(Double, Vector)], initialWeights: Vector): Vector = {val (weights, _) = GradientDescent.runMiniBatchSGD(data,gradient,updater,stepSize,numIterations,regParam,miniBatchFraction,initialWeights,convergenceTol)weights}
}

 发现调用的是随机梯度下降的miniBatch方法,runMiniBatchSGD:

  def runMiniBatchSGD(data: RDD[(Double, Vector)],gradient: Gradient,updater: Updater,stepSize: Double,numIterations: Int,regParam: Double,miniBatchFraction: Double,initialWeights: Vector,convergenceTol: Double): (Vector, Array[Double]) = {// convergenceTol should be set with non minibatch settingsif (miniBatchFraction < 1.0 && convergenceTol > 0.0) {logWarning("Testing against a convergenceTol when using miniBatchFraction " +"< 1.0 can be unstable because of the stochasticity in sampling.")}val stochasticLossHistory = new ArrayBuffer[Double](numIterations)// Record previous weight and current one to calculate solution vector differencevar previousWeights: Option[Vector] = Nonevar currentWeights: Option[Vector] = Noneval numExamples = data.count()// if no data, return initial weights to avoid NaNsif (numExamples == 0) {logWarning("GradientDescent.runMiniBatchSGD returning initial weights, no data found")return (initialWeights, stochasticLossHistory.toArray)}if (numExamples * miniBatchFraction < 1) {logWarning("The miniBatchFraction is too small")}// Initialize weights as a column vectorvar weights = Vectors.dense(initialWeights.toArray)val n = weights.size/*** For the first iteration, the regVal will be initialized as sum of weight squares* if it's L2 updater; for L1 updater, the same logic is followed.*/var regVal = updater.compute(weights, Vectors.zeros(weights.size), 0, 1, regParam)._2 //计算正则化的值var converged = false // indicates whether converged based on convergenceTolvar i = 1while (!converged && i <= numIterations) { //迭代开始,在小于最大迭代数的时候不断运行val bcWeights = data.context.broadcast(weights)// Sample a subset (fraction miniBatchFraction) of the total data// compute and sum up the subgradients on this subset (this is one map-reduce)val (gradientSum, lossSum, miniBatchSize) = data.sample(false, miniBatchFraction, 42 + i).treeAggregate((BDV.zeros[Double](n), 0.0, 0L))(seqOp = (c, v) => {// c: (grad, loss, count), v: (label, features)val l = gradient.compute(v._2, v._1, bcWeights.value, Vectors.fromBreeze(c._1)) //计算一个batch中每条数据的梯度(c._1, c._2 + l, c._3 + 1)},combOp = (c1, c2) => {// c: (grad, loss, count)(c1._1 += c2._1, c1._2 + c2._2, c1._3 + c2._3) //将batch中所有数据的梯度相加,损失函数值相加,记录batch的size})if (miniBatchSize > 0) {/*** lossSum is computed using the weights from the previous iteration* and regVal is the regularization value computed in the previous iteration as well.*/stochasticLossHistory.append(lossSum / miniBatchSize + regVal) //原来损失函数是这样计算batch的总损失值除以batchSize再加上正则化值val update = updater.compute(weights, Vectors.fromBreeze(gradientSum / miniBatchSize.toDouble), //更新权重和下次的正则化值stepSize, i, regParam)weights = update._1regVal = update._2previousWeights = currentWeightscurrentWeights = Some(weights)if (previousWeights != None && currentWeights != None) {converged = isConverged(previousWeights.get,currentWeights.get, convergenceTol)}} else {logWarning(s"Iteration ($i/$numIterations). The size of sampled batch is zero")}i += 1}logInfo("GradientDescent.runMiniBatchSGD finished. Last 10 stochastic losses %s".format(stochasticLossHistory.takeRight(10).mkString(", ")))(weights, stochasticLossHistory.toArray)}

 发现要对Batch中每一条数据计算梯度,调用的是gradient.compute函数,对于二值分类:

  override def compute(data: Vector,label: Double,weights: Vector,cumGradient: Vector): Double = {val dataSize = data.size// (weights.size / dataSize + 1) is number of classesrequire(weights.size % dataSize == 0 && numClasses == weights.size / dataSize + 1)numClasses match {case 2 =>/*** For Binary Logistic Regression.** Although the loss and gradient calculation for multinomial one is more generalized,* and multinomial one can also be used in binary case, we still implement a specialized* binary version for performance reason.*/val margin = -1.0 * dot(data, weights)val multiplier = (1.0 / (1.0 + math.exp(margin))) - labelaxpy(multiplier, data, cumGradient) //梯度的计算就是multiplier * data即,(h(x) - y)*xif (label > 0) {// The following is equivalent to log(1 + exp(margin)) but more numerically stable.MLUtils.log1pExp(margin) //返回损失函数值} else {MLUtils.log1pExp(margin) - margin}... //下面有多分类,还没看
}

 利用treeAggregate并行化batch所有数据后,得到gradientSum要除以miniBatchSize,然后进入updater.compute进行权重theta和正则化值的更新,为了下一次迭代:

@DeveloperApi
class SquaredL2Updater extends Updater {override def compute(weightsOld: Vector,gradient: Vector,stepSize: Double,iter: Int,regParam: Double): (Vector, Double) = {// add up both updates from the gradient of the loss (= step) as well as// the gradient of the regularizer (= regParam * weightsOld)// w' = w - thisIterStepSize * (gradient + regParam * w)// w' = (1 - thisIterStepSize * regParam) * w - thisIterStepSize * gradient //这个就是权重更新的迭代式子,这个是L2正则化后的更新,神奇的是(1 - thisIterStepSize * regParam)val thisIterStepSize = stepSize / math.sqrt(iter)                           //记得更新式子不是w‘ = w - alpha*gradient alpha就是学习率也就是thisIterStepSizeval brzWeights: BV[Double] = weightsOld.toBreeze.toDenseVector              //你会发现alpha = thisIterStepSize = 1/sqrt(iter)也就是随着迭代次数越多学习率越低,迈出的步伐越小brzWeights :*= (1.0 - thisIterStepSize * regParam)brzAxpy(-thisIterStepSize, gradient.toBreeze, brzWeights)val norm = brzNorm(brzWeights, 2.0)(Vectors.fromBreeze(brzWeights), 0.5 * regParam * norm * norm)              //正则化值就是w'的二范数的平方乘以正则化参数regParam乘以0.5}
}

 

转载于:https://www.cnblogs.com/Key-Ky/p/5246093.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/396708.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql相关命令操作

2019独角兽企业重金招聘Python工程师标准>>> 远程连接容器中的mysql&#xff1a;mysql -h 192.168.5.116 -P 3306 -u root -p123456 启动mysql容器&#xff1a; $ sudo docker pull mysql:5.6.35 $ sudo docker run --name mysql -p 12345:3306 -e MYSQL_ROOT_PASSW…

html实体注册商标,html 注册商标,html 注册商标代码

html中注册的页面用什么标签写好对于html中的注册页面&#xff0c;策朋专业办理商标注册、专利申请、版权登记保护&#xff0c;需要一个表格。使用标签&#xff0c;输入和按钮标签来组合成就。使用html作为注册页面。实际上&#xff0c;只要您能达到期望的效果&#xff0c;它的…

java已知一个二叉树_#二叉树复习#

#二叉树复习#目录满二叉树完全二叉树平衡二叉树二叉树的主要性质--二叉树的度--二叉树的深度计算二叉树的遍历其他符号变量结点总数深度度为0的结点数/叶子结点数度为1的结点数度为2的结点数什么是满二叉树&#xff1f;二叉树每层的结点数为。满二叉树总结点数&#xff1a;。图…

hashtable - hashmap

http://www.importnew.com/24822.html转载于:https://www.cnblogs.com/qinqiu/p/9711147.html

java 反射机制_基础篇:深入解析JAVA反射机制

反射的概念java 的放射机制&#xff1a;在程序运行时&#xff0c;程序有能力获取一个类的所有方法和属性&#xff1b;并且对于任意一个对象&#xff0c;可以调用它的任意方法或者获取其属性通俗解析&#xff1a;java 文件需要编译成. class 文件才能被 jvm 加载使用, 对象的. c…

构建之法阅读笔记01

本学期阅读计划有两个&#xff0c;一个是《构建之法》&#xff0c;另一个是《大道至简》。 在快速阅读构建之法后&#xff0c;我想提一下几个问题&#xff1a; 1、软件程序软件工程&#xff0c;那么只会软件工程是怎样具体详细的将程序变成合格的软件的&#xff1f; 2、效能分析…

html div float center,跨浏览器实现float:center

跨浏览器实现float:center互联网 发布时间&#xff1a;2008-10-17 19:26:11 作者&#xff1a;佚名 我要评论原文&#xff1a;http://www.macji.com/blog/article/to-achieve-cross-browser-css-float-center/to-achieve-cross-browser-css-float-center/我们都知道float…

博弈论中:纳什均衡、纯策略纳什均衡、混合策略纳什均衡、占优策略

纳什均衡 纳什均衡是由约翰福布斯纳什&#xff08;John Forbes Nash&#xff09;在20世纪50年代提出的博弈论概念&#xff0c;用于描述博弈中的一种稳定状态。在纳什均衡状态下&#xff0c;每个参与者都假定其他参与者的策略是已知的&#xff0c;他们选择的策略是最优的&#…

工具_HBuilder使用快捷方式

HBuilder常用快捷键大概共9类&#xff08;【4 13 3】文件、编辑、插入&#xff1b;【4 9 8】选择、跳转、查找&#xff1b;【1 1 6】运行、工具、视图&#xff09; 1.文件(4) 新建 Ctrl N 关闭 Ctrl F4 全部关闭 Ctrl Shift F4 属性 Alt Enter 2.编辑(13) 激活代码助…

oracle左连接没用_一周零基础学完Oracle数据库第三天02

四、 多表查询1 什么是多表查询多表查询&#xff1a;当查询的数据并不是来源一个表时&#xff0c;需要使用多表链接操作完成查询。根据 不同表中的数据之间的关系查询相关联的数据。多表链接方式&#xff1a; 内连接&#xff1a;连接两个表&#xff0c;通过相等或不等判断链接列…

weblogic启动项目报错找不到类_启动类报错是经常出现的事但是单一的从一个地方找原因会越找越错...

Error starting ApplicationContext. To display the conditions report rerun your application with debug enabled.当我们看到这个报错的时候有的说是jar包重复&#xff0c;有的说是Controller包和Application包处于平行位置&#xff0c;还有的觉得是RequestMapping的valu…

fis

fis3实时刷新 npm install -g fis3 进入相关目录 发布&#xff1a; fis3 release 启动&#xff1a; fis3 server start // 服务启动后&#xff0c;会一直存在&#xff0c;重启或者fis3 server stop 才会关闭服务 自动刷新 fis3 release -wL关闭服务 fis3 server stop …

深入理解javascript原型和闭包(7)——原型的灵活性

在Java和C#中&#xff0c;你可以简单的理解class是一个模子&#xff0c;对象就是被这个模子压出来的一批一批月饼&#xff08;中秋节刚过完&#xff09;。压个啥样&#xff0c;就得是个啥样&#xff0c;不能随便动&#xff0c;动一动就坏了。 而在javascript中&#xff0c;就没…

微型计算机一般不采用的控制方式,微型计算机控制作业.doc

作业一PID控制器引言在实际的过程控制与运动控制系统中&#xff0c;PID家族占据有相当的地位&#xff0c;据统计&#xff0c;工业控制的控制器中PID类控制占有90%以上。PID控制器是最早出现的控制器类型&#xff0c;因为其结构简单&#xff0c;各个控制器参数有着明显的物理意义…

js根据毫米/厘米算像素px

<html><meta http-equiv"content-type" content"text/html;charsetutf-8"><body> 纸张宽度(毫米mm)&#xff1a;<input type"text" id"width" value"10"> <span id"width_px"><…

c语言为什么有这么多的编程环境?_为什么98%的程序员学编程都会从C语言开始?...

在互联网蓬勃发展的时代&#xff0c;有一类人做出了巨大的贡献&#xff0c;这一群人被大家称之为程序员&#xff0c;怎样才能成为一名优秀的程序员呢&#xff0c;为什么每一个程序员都需要学习C语言呢&#xff1f;就让我来跟大家分享分享&#xff1a;壹第一&#xff1a;相比较其…

怎么把电脑上的python软件卸载干净_怎么把一个软件卸载干净_把一个软件卸载干净的两种方法-系统城...

平时使用电脑肯定有卸载软件的操作&#xff0c;一般人直接用户桌面的快捷方式删除&#xff0c;表示软件已经卸载干净了&#xff0c;因为在桌面已经看不见了。其实大部分都没有卸载干净&#xff0c;如果没卸载干净&#xff0c;下载就无法安装了&#xff0c;因为之前还有残留文件…

2.x最终照着教程,成功使用OpenGL ES 绘制纹理贴图,添加了灰度图

在之前成功绘制变色的几何图形之后&#xff0c;今天利用Openg ES的可编程管线绘制出第一张纹理。学校时候不知道OpenGL的重要性&#xff0c;怕晦涩的语法。没有跟老师学习OpenGL的环境配置&#xff0c;现在仅仅能利用cocos2dx 2.2.3 配置好的环境学习OpenGL ES。源码来自《coco…

C# Dapper 简单实例

/// <summary>/// 分页信息/// </summary>public class PageInfo<T>{/// <summary>/// 分页信息/// </summary>public PageInfo(){}/// <summary>/// 总页数/// </summary>public long TotalCount{get; set;}/// <summary>///…

Angular 星级评分组件

一、需求演变及描述&#xff1a; 1. 有一个“客户对公司的总体评价”的字段&#xff08;evalutation&#xff09;。字段为枚举类型&#xff0c;0-5&#xff0c;对应关系为&#xff1a;0-暂无评价&#xff0c;1-很差&#xff0c;2-差&#xff0c;3-一般&#xff0c;4-好&#xf…