You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by yanboliang <gi...@git.apache.org> on 2015/09/05 09:47:05 UTC
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
GitHub user yanboliang opened a pull request:
https://github.com/apache/spark/pull/8611
[SPARK-8518] [ML] Log-linear models for survival analysis
Log-linear models for survival analysis
You can merge this pull request into a Git repository by running:
$ git pull https://github.com/yanboliang/spark spark-8518
Alternatively you can review and apply these changes as the patch at:
https://github.com/apache/spark/pull/8611.patch
To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:
This closes #8611
----
commit 0edabbb2b986ed1da2bd3ce309d95efa2f6bc37e
Author: Yanbo Liang <yb...@gmail.com>
Date: 2015-09-05T07:33:38Z
initial implementation of log-linear survival analysis
commit 7f2a31db621cbbef9c2221e4466e1d79b2cbac42
Author: Yanbo Liang <yb...@gmail.com>
Date: 2015-09-05T07:42:48Z
fix test case issue
----
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141337341
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42637/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532356
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
--- End diff --
* minor: Should we call it `censorCol` or `censoredCol`? I don't know which one is better.
* the second `[String]` is not necessary
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532367
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
--- End diff --
* `AFTSurvivalRegression` -> `AFTSurvivalRegressor` to be consistent with other estimator names.
* Add `@Since` version to class, constructor, and public variables in the constructor.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811902
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
--- End diff --
`it censored` -> `censored`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39750108
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ lambda
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, weights, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * For random lifetime T_{i} of subjects i = 1, ..., n, with possible right-censoring,
+ * the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The the log of scale parameter,
+ * the intercept and weights/coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ private val beta = weights.slice(1, weights.length)
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
--- End diff --
It has been checked [here](https://github.com/apache/spark/pull/8611/files#diff-e277fd0bc21f825d3196b4551c01fe5fR359).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138270800
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138277247
[Test build #42091 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42091/console) for PR 8611 at commit [`c30a1c2`](https://github.com/apache/spark/commit/c30a1c2c6e256380032441c3e52adaeb5f9be1da).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTRegression(override val uid: String)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39538066
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
--- End diff --
remove `val lambda = ` and use `BLAS.dot`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141333239
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141337307
[Test build #42637 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42637/console) for PR 8611 at commit [`aa37878`](https://github.com/apache/spark/commit/aa37878c50ef6e7722a615298240ba6e61ea083c).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)`
* ` require(censor == 1.0 || censor == 0.0, "censor of class AFTPoint must be 1.0 or 0.0")`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39750238
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTSurvivalRegressionSuite.scala ---
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.util.Random
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.{Row, DataFrame}
+
+private[ml] case class AFTPoint(features: Vector, censored: Double, label: Double)
+
+class AFTSurvivalRegressionSuite extends SparkFunSuite with MLlibTestSparkContext {
+
+ @transient var datasetUnivariate: DataFrame = _
+ @transient var datasetMultivariate: DataFrame = _
+
+ override def beforeAll(): Unit = {
+ super.beforeAll()
+ datasetUnivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 1, Array(5.5), Array(0.8), 1000, 42, 1.0, 2.0, 2.0)))
+ datasetMultivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 2, Array(0.9, -1.3), Array(0.7, 1.2), 1000, 42, 1.5, 2.5, 2.0)))
+ }
+
+ test("params") {
+ ParamsSuite.checkParams(new AFTSurvivalRegression)
+ val model = new AFTSurvivalRegressionModel("aftSurvReg", Vectors.dense(0.0), 0.0, 0.0)
+ ParamsSuite.checkParams(model)
+ }
+
+ test("aft survival regression: default params") {
+ val aftr = new AFTSurvivalRegression
+ assert(aftr.getLabelCol === "label")
+ assert(aftr.getFeaturesCol === "features")
+ assert(aftr.getPredictionCol === "prediction")
+ assert(aftr.getCensorCol === "censored")
+ assert(aftr.getFitIntercept)
+ assert(aftr.getMaxIter === 100)
+ assert(aftr.getTol === 1E-6)
+ val model = aftr.fit(datasetUnivariate)
+
+ // copied model must have the same parent.
+ MLTestingUtils.checkCopy(model)
+
+ model.transform(datasetUnivariate)
+ .select("label", "prediction")
+ .collect()
+ assert(model.getFeaturesCol === "features")
+ assert(model.getPredictionCol === "prediction")
+ assert(model.intercept !== 0.0)
+ assert(model.hasParent)
+ }
+
+ def generateAFTInput(
+ numFeatures: Int,
+ xMean: Array[Double],
+ xVariance: Array[Double],
+ nPoints: Int,
+ seed: Int,
+ weibullShape: Double,
+ weibullScale: Double,
+ exponentialMean: Double): Seq[AFTPoint] = {
+
+ def censored(x: Double, y: Double): Double = { if (x <= y) 1.0 else 0.0 }
+
+ val weibull = new WeibullGenerator(weibullShape, weibullScale)
+ weibull.setSeed(seed)
+
+ val exponential = new ExponentialGenerator(exponentialMean)
+ exponential.setSeed(seed)
+
+ val rnd = new Random(seed)
+ val x = Array.fill[Array[Double]](nPoints)(Array.fill[Double](numFeatures)(rnd.nextDouble()))
+
+ x.foreach { v =>
+ var i = 0
+ val len = v.length
+ while (i < len) {
+ v(i) = (v(i) - 0.5) * math.sqrt(12.0 * xVariance(i)) + xMean(i)
+ i += 1
+ }
+ }
+ val y = (1 to nPoints).map { i => (weibull.nextValue(), exponential.nextValue()) }
+
+ y.zip(x).map { p => AFTPoint(Vectors.dense(p._2), censored(p._1._1, p._1._2), p._1._1) }
+ }
+
+ test("aft survival regression with univariate") {
+ val trainer = new AFTSurvivalRegression
+ val model = trainer.fit(datasetUnivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
+ > data <- read.csv("path", header=FALSE, stringsAsFactors=FALSE)
+ > features <- as.matrix(data.frame(as.numeric(data$V1)))
+ > censored <- as.numeric(data$V2)
+ > label <- as.numeric(data$V3)
+ > sr.fit <- survreg(Surv(label, censored)~features, dist='weibull')
+ > summary(sr.fit)
+
+ survreg(formula = Surv(label, censored) ~ features, dist = "weibull")
+ Value Std. Error z p
+ (Intercept) 1.759 0.4141 4.247 2.16e-05
+ features -0.039 0.0735 -0.531 5.96e-01
+ Log(scale) 0.344 0.0379 9.073 1.16e-19
+
+ Scale= 1.41
+
+ Weibull distribution
+ Loglik(model)= -1152.2 Loglik(intercept only)= -1152.3
+ Chisq= 0.28 on 1 degrees of freedom, p= 0.6
+ Number of Newton-Raphson Iterations: 5
+ n= 1000
+ */
+ val weightsR = Vectors.dense(-0.039)
+ val interceptR = 1.759
+ val scaleR = 1.41
+
+ assert(model.intercept ~== interceptR relTol 1E-3)
+ assert(model.weights ~= weightsR relTol 1E-3)
--- End diff --
It's typo.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138509440
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811544
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
+ dataset.select($(featuresCol), $(labelCol), $(censoredCol)).map {
+ case Row(features: Vector, label: Double, censored: Double) =>
+ AFTPoint(features, label, censored)
+ }
+ }
+
+ @Since("1.6.0")
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractAFTPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, regression coefficients vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
--- End diff --
remove `val rawWeights = `
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811339
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
+ dataset.select($(featuresCol), $(labelCol), $(censoredCol)).map {
+ case Row(features: Vector, label: Double, censored: Double) =>
+ AFTPoint(features, label, censored)
+ }
+ }
+
+ @Since("1.6.0")
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractAFTPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, regression coefficients vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val coefficients = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegressionModel private[ml] (
+ @Since("1.6.0") override val uid: String,
+ @Since("1.6.0") val coefficients: Vector,
+ @Since("1.6.0") val intercept: Double,
+ @Since("1.6.0") val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setQuantileProbabilities(value: Array[Double]): this.type = set(quantileProbabilities, value)
+
+ @Since("1.6.0")
+ def predictQuantiles(features: Vector): Vector = {
+ require(hasQuantileProbabilities,
+ "AFTSurvivalRegressionModel predictQuantiles must set quantile probabilities array")
+ // scale parameter for the Weibull distribution of lifetime
+ val lambda = math.exp(BLAS.dot(coefficients, features) + intercept)
+ // shape parameter for the Weibull distribution of lifetime
+ val k = 1 / scale
+ val quantiles = $(quantileProbabilities).map {
+ q => lambda * math.exp(math.log(-math.log(1-q)) / k)
+ }
+ Vectors.dense(quantiles)
+ }
+
+ @Since("1.6.0")
+ def predict(features: Vector): Double = {
+ math.exp(BLAS.dot(coefficients, features) + intercept)
+ }
+
+ @Since("1.6.0")
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * Given the values of the covariates x^{'}, for random lifetime t_{i} of subjects i = 1, ..., n,
+ * with possible right-censoring, the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Where \delta_{i} is the indicator of the event has occurred i.e. uncensored or not.
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function,
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ *
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution of lifetime is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The log of scale parameter, the intercept and
+ * regression coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ // beta is the intercept and regression coefficients to the covariates
+ private val beta = weights.slice(1, weights.length)
+ // sigma is the scale parameter of the AFT model
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
+ gradientBetaSum/totalCnt.toDouble)
+
+ /**
+ * Add a new training data to this AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ *
+ * @param data The AFTPoint representation for one data point to be added into this aggregator.
+ * @return This AFTAggregator object.
+ */
+ def add(data: AFTPoint): this.type = {
+
+ val xi = if (fitIntercept) {
+ Vectors.dense(Array(1.0) ++ data.features.toArray).toBreeze
--- End diff --
Leave a TODO here because this is expensive. We don't need to create a new `xi` every time.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39090813
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTRegressionSuite.scala ---
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.feature.OneHotEncoder
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.functions._
+
+import scala.util.Random
+
+case class AFTExamplePoint(stage: Double, time: Double, age: Int, year: Int, censored: Double)
+
+case class AFTPoint(features: Vector, censored: Double, label: Double)
+
+class AFTRegressionSuite extends SparkFunSuite with MLlibTestSparkContext {
+
+ @transient var datasetUnivariate: DataFrame = _
+ @transient var datasetMultivariate: DataFrame = _
+
+ override def beforeAll(): Unit = {
+ super.beforeAll()
+ datasetUnivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 1, Array(5.5), Array(0.8), 1000, 42, 1.0, 2.0)))
+ datasetMultivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 2, Array(0.9, -1.3), Array(0.7, 1.2), 1000, 42, 1.5, 2.5)))
+ }
+
+ test("params") {
+ ParamsSuite.checkParams(new AFTRegression)
+ val model = new AFTRegressionModel("aftReg", Vectors.dense(0.0), 0.0, 0.0)
+ ParamsSuite.checkParams(model)
+ }
+
+ test("aft regression: default params") {
+ val aftr = new AFTRegression
+ assert(aftr.getLabelCol === "label")
+ assert(aftr.getFeaturesCol === "features")
+ assert(aftr.getPredictionCol === "prediction")
+ assert(aftr.getFitIntercept)
+ val model = aftr.fit(datasetUnivariate)
+
+ // copied model must have the same parent.
+ MLTestingUtils.checkCopy(model)
+
+ assert(model.getFeaturesCol === "features")
+ assert(model.getPredictionCol === "prediction")
+ assert(model.getQuantileCol == "quantile")
+ assert(model.intercept !== 0.0)
+ assert(model.hasParent)
+ }
+
+ def generateAFTInput(
+ numFeatures: Int,
+ xMean: Array[Double],
+ xVariance: Array[Double],
+ nPoints: Int,
+ seed: Int,
+ alpha: Double,
+ beta: Double): Seq[AFTPoint] = {
+
+ def censored(x: Double, y: Double): Double = {
+ if (x <= y) 1.0 else 0.0
+ }
+
+ val weibull = new WeibullGenerator(alpha, beta)
+ weibull.setSeed(seed)
+
+ val exponential = new ExponentialGenerator(2.0)
+ exponential.setSeed(seed)
+
+ val rnd = new Random(seed)
+ val x = Array.fill[Array[Double]](nPoints)(
+ Array.fill[Double](numFeatures)(rnd.nextDouble()))
+
+ x.foreach { v =>
+ var i = 0
+ val len = v.length
+ while (i < len) {
+ v(i) = (v(i) - 0.5) * math.sqrt(12.0 * xVariance(i)) + xMean(i)
+ i += 1
+ }
+ }
+ val y = (1 to nPoints).map { i =>
+ (weibull.nextValue(), exponential.nextValue())
+ }
+
+ y.zip(x).map { p =>
+ AFTPoint(Vectors.dense(p._2), censored(p._1._1, p._1._2), p._1._1)
+ }
+ }
+
+ test("aft regression with univariate") {
+ val trainer = new AFTRegression
+ val model = trainer.fit(datasetUnivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
+ > data <- read.csv("path", header=FALSE, stringsAsFactors=FALSE)
+ > features <- as.matrix(data.frame(as.numeric(data$V1)))
+ > censored <- as.numeric(data$V2)
+ > label <- as.numeric(data$V3)
+ > sr.fit <- survreg(Surv(label, censored)~features, dist='weibull')
+ > summary(sr.fit)
+
+ survreg(formula = Surv(label, censored) ~ features, dist = "weibull")
+ Value Std. Error z p
+ (Intercept) 1.759 0.4141 4.247 2.16e-05
+ features -0.039 0.0735 -0.531 5.96e-01
+ Log(scale) 0.344 0.0379 9.073 1.16e-19
+
+ Scale= 1.41
+
+ Weibull distribution
+ Loglik(model)= -1152.2 Loglik(intercept only)= -1152.3
+ Chisq= 0.28 on 1 degrees of freedom, p= 0.6
+ Number of Newton-Raphson Iterations: 5
+ n= 1000
+ */
+ val weightsR = Vectors.dense(-0.039)
+ val interceptR = 1.759
+ val scaleR = 1.41
+
+ assert(model.intercept ~== interceptR relTol 1E-3)
+ assert(model.weights ~= weightsR relTol 1E-3)
+ assert(model.scale ~= scaleR relTol 1E-3)
+
+ val features = Vectors.dense(4.675290165370009)
+ val quantile = Vectors.dense(Array(0.1, 0.5, 0.9))
+ val expected = model.predict(features, quantile)
--- End diff --
put an `assert` statement for `expected`?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811346
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
+ dataset.select($(featuresCol), $(labelCol), $(censoredCol)).map {
+ case Row(features: Vector, label: Double, censored: Double) =>
+ AFTPoint(features, label, censored)
+ }
+ }
+
+ @Since("1.6.0")
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractAFTPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, regression coefficients vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val coefficients = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegressionModel private[ml] (
+ @Since("1.6.0") override val uid: String,
+ @Since("1.6.0") val coefficients: Vector,
+ @Since("1.6.0") val intercept: Double,
+ @Since("1.6.0") val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setQuantileProbabilities(value: Array[Double]): this.type = set(quantileProbabilities, value)
+
+ @Since("1.6.0")
+ def predictQuantiles(features: Vector): Vector = {
+ require(hasQuantileProbabilities,
+ "AFTSurvivalRegressionModel predictQuantiles must set quantile probabilities array")
+ // scale parameter for the Weibull distribution of lifetime
+ val lambda = math.exp(BLAS.dot(coefficients, features) + intercept)
+ // shape parameter for the Weibull distribution of lifetime
+ val k = 1 / scale
+ val quantiles = $(quantileProbabilities).map {
+ q => lambda * math.exp(math.log(-math.log(1-q)) / k)
+ }
+ Vectors.dense(quantiles)
+ }
+
+ @Since("1.6.0")
+ def predict(features: Vector): Double = {
+ math.exp(BLAS.dot(coefficients, features) + intercept)
+ }
+
+ @Since("1.6.0")
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * Given the values of the covariates x^{'}, for random lifetime t_{i} of subjects i = 1, ..., n,
+ * with possible right-censoring, the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Where \delta_{i} is the indicator of the event has occurred i.e. uncensored or not.
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function,
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ *
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution of lifetime is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The log of scale parameter, the intercept and
+ * regression coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ // beta is the intercept and regression coefficients to the covariates
+ private val beta = weights.slice(1, weights.length)
+ // sigma is the scale parameter of the AFT model
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
+ gradientBetaSum/totalCnt.toDouble)
+
+ /**
+ * Add a new training data to this AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ *
+ * @param data The AFTPoint representation for one data point to be added into this aggregator.
+ * @return This AFTAggregator object.
+ */
+ def add(data: AFTPoint): this.type = {
+
+ val xi = if (fitIntercept) {
+ Vectors.dense(Array(1.0) ++ data.features.toArray).toBreeze
+ } else {
+ Vectors.dense(Array(0.0) ++ data.features.toArray).toBreeze
+ }
+ val ti = data.label
+ val delta = data.censored
+ val epsilon = (math.log(ti) - beta.dot(xi)) / sigma
+
+ lossSum += math.log(sigma) * delta
+ lossSum += (math.exp(epsilon) - delta * epsilon)
+
+ // Sanity check (should never occur):
+ assert(!lossSum.isInfinity,
+ s"AFTAggregator loss sum is infinity. Error for unknown reason.")
+
+ gradientBetaSum += xi * (delta - math.exp(epsilon)) / sigma
+ gradientLogSigmaSum += delta + (delta - math.exp(epsilon)) * epsilon
+
+ totalCnt += 1
+ this
+ }
+
+ /**
+ * Merge another AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ * (Note that it's in place merging; as a result, `this` object will be modified.)
+ *
+ * @param other The other AFTAggregator to be merged.
+ * @return This AFTAggregator object.
+ */
+ def merge(other: AFTAggregator): this.type = {
+ if (totalCnt != 0) {
+ totalCnt += other.totalCnt
+ lossSum += other.lossSum
+
+ gradientBetaSum += other.gradientBetaSum
+ gradientLogSigmaSum += other.gradientLogSigmaSum
+ }
+ this
+ }
+}
+
+/**
+ * AFTCostFun implements Breeze's DiffFunction[T] for AFT cost.
+ * It returns the loss and gradient at a particular point (coefficients).
+ * It's used in Breeze's convex optimization routines.
+ */
+private class AFTCostFun(data: RDD[AFTPoint], fitIntercept: Boolean)
+ extends DiffFunction[BDV[Double]] {
+
+ override def calculate(coefficients: BDV[Double]): (Double, BDV[Double]) = {
+
+ val aftAggregator = data.treeAggregate(new AFTAggregator(coefficients, fitIntercept))(
+ seqOp = (c, v) => (c, v) match {
+ case (aggregator, instance) => aggregator.add(instance)
+ },
+ combOp = (c1, c2) => (c1, c2) match {
+ case (aggregator1, aggregator2) => aggregator1.merge(aggregator2)
+ })
+
+ (aftAggregator.loss, aftAggregator.gradient)
+ }
+}
+
+/**
+ * Class that represents the (features, label, censored) of a data point.
+ *
+ * @param features List of features for this data point.
+ * @param label Label for this data point.
+ * @param censored Indicator of the event has occurred or not. If the value is 1, it means
+ * the event has occurred i.e. uncensored; otherwise it censored.
+ */
+private[ml] case class AFTPoint(features: Vector, label: Double, censored: Double)
--- End diff --
`[ml]` -> `[regression]`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39105683
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTRegressionSuite.scala ---
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.feature.OneHotEncoder
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.functions._
+
+import scala.util.Random
+
+case class AFTExamplePoint(stage: Double, time: Double, age: Int, year: Int, censored: Double)
+
+case class AFTPoint(features: Vector, censored: Double, label: Double)
--- End diff --
make this private?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141102645
@mengxr @rotationsymmetry Thanks for your comments. I have updated the PR, Would you mind to make another pass?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138941709
@rotationsymmetry Do you have time to make a pass?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532387
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ lambda
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, weights, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * For random lifetime T_{i} of subjects i = 1, ..., n, with possible right-censoring,
+ * the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The the log of scale parameter,
+ * the intercept and weights/coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ private val beta = weights.slice(1, weights.length)
--- End diff --
It might be useful to doc that `beta` is from Weibull.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532376
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
--- End diff --
* We can have a private case class to represent an instance. It makes the code simpler to read.
* fix indentation
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138521698
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811937
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
+ dataset.select($(featuresCol), $(labelCol), $(censoredCol)).map {
+ case Row(features: Vector, label: Double, censored: Double) =>
+ AFTPoint(features, label, censored)
+ }
+ }
+
+ @Since("1.6.0")
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractAFTPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, regression coefficients vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val coefficients = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegressionModel private[ml] (
+ @Since("1.6.0") override val uid: String,
+ @Since("1.6.0") val coefficients: Vector,
+ @Since("1.6.0") val intercept: Double,
+ @Since("1.6.0") val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setQuantileProbabilities(value: Array[Double]): this.type = set(quantileProbabilities, value)
+
+ @Since("1.6.0")
+ def predictQuantiles(features: Vector): Vector = {
+ require(hasQuantileProbabilities,
+ "AFTSurvivalRegressionModel predictQuantiles must set quantile probabilities array")
+ // scale parameter for the Weibull distribution of lifetime
+ val lambda = math.exp(BLAS.dot(coefficients, features) + intercept)
+ // shape parameter for the Weibull distribution of lifetime
+ val k = 1 / scale
+ val quantiles = $(quantileProbabilities).map {
+ q => lambda * math.exp(math.log(-math.log(1-q)) / k)
+ }
+ Vectors.dense(quantiles)
+ }
+
+ @Since("1.6.0")
+ def predict(features: Vector): Double = {
+ math.exp(BLAS.dot(coefficients, features) + intercept)
+ }
+
+ @Since("1.6.0")
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * Given the values of the covariates x^{'}, for random lifetime t_{i} of subjects i = 1, ..., n,
+ * with possible right-censoring, the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Where \delta_{i} is the indicator of the event has occurred i.e. uncensored or not.
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function,
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ *
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution of lifetime is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The log of scale parameter, the intercept and
+ * regression coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ // beta is the intercept and regression coefficients to the covariates
+ private val beta = weights.slice(1, weights.length)
+ // sigma is the scale parameter of the AFT model
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
+ gradientBetaSum/totalCnt.toDouble)
+
+ /**
+ * Add a new training data to this AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ *
+ * @param data The AFTPoint representation for one data point to be added into this aggregator.
+ * @return This AFTAggregator object.
+ */
+ def add(data: AFTPoint): this.type = {
+
+ val xi = if (fitIntercept) {
+ Vectors.dense(Array(1.0) ++ data.features.toArray).toBreeze
+ } else {
+ Vectors.dense(Array(0.0) ++ data.features.toArray).toBreeze
+ }
+ val ti = data.label
+ val delta = data.censored
+ val epsilon = (math.log(ti) - beta.dot(xi)) / sigma
+
+ lossSum += math.log(sigma) * delta
+ lossSum += (math.exp(epsilon) - delta * epsilon)
+
+ // Sanity check (should never occur):
+ assert(!lossSum.isInfinity,
+ s"AFTAggregator loss sum is infinity. Error for unknown reason.")
+
+ gradientBetaSum += xi * (delta - math.exp(epsilon)) / sigma
+ gradientLogSigmaSum += delta + (delta - math.exp(epsilon)) * epsilon
+
+ totalCnt += 1
+ this
+ }
+
+ /**
+ * Merge another AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ * (Note that it's in place merging; as a result, `this` object will be modified.)
+ *
+ * @param other The other AFTAggregator to be merged.
+ * @return This AFTAggregator object.
+ */
+ def merge(other: AFTAggregator): this.type = {
+ if (totalCnt != 0) {
+ totalCnt += other.totalCnt
+ lossSum += other.lossSum
+
+ gradientBetaSum += other.gradientBetaSum
+ gradientLogSigmaSum += other.gradientLogSigmaSum
+ }
+ this
+ }
+}
+
+/**
+ * AFTCostFun implements Breeze's DiffFunction[T] for AFT cost.
+ * It returns the loss and gradient at a particular point (coefficients).
+ * It's used in Breeze's convex optimization routines.
+ */
+private class AFTCostFun(data: RDD[AFTPoint], fitIntercept: Boolean)
+ extends DiffFunction[BDV[Double]] {
+
+ override def calculate(coefficients: BDV[Double]): (Double, BDV[Double]) = {
+
+ val aftAggregator = data.treeAggregate(new AFTAggregator(coefficients, fitIntercept))(
+ seqOp = (c, v) => (c, v) match {
+ case (aggregator, instance) => aggregator.add(instance)
+ },
+ combOp = (c1, c2) => (c1, c2) match {
+ case (aggregator1, aggregator2) => aggregator1.merge(aggregator2)
+ })
+
+ (aftAggregator.loss, aftAggregator.gradient)
+ }
+}
+
+/**
+ * Class that represents the (features, label, censored) of a data point.
+ *
+ * @param features List of features for this data point.
+ * @param label Label for this data point.
+ * @param censored Indicator of the event has occurred or not. If the value is 1, it means
+ * the event has occurred i.e. uncensored; otherwise it censored.
+ */
+private[ml] case class AFTPoint(features: Vector, label: Double, censored: Double)
--- End diff --
Also validate `censored` is in `{0, 1}`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138861693
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140350768
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532398
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ lambda
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, weights, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * For random lifetime T_{i} of subjects i = 1, ..., n, with possible right-censoring,
+ * the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The the log of scale parameter,
+ * the intercept and weights/coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ private val beta = weights.slice(1, weights.length)
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
--- End diff --
leave an empty line between methods
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141110526
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141341794
LGTM. Merged into master. Thanks! I created https://issues.apache.org/jira/browse/SPARK-10686 for follow-up work.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140350782
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811229
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
--- End diff --
This is confusing. The column name is called `censored` but value `1` means `uncensored`. I searched for some survival analysis datasets, where "censor" is commonly used as the column name. See https://www.umass.edu/statdata/statdata/stat-survival.html. However, in those datasets, `1` actually means occurred, i.e., uncensored. So my recommendation would be renaming the param name back to `censorCol` and keep the current doc. That is `1` for uncensored and `0` for censored. And note that this is to be consistent with existing datasets.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138278271
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39537494
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
--- End diff --
`quantilePredict` -> `predictQuantiles` (e.g., we have `predictProbabilities`)
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811330
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
+ dataset.select($(featuresCol), $(labelCol), $(censoredCol)).map {
+ case Row(features: Vector, label: Double, censored: Double) =>
+ AFTPoint(features, label, censored)
+ }
+ }
+
+ @Since("1.6.0")
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractAFTPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, regression coefficients vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val coefficients = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegressionModel private[ml] (
+ @Since("1.6.0") override val uid: String,
+ @Since("1.6.0") val coefficients: Vector,
+ @Since("1.6.0") val intercept: Double,
+ @Since("1.6.0") val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setQuantileProbabilities(value: Array[Double]): this.type = set(quantileProbabilities, value)
+
+ @Since("1.6.0")
+ def predictQuantiles(features: Vector): Vector = {
+ require(hasQuantileProbabilities,
+ "AFTSurvivalRegressionModel predictQuantiles must set quantile probabilities array")
+ // scale parameter for the Weibull distribution of lifetime
+ val lambda = math.exp(BLAS.dot(coefficients, features) + intercept)
+ // shape parameter for the Weibull distribution of lifetime
+ val k = 1 / scale
+ val quantiles = $(quantileProbabilities).map {
+ q => lambda * math.exp(math.log(-math.log(1-q)) / k)
--- End diff --
`1-q` -> `1 - q`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39538575
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTSurvivalRegressionSuite.scala ---
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.util.Random
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.{Row, DataFrame}
+
+private[ml] case class AFTPoint(features: Vector, censored: Double, label: Double)
+
+class AFTSurvivalRegressionSuite extends SparkFunSuite with MLlibTestSparkContext {
+
+ @transient var datasetUnivariate: DataFrame = _
+ @transient var datasetMultivariate: DataFrame = _
+
+ override def beforeAll(): Unit = {
+ super.beforeAll()
+ datasetUnivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 1, Array(5.5), Array(0.8), 1000, 42, 1.0, 2.0, 2.0)))
+ datasetMultivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 2, Array(0.9, -1.3), Array(0.7, 1.2), 1000, 42, 1.5, 2.5, 2.0)))
+ }
+
+ test("params") {
+ ParamsSuite.checkParams(new AFTSurvivalRegression)
+ val model = new AFTSurvivalRegressionModel("aftSurvReg", Vectors.dense(0.0), 0.0, 0.0)
+ ParamsSuite.checkParams(model)
+ }
+
+ test("aft survival regression: default params") {
+ val aftr = new AFTSurvivalRegression
+ assert(aftr.getLabelCol === "label")
+ assert(aftr.getFeaturesCol === "features")
+ assert(aftr.getPredictionCol === "prediction")
+ assert(aftr.getCensorCol === "censored")
+ assert(aftr.getFitIntercept)
+ assert(aftr.getMaxIter === 100)
+ assert(aftr.getTol === 1E-6)
+ val model = aftr.fit(datasetUnivariate)
+
+ // copied model must have the same parent.
+ MLTestingUtils.checkCopy(model)
+
+ model.transform(datasetUnivariate)
+ .select("label", "prediction")
+ .collect()
+ assert(model.getFeaturesCol === "features")
+ assert(model.getPredictionCol === "prediction")
+ assert(model.intercept !== 0.0)
+ assert(model.hasParent)
+ }
+
+ def generateAFTInput(
+ numFeatures: Int,
+ xMean: Array[Double],
+ xVariance: Array[Double],
+ nPoints: Int,
+ seed: Int,
+ weibullShape: Double,
+ weibullScale: Double,
+ exponentialMean: Double): Seq[AFTPoint] = {
+
+ def censored(x: Double, y: Double): Double = { if (x <= y) 1.0 else 0.0 }
+
+ val weibull = new WeibullGenerator(weibullShape, weibullScale)
+ weibull.setSeed(seed)
+
+ val exponential = new ExponentialGenerator(exponentialMean)
+ exponential.setSeed(seed)
+
+ val rnd = new Random(seed)
+ val x = Array.fill[Array[Double]](nPoints)(Array.fill[Double](numFeatures)(rnd.nextDouble()))
+
+ x.foreach { v =>
+ var i = 0
+ val len = v.length
+ while (i < len) {
+ v(i) = (v(i) - 0.5) * math.sqrt(12.0 * xVariance(i)) + xMean(i)
+ i += 1
+ }
+ }
+ val y = (1 to nPoints).map { i => (weibull.nextValue(), exponential.nextValue()) }
+
+ y.zip(x).map { p => AFTPoint(Vectors.dense(p._2), censored(p._1._1, p._1._2), p._1._1) }
+ }
+
+ test("aft survival regression with univariate") {
+ val trainer = new AFTSurvivalRegression
+ val model = trainer.fit(datasetUnivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
+ > data <- read.csv("path", header=FALSE, stringsAsFactors=FALSE)
+ > features <- as.matrix(data.frame(as.numeric(data$V1)))
+ > censored <- as.numeric(data$V2)
+ > label <- as.numeric(data$V3)
+ > sr.fit <- survreg(Surv(label, censored)~features, dist='weibull')
+ > summary(sr.fit)
+
+ survreg(formula = Surv(label, censored) ~ features, dist = "weibull")
+ Value Std. Error z p
+ (Intercept) 1.759 0.4141 4.247 2.16e-05
+ features -0.039 0.0735 -0.531 5.96e-01
+ Log(scale) 0.344 0.0379 9.073 1.16e-19
+
+ Scale= 1.41
+
+ Weibull distribution
+ Loglik(model)= -1152.2 Loglik(intercept only)= -1152.3
+ Chisq= 0.28 on 1 degrees of freedom, p= 0.6
+ Number of Newton-Raphson Iterations: 5
+ n= 1000
+ */
+ val weightsR = Vectors.dense(-0.039)
+ val interceptR = 1.759
+ val scaleR = 1.41
+
+ assert(model.intercept ~== interceptR relTol 1E-3)
+ assert(model.weights ~= weightsR relTol 1E-3)
+ assert(model.scale ~= scaleR relTol 1E-3)
+
+ /*
+ Using the following R code to predict.
+ > responsePred <- predict(sr.fit)
+ > quantilePred <- predict(sr.fit, type='quantile', p=c(0.1, 0.5, 0.9))
--- End diff --
also include R output
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39681846
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
--- End diff --
This setter is to set the probabilities that the quantiles should be at. So I suggest we rename this to `setQuantileProbabilities`. This will avoid the confusion of having both `setQuantile` and `predictQuantiles` even though the items to be set and predict are different.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140472590
I made a brief scan over the code. @rotationsymmetry Could you make another pass?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141110530
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42603/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140359907
[Test build #42484 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42484/console) for PR 8611 at commit [`999a753`](https://github.com/apache/spark/commit/999a753d0567fe3743ebdb9d9d18609295cdd10c).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTSurvivalRegression(override val uid: String)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138509491
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-137925197
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811447
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
--- End diff --
No, it should work. But since this is just a list of values, a Double array should be sufficient.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-137929010
[Test build #42039 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42039/console) for PR 8611 at commit [`7f2a31d`](https://github.com/apache/spark/commit/7f2a31db621cbbef9c2221e4466e1d79b2cbac42).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTRegression(override val uid: String)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140351723
[Test build #42484 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42484/consoleFull) for PR 8611 at commit [`999a753`](https://github.com/apache/spark/commit/999a753d0567fe3743ebdb9d9d18609295cdd10c).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-137925191
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138270500
[Test build #42091 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42091/consoleFull) for PR 8611 at commit [`c30a1c2`](https://github.com/apache/spark/commit/c30a1c2c6e256380032441c3e52adaeb5f9be1da).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532368
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
--- End diff --
minor: `aftSurvReg`?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39662334
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ lambda
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, weights, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * For random lifetime T_{i} of subjects i = 1, ..., n, with possible right-censoring,
+ * the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
--- End diff --
1) delta in the formula is the *event* indicator. Since we decide to use the *censored* indicator, I recommend we clarify this in the formula.
2) please add a sentence to clarify t_{i} = log(T_{i}).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532351
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
--- End diff --
Document expected values in this column.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-137925642
[Test build #42039 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42039/consoleFull) for PR 8611 at commit [`7f2a31d`](https://github.com/apache/spark/commit/7f2a31db621cbbef9c2221e4466e1d79b2cbac42).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138510966
[Test build #42128 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42128/consoleFull) for PR 8611 at commit [`28ca4c0`](https://github.com/apache/spark/commit/28ca4c02f3765b345bb39f457635fbecb6971f49).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138069507
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39090742
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTRegressionSuite.scala ---
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.feature.OneHotEncoder
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.functions._
+
+import scala.util.Random
+
+case class AFTExamplePoint(stage: Double, time: Double, age: Int, year: Int, censored: Double)
+
+case class AFTPoint(features: Vector, censored: Double, label: Double)
+
+class AFTRegressionSuite extends SparkFunSuite with MLlibTestSparkContext {
+
+ @transient var datasetUnivariate: DataFrame = _
+ @transient var datasetMultivariate: DataFrame = _
+
+ override def beforeAll(): Unit = {
+ super.beforeAll()
+ datasetUnivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 1, Array(5.5), Array(0.8), 1000, 42, 1.0, 2.0)))
+ datasetMultivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 2, Array(0.9, -1.3), Array(0.7, 1.2), 1000, 42, 1.5, 2.5)))
+ }
+
+ test("params") {
+ ParamsSuite.checkParams(new AFTRegression)
+ val model = new AFTRegressionModel("aftReg", Vectors.dense(0.0), 0.0, 0.0)
+ ParamsSuite.checkParams(model)
+ }
+
+ test("aft regression: default params") {
+ val aftr = new AFTRegression
+ assert(aftr.getLabelCol === "label")
+ assert(aftr.getFeaturesCol === "features")
+ assert(aftr.getPredictionCol === "prediction")
+ assert(aftr.getFitIntercept)
+ val model = aftr.fit(datasetUnivariate)
+
+ // copied model must have the same parent.
+ MLTestingUtils.checkCopy(model)
+
+ assert(model.getFeaturesCol === "features")
+ assert(model.getPredictionCol === "prediction")
+ assert(model.getQuantileCol == "quantile")
+ assert(model.intercept !== 0.0)
+ assert(model.hasParent)
+ }
+
+ def generateAFTInput(
+ numFeatures: Int,
+ xMean: Array[Double],
+ xVariance: Array[Double],
+ nPoints: Int,
+ seed: Int,
+ alpha: Double,
+ beta: Double): Seq[AFTPoint] = {
+
+ def censored(x: Double, y: Double): Double = {
+ if (x <= y) 1.0 else 0.0
+ }
+
+ val weibull = new WeibullGenerator(alpha, beta)
+ weibull.setSeed(seed)
+
+ val exponential = new ExponentialGenerator(2.0)
+ exponential.setSeed(seed)
+
+ val rnd = new Random(seed)
+ val x = Array.fill[Array[Double]](nPoints)(
+ Array.fill[Double](numFeatures)(rnd.nextDouble()))
+
+ x.foreach { v =>
+ var i = 0
+ val len = v.length
+ while (i < len) {
+ v(i) = (v(i) - 0.5) * math.sqrt(12.0 * xVariance(i)) + xMean(i)
+ i += 1
+ }
+ }
+ val y = (1 to nPoints).map { i =>
+ (weibull.nextValue(), exponential.nextValue())
+ }
+
+ y.zip(x).map { p =>
+ AFTPoint(Vectors.dense(p._2), censored(p._1._1, p._1._2), p._1._1)
+ }
+ }
+
+ test("aft regression with univariate") {
+ val trainer = new AFTRegression
+ val model = trainer.fit(datasetUnivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
+ > data <- read.csv("path", header=FALSE, stringsAsFactors=FALSE)
+ > features <- as.matrix(data.frame(as.numeric(data$V1)))
+ > censored <- as.numeric(data$V2)
+ > label <- as.numeric(data$V3)
+ > sr.fit <- survreg(Surv(label, censored)~features, dist='weibull')
+ > summary(sr.fit)
+
+ survreg(formula = Surv(label, censored) ~ features, dist = "weibull")
+ Value Std. Error z p
+ (Intercept) 1.759 0.4141 4.247 2.16e-05
+ features -0.039 0.0735 -0.531 5.96e-01
+ Log(scale) 0.344 0.0379 9.073 1.16e-19
+
+ Scale= 1.41
+
+ Weibull distribution
+ Loglik(model)= -1152.2 Loglik(intercept only)= -1152.3
+ Chisq= 0.28 on 1 degrees of freedom, p= 0.6
+ Number of Newton-Raphson Iterations: 5
+ n= 1000
+ */
+ val weightsR = Vectors.dense(-0.039)
+ val interceptR = 1.759
+ val scaleR = 1.41
+
+ assert(model.intercept ~== interceptR relTol 1E-3)
+ assert(model.weights ~= weightsR relTol 1E-3)
+ assert(model.scale ~= scaleR relTol 1E-3)
+
+ val features = Vectors.dense(4.675290165370009)
+ val quantile = Vectors.dense(Array(0.1, 0.5, 0.9))
+ val expected = model.predict(features, quantile)
+ }
+
+ test("aft regression with multivariate") {
+ val trainer = new AFTRegression
+ val model = trainer.fit(datasetMultivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
+ > data <- read.csv("path", header=FALSE, stringsAsFactors=FALSE)
+ > features <- as.matrix(data.frame(as.numeric(data$V1), as.numeric(data$V2)))
+ > censored <- as.numeric(data$V3)
+ > label <- as.numeric(data$V4)
+ > sr.fit <- survreg(Surv(label, censored)~features, dist='weibull')
+ > summary(sr.fit)
+
+ Value Std. Error z p
+ (Intercept) 1.9206 0.1057 18.171 8.78e-74
+ featuresas.numeric.data.V1. -0.0844 0.0611 -1.381 1.67e-01
+ featuresas.numeric.data.V2. 0.0677 0.0468 1.447 1.48e-01
+ Log(scale) -0.0236 0.0436 -0.542 5.88e-01
+
+ Scale= 0.977
+
+ Weibull distribution
+ Loglik(model)= -1070.7 Loglik(intercept only)= -1072.7
+ Chisq= 3.91 on 2 degrees of freedom, p= 0.14
+ Number of Newton-Raphson Iterations: 5
+ n= 1000
+ */
+ val weightsR = Vectors.dense(-0.0844, 0.0677)
+ val interceptR = 1.9206
+ val scaleR = 0.977
+
+ assert(model.intercept ~== interceptR relTol 1E-3)
+ assert(model.weights ~= weightsR relTol 1E-3)
+ assert(model.scale ~= scaleR relTol 1E-3)
+
+ val features = Vectors.dense(1.109175828579902, -0.5315711415960551)
+ val quantile = Vectors.dense(Array(0.1, 0.5, 0.9))
+ val expected = model.predict(features, quantile)
--- End diff --
put an `assert` statement for `expected`?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39812017
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
+ dataset.select($(featuresCol), $(labelCol), $(censoredCol)).map {
+ case Row(features: Vector, label: Double, censored: Double) =>
+ AFTPoint(features, label, censored)
+ }
+ }
+
+ @Since("1.6.0")
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractAFTPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, regression coefficients vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val coefficients = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegressionModel private[ml] (
+ @Since("1.6.0") override val uid: String,
+ @Since("1.6.0") val coefficients: Vector,
+ @Since("1.6.0") val intercept: Double,
+ @Since("1.6.0") val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setQuantileProbabilities(value: Array[Double]): this.type = set(quantileProbabilities, value)
+
+ @Since("1.6.0")
+ def predictQuantiles(features: Vector): Vector = {
+ require(hasQuantileProbabilities,
+ "AFTSurvivalRegressionModel predictQuantiles must set quantile probabilities array")
+ // scale parameter for the Weibull distribution of lifetime
+ val lambda = math.exp(BLAS.dot(coefficients, features) + intercept)
+ // shape parameter for the Weibull distribution of lifetime
+ val k = 1 / scale
+ val quantiles = $(quantileProbabilities).map {
+ q => lambda * math.exp(math.log(-math.log(1-q)) / k)
+ }
+ Vectors.dense(quantiles)
+ }
+
+ @Since("1.6.0")
+ def predict(features: Vector): Double = {
+ math.exp(BLAS.dot(coefficients, features) + intercept)
+ }
+
+ @Since("1.6.0")
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * Given the values of the covariates x^{'}, for random lifetime t_{i} of subjects i = 1, ..., n,
+ * with possible right-censoring, the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Where \delta_{i} is the indicator of the event has occurred i.e. uncensored or not.
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function,
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ *
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution of lifetime is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The log of scale parameter, the intercept and
+ * regression coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ // beta is the intercept and regression coefficients to the covariates
+ private val beta = weights.slice(1, weights.length)
+ // sigma is the scale parameter of the AFT model
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
+ gradientBetaSum/totalCnt.toDouble)
+
+ /**
+ * Add a new training data to this AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ *
+ * @param data The AFTPoint representation for one data point to be added into this aggregator.
+ * @return This AFTAggregator object.
+ */
+ def add(data: AFTPoint): this.type = {
+
+ val xi = if (fitIntercept) {
+ Vectors.dense(Array(1.0) ++ data.features.toArray).toBreeze
+ } else {
+ Vectors.dense(Array(0.0) ++ data.features.toArray).toBreeze
+ }
+ val ti = data.label
+ val delta = data.censored
+ val epsilon = (math.log(ti) - beta.dot(xi)) / sigma
+
+ lossSum += math.log(sigma) * delta
+ lossSum += (math.exp(epsilon) - delta * epsilon)
+
+ // Sanity check (should never occur):
+ assert(!lossSum.isInfinity,
+ s"AFTAggregator loss sum is infinity. Error for unknown reason.")
+
+ gradientBetaSum += xi * (delta - math.exp(epsilon)) / sigma
+ gradientLogSigmaSum += delta + (delta - math.exp(epsilon)) * epsilon
+
+ totalCnt += 1
+ this
+ }
+
+ /**
+ * Merge another AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ * (Note that it's in place merging; as a result, `this` object will be modified.)
+ *
+ * @param other The other AFTAggregator to be merged.
+ * @return This AFTAggregator object.
+ */
+ def merge(other: AFTAggregator): this.type = {
+ if (totalCnt != 0) {
+ totalCnt += other.totalCnt
+ lossSum += other.lossSum
+
+ gradientBetaSum += other.gradientBetaSum
+ gradientLogSigmaSum += other.gradientLogSigmaSum
+ }
+ this
+ }
+}
+
+/**
+ * AFTCostFun implements Breeze's DiffFunction[T] for AFT cost.
+ * It returns the loss and gradient at a particular point (coefficients).
+ * It's used in Breeze's convex optimization routines.
+ */
+private class AFTCostFun(data: RDD[AFTPoint], fitIntercept: Boolean)
+ extends DiffFunction[BDV[Double]] {
+
+ override def calculate(coefficients: BDV[Double]): (Double, BDV[Double]) = {
+
+ val aftAggregator = data.treeAggregate(new AFTAggregator(coefficients, fitIntercept))(
+ seqOp = (c, v) => (c, v) match {
+ case (aggregator, instance) => aggregator.add(instance)
+ },
+ combOp = (c1, c2) => (c1, c2) match {
+ case (aggregator1, aggregator2) => aggregator1.merge(aggregator2)
+ })
+
+ (aftAggregator.loss, aftAggregator.gradient)
+ }
+}
+
+/**
+ * Class that represents the (features, label, censored) of a data point.
+ *
+ * @param features List of features for this data point.
+ * @param label Label for this data point.
+ * @param censored Indicator of the event has occurred or not. If the value is 1, it means
+ * the event has occurred i.e. uncensored; otherwise it censored.
--- End diff --
remove `it`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39747513
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
--- End diff --
Agree, I renamed to ```censoredCol```
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811301
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
--- End diff --
Should fit into one line.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532394
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ lambda
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, weights, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * For random lifetime T_{i} of subjects i = 1, ..., n, with possible right-censoring,
+ * the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The the log of scale parameter,
+ * the intercept and weights/coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ private val beta = weights.slice(1, weights.length)
+ private val sigma = math.exp(weights(0))
--- End diff --
ditto
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39651055
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
--- End diff --
+1 for `censoredCol`. This matches up with the default value.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-139449375
Had an offline discussion with @yanboliang:
1. rename `AFTRegression` to `AFTSurvivalRegression`
2. make `quantile` a parameter, which applies to all instances
3. `predictionCol` outputs the mean prediction
4. `quantileCol` (default: "") outputs the quantiles
5. some documentation
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532365
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
--- End diff --
`[ml]` -> `[regression]`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532416
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTSurvivalRegressionSuite.scala ---
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.util.Random
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.{Row, DataFrame}
+
+private[ml] case class AFTPoint(features: Vector, censored: Double, label: Double)
+
+class AFTSurvivalRegressionSuite extends SparkFunSuite with MLlibTestSparkContext {
+
+ @transient var datasetUnivariate: DataFrame = _
+ @transient var datasetMultivariate: DataFrame = _
+
+ override def beforeAll(): Unit = {
+ super.beforeAll()
+ datasetUnivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 1, Array(5.5), Array(0.8), 1000, 42, 1.0, 2.0, 2.0)))
+ datasetMultivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 2, Array(0.9, -1.3), Array(0.7, 1.2), 1000, 42, 1.5, 2.5, 2.0)))
+ }
+
+ test("params") {
+ ParamsSuite.checkParams(new AFTSurvivalRegression)
+ val model = new AFTSurvivalRegressionModel("aftSurvReg", Vectors.dense(0.0), 0.0, 0.0)
+ ParamsSuite.checkParams(model)
+ }
+
+ test("aft survival regression: default params") {
+ val aftr = new AFTSurvivalRegression
+ assert(aftr.getLabelCol === "label")
+ assert(aftr.getFeaturesCol === "features")
+ assert(aftr.getPredictionCol === "prediction")
+ assert(aftr.getCensorCol === "censored")
+ assert(aftr.getFitIntercept)
+ assert(aftr.getMaxIter === 100)
+ assert(aftr.getTol === 1E-6)
+ val model = aftr.fit(datasetUnivariate)
+
+ // copied model must have the same parent.
+ MLTestingUtils.checkCopy(model)
+
+ model.transform(datasetUnivariate)
+ .select("label", "prediction")
+ .collect()
+ assert(model.getFeaturesCol === "features")
+ assert(model.getPredictionCol === "prediction")
+ assert(model.intercept !== 0.0)
+ assert(model.hasParent)
+ }
+
+ def generateAFTInput(
+ numFeatures: Int,
+ xMean: Array[Double],
+ xVariance: Array[Double],
+ nPoints: Int,
+ seed: Int,
+ weibullShape: Double,
+ weibullScale: Double,
+ exponentialMean: Double): Seq[AFTPoint] = {
+
+ def censored(x: Double, y: Double): Double = { if (x <= y) 1.0 else 0.0 }
+
+ val weibull = new WeibullGenerator(weibullShape, weibullScale)
+ weibull.setSeed(seed)
+
+ val exponential = new ExponentialGenerator(exponentialMean)
+ exponential.setSeed(seed)
+
+ val rnd = new Random(seed)
+ val x = Array.fill[Array[Double]](nPoints)(Array.fill[Double](numFeatures)(rnd.nextDouble()))
+
+ x.foreach { v =>
+ var i = 0
+ val len = v.length
+ while (i < len) {
+ v(i) = (v(i) - 0.5) * math.sqrt(12.0 * xVariance(i)) + xMean(i)
+ i += 1
+ }
+ }
+ val y = (1 to nPoints).map { i => (weibull.nextValue(), exponential.nextValue()) }
+
+ y.zip(x).map { p => AFTPoint(Vectors.dense(p._2), censored(p._1._1, p._1._2), p._1._1) }
+ }
+
+ test("aft survival regression with univariate") {
+ val trainer = new AFTSurvivalRegression
+ val model = trainer.fit(datasetUnivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
--- End diff --
remove `>` to make copying easier
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39067652
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTRegression.scala ---
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile column name.
+ * @group param
+ */
+ final val quantileCol: Param[String] = new Param[String](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantileCol: String = $(quantileCol)
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ } else {
+ SchemaUtils.checkColumnType(schema, $(quantileCol), new VectorUDT)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+@Experimental
+class AFTRegression(override val uid: String)
+ extends Estimator[AFTRegressionModel] with AFTRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (feature, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(feature: Vector, label: Double, censored: Double) =>
+ (feature, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = new DenseVector(Array.fill(numFeatures + 2)(1.0))
--- End diff --
I think we need to check if `fitIntercept == true`.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811290
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
--- End diff --
This default could go to `AFTParams`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140902838
@yanboliang @mengxr I just made another round. Thanks!
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39749679
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
--- End diff --
Agree, renamed ```quantile``` to ```quantileProbabilities```
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39682109
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
--- End diff --
If we rename the existing `quantile` to `quantileProb`, then `array` can be renamed to `quantile`.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39674163
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTSurvivalRegressionSuite.scala ---
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.util.Random
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.{Row, DataFrame}
+
+private[ml] case class AFTPoint(features: Vector, censored: Double, label: Double)
+
+class AFTSurvivalRegressionSuite extends SparkFunSuite with MLlibTestSparkContext {
+
+ @transient var datasetUnivariate: DataFrame = _
+ @transient var datasetMultivariate: DataFrame = _
+
+ override def beforeAll(): Unit = {
+ super.beforeAll()
+ datasetUnivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 1, Array(5.5), Array(0.8), 1000, 42, 1.0, 2.0, 2.0)))
+ datasetMultivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 2, Array(0.9, -1.3), Array(0.7, 1.2), 1000, 42, 1.5, 2.5, 2.0)))
+ }
+
+ test("params") {
+ ParamsSuite.checkParams(new AFTSurvivalRegression)
+ val model = new AFTSurvivalRegressionModel("aftSurvReg", Vectors.dense(0.0), 0.0, 0.0)
+ ParamsSuite.checkParams(model)
+ }
+
+ test("aft survival regression: default params") {
+ val aftr = new AFTSurvivalRegression
+ assert(aftr.getLabelCol === "label")
+ assert(aftr.getFeaturesCol === "features")
+ assert(aftr.getPredictionCol === "prediction")
+ assert(aftr.getCensorCol === "censored")
+ assert(aftr.getFitIntercept)
+ assert(aftr.getMaxIter === 100)
+ assert(aftr.getTol === 1E-6)
+ val model = aftr.fit(datasetUnivariate)
+
+ // copied model must have the same parent.
+ MLTestingUtils.checkCopy(model)
+
+ model.transform(datasetUnivariate)
+ .select("label", "prediction")
+ .collect()
+ assert(model.getFeaturesCol === "features")
+ assert(model.getPredictionCol === "prediction")
+ assert(model.intercept !== 0.0)
+ assert(model.hasParent)
+ }
+
+ def generateAFTInput(
+ numFeatures: Int,
+ xMean: Array[Double],
+ xVariance: Array[Double],
+ nPoints: Int,
+ seed: Int,
+ weibullShape: Double,
+ weibullScale: Double,
+ exponentialMean: Double): Seq[AFTPoint] = {
+
+ def censored(x: Double, y: Double): Double = { if (x <= y) 1.0 else 0.0 }
+
+ val weibull = new WeibullGenerator(weibullShape, weibullScale)
+ weibull.setSeed(seed)
+
+ val exponential = new ExponentialGenerator(exponentialMean)
+ exponential.setSeed(seed)
+
+ val rnd = new Random(seed)
+ val x = Array.fill[Array[Double]](nPoints)(Array.fill[Double](numFeatures)(rnd.nextDouble()))
+
+ x.foreach { v =>
+ var i = 0
+ val len = v.length
+ while (i < len) {
+ v(i) = (v(i) - 0.5) * math.sqrt(12.0 * xVariance(i)) + xMean(i)
+ i += 1
+ }
+ }
+ val y = (1 to nPoints).map { i => (weibull.nextValue(), exponential.nextValue()) }
+
+ y.zip(x).map { p => AFTPoint(Vectors.dense(p._2), censored(p._1._1, p._1._2), p._1._1) }
+ }
+
+ test("aft survival regression with univariate") {
+ val trainer = new AFTSurvivalRegression
+ val model = trainer.fit(datasetUnivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
+ > data <- read.csv("path", header=FALSE, stringsAsFactors=FALSE)
+ > features <- as.matrix(data.frame(as.numeric(data$V1)))
+ > censored <- as.numeric(data$V2)
+ > label <- as.numeric(data$V3)
+ > sr.fit <- survreg(Surv(label, censored)~features, dist='weibull')
+ > summary(sr.fit)
+
+ survreg(formula = Surv(label, censored) ~ features, dist = "weibull")
+ Value Std. Error z p
+ (Intercept) 1.759 0.4141 4.247 2.16e-05
+ features -0.039 0.0735 -0.531 5.96e-01
+ Log(scale) 0.344 0.0379 9.073 1.16e-19
+
+ Scale= 1.41
+
+ Weibull distribution
+ Loglik(model)= -1152.2 Loglik(intercept only)= -1152.3
+ Chisq= 0.28 on 1 degrees of freedom, p= 0.6
+ Number of Newton-Raphson Iterations: 5
+ n= 1000
+ */
+ val weightsR = Vectors.dense(-0.039)
+ val interceptR = 1.759
+ val scaleR = 1.41
+
+ assert(model.intercept ~== interceptR relTol 1E-3)
+ assert(model.weights ~= weightsR relTol 1E-3)
--- End diff --
just curious why use `~=` instead `~==`?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138271936
[Test build #42092 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42092/consoleFull) for PR 8611 at commit [`4223793`](https://github.com/apache/spark/commit/422379328962a5c0bccbdcd93f52f3f7857a61ba).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138116002
[Test build #42073 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42073/console) for PR 8611 at commit [`d0a29bb`](https://github.com/apache/spark/commit/d0a29bbe709bcc535283e1a0201fc772535c9f90).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTRegression(override val uid: String)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141333538
[Test build #42637 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42637/consoleFull) for PR 8611 at commit [`aa37878`](https://github.com/apache/spark/commit/aa37878c50ef6e7722a615298240ba6e61ea083c).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138108130
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138959708
@mengxr Yes, I have done a quick run and added some comments the past weekend. I will do a more thorough pass today/tomorrow.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811248
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
--- End diff --
`"quantile"` -> `"quantileProbabilities"` (should be detected by `checkParams`)
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138861725
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-137929033
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42039/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138336131
@yanboliang
As sigma is restricted to be positive, in the L-BLGS algorithm, shall we optimize over log(sigma)? This way, there is no more restriction on the possible value of sigma and usual help with convergence.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138278272
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42092/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141094758
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138872504
[Test build #42200 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42200/console) for PR 8611 at commit [`b7dd012`](https://github.com/apache/spark/commit/b7dd0129759e6337aa99a2db6a59abfaec484407).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds no public classes.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138109218
[Test build #42073 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42073/consoleFull) for PR 8611 at commit [`d0a29bb`](https://github.com/apache/spark/commit/d0a29bbe709bcc535283e1a0201fc772535c9f90).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39131812
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTRegression.scala ---
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile column name.
+ * @group param
+ */
+ final val quantileCol: Param[String] = new Param[String](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantileCol: String = $(quantileCol)
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ } else {
+ SchemaUtils.checkColumnType(schema, $(quantileCol), new VectorUDT)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+@Experimental
+class AFTRegression(override val uid: String)
+ extends Estimator[AFTRegressionModel] with AFTRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (feature, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(feature: Vector, label: Double, censored: Double) =>
+ (feature, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = new DenseVector(Array.fill(numFeatures + 2)(1.0))
--- End diff --
here intercept (2nd element) is initialized to 1 regardless of `fitIntercept`. If `fitIntercept` is false, the 2nd element will stay as 1 after the LBFGS optimization. This value will be carry to the `AFTRegressionModel`. Then `predict` and `transform` will be incorrect.
How about we include intercept in `initialWeights` *only* when `fitIntercept` is `true`?
Btw, shall we set the initial values to be zero since we are working in the log scale.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-137929032
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39749007
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
--- End diff --
Change to use ```DoubleArrayParam```.
But I found using ```Param[Vector]``` works well in Python such as [```ElementwiseProduct .scalingVec```](https://github.com/apache/spark/blob/master/python/pyspark/ml/feature.py#L250). Is there something I have missed?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-139137186
@yanboliang Thanks for the PR. I have done one pass. Please see my line comments. On top of that, shall we consider the following:
* Parameterization
Different parameterizations of the Weibull distribution are used throughout the code.
* epsilon, sigma in `AFTAggregator`
* lambda, k in `predict` of ` AFTRegressionModel`
* alpha, beta in the `generateAFTInput` of unit tests
I propose we standardize the parameterization so that the code base is easier to understand and maintain. I prefer the parameterization in `AFTAggregator`.
* Documentation of model and algorithm
I recommend we document the model as well as formula used in the estimation.
cc @mengxr
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140360293
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138509653
@rotationsymmetry I agree with you, updated PR. Thanks for your comments.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141333226
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141337339
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39667014
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ lambda
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, weights, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * For random lifetime T_{i} of subjects i = 1, ..., n, with possible right-censoring,
+ * the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The the log of scale parameter,
+ * the intercept and weights/coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ private val beta = weights.slice(1, weights.length)
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
--- End diff --
add a check for `totalCnt==0` like in `loss`?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39538309
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
--- End diff --
`Accelerated failure time` -> `accelerated failure time (AFT)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140351032
@mengxr @rotationsymmetry
Thanks for all your helpful comments. I have updated the PR and add necessary documents.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39130798
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTRegressionSuite.scala ---
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.feature.OneHotEncoder
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.functions._
+
+import scala.util.Random
+
+case class AFTExamplePoint(stage: Double, time: Double, age: Int, year: Int, censored: Double)
+
+case class AFTPoint(features: Vector, censored: Double, label: Double)
+
+class AFTRegressionSuite extends SparkFunSuite with MLlibTestSparkContext {
+
+ @transient var datasetUnivariate: DataFrame = _
+ @transient var datasetMultivariate: DataFrame = _
+
+ override def beforeAll(): Unit = {
+ super.beforeAll()
+ datasetUnivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 1, Array(5.5), Array(0.8), 1000, 42, 1.0, 2.0)))
+ datasetMultivariate = sqlContext.createDataFrame(
+ sc.parallelize(generateAFTInput(
+ 2, Array(0.9, -1.3), Array(0.7, 1.2), 1000, 42, 1.5, 2.5)))
+ }
+
+ test("params") {
+ ParamsSuite.checkParams(new AFTRegression)
+ val model = new AFTRegressionModel("aftReg", Vectors.dense(0.0), 0.0, 0.0)
+ ParamsSuite.checkParams(model)
+ }
+
+ test("aft regression: default params") {
+ val aftr = new AFTRegression
+ assert(aftr.getLabelCol === "label")
+ assert(aftr.getFeaturesCol === "features")
+ assert(aftr.getPredictionCol === "prediction")
+ assert(aftr.getFitIntercept)
+ val model = aftr.fit(datasetUnivariate)
+
+ // copied model must have the same parent.
+ MLTestingUtils.checkCopy(model)
+
+ assert(model.getFeaturesCol === "features")
+ assert(model.getPredictionCol === "prediction")
+ assert(model.getQuantileCol == "quantile")
+ assert(model.intercept !== 0.0)
+ assert(model.hasParent)
+ }
+
+ def generateAFTInput(
+ numFeatures: Int,
+ xMean: Array[Double],
+ xVariance: Array[Double],
+ nPoints: Int,
+ seed: Int,
+ alpha: Double,
+ beta: Double): Seq[AFTPoint] = {
+
+ def censored(x: Double, y: Double): Double = {
+ if (x <= y) 1.0 else 0.0
+ }
+
+ val weibull = new WeibullGenerator(alpha, beta)
+ weibull.setSeed(seed)
+
+ val exponential = new ExponentialGenerator(2.0)
+ exponential.setSeed(seed)
+
+ val rnd = new Random(seed)
+ val x = Array.fill[Array[Double]](nPoints)(
+ Array.fill[Double](numFeatures)(rnd.nextDouble()))
+
+ x.foreach { v =>
+ var i = 0
+ val len = v.length
+ while (i < len) {
+ v(i) = (v(i) - 0.5) * math.sqrt(12.0 * xVariance(i)) + xMean(i)
+ i += 1
+ }
+ }
+ val y = (1 to nPoints).map { i =>
+ (weibull.nextValue(), exponential.nextValue())
+ }
+
+ y.zip(x).map { p =>
+ AFTPoint(Vectors.dense(p._2), censored(p._1._1, p._1._2), p._1._1)
+ }
+ }
+
+ test("aft regression with univariate") {
+ val trainer = new AFTRegression
+ val model = trainer.fit(datasetUnivariate)
+
+ /*
+ Using the following R code to load the data and train the model using survival package.
+
+ > library("survival")
+ > data <- read.csv("path", header=FALSE, stringsAsFactors=FALSE)
+ > features <- as.matrix(data.frame(as.numeric(data$V1)))
+ > censored <- as.numeric(data$V2)
+ > label <- as.numeric(data$V3)
+ > sr.fit <- survreg(Surv(label, censored)~features, dist='weibull')
+ > summary(sr.fit)
+
+ survreg(formula = Surv(label, censored) ~ features, dist = "weibull")
+ Value Std. Error z p
+ (Intercept) 1.759 0.4141 4.247 2.16e-05
+ features -0.039 0.0735 -0.531 5.96e-01
+ Log(scale) 0.344 0.0379 9.073 1.16e-19
+
+ Scale= 1.41
+
+ Weibull distribution
+ Loglik(model)= -1152.2 Loglik(intercept only)= -1152.3
+ Chisq= 0.28 on 1 degrees of freedom, p= 0.6
+ Number of Newton-Raphson Iterations: 5
+ n= 1000
+ */
+ val weightsR = Vectors.dense(-0.039)
+ val interceptR = 1.759
+ val scaleR = 1.41
+
+ assert(model.intercept ~== interceptR relTol 1E-3)
+ assert(model.weights ~= weightsR relTol 1E-3)
+ assert(model.scale ~= scaleR relTol 1E-3)
+
+ val features = Vectors.dense(4.675290165370009)
+ val quantile = Vectors.dense(Array(0.1, 0.5, 0.9))
+ val expected = model.predict(features, quantile)
+ }
+
+ test("aft regression with multivariate") {
--- End diff --
Add test cases for `fitIntercept` is `true` or `false`.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138862663
[Test build #42200 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42200/consoleFull) for PR 8611 at commit [`b7dd012`](https://github.com/apache/spark/commit/b7dd0129759e6337aa99a2db6a59abfaec484407).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138278180
[Test build #42092 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42092/console) for PR 8611 at commit [`4223793`](https://github.com/apache/spark/commit/422379328962a5c0bccbdcd93f52f3f7857a61ba).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTRegression(override val uid: String)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138270809
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138270202
Merged build started.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39750273
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
--- End diff --
Done.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39130715
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTRegression.scala ---
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile column name.
+ * @group param
+ */
+ final val quantileCol: Param[String] = new Param[String](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantileCol: String = $(quantileCol)
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ } else {
+ SchemaUtils.checkColumnType(schema, $(quantileCol), new VectorUDT)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+@Experimental
+class AFTRegression(override val uid: String)
+ extends Estimator[AFTRegressionModel] with AFTRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (feature, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(feature: Vector, label: Double, censored: Double) =>
+ (feature, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = new DenseVector(Array.fill(numFeatures + 2)(1.0))
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ // println(state.fVals.mkString(","))
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTRegression]].
+ */
+@Experimental
+class AFTRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTRegressionModel] with AFTRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setQuantileCol(value: String): this.type = set(quantileCol, value)
+ setDefault(quantileCol -> "quantile")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ def predict(features: Vector, quantile: Vector): Vector = {
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = quantile.toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { (features: Vector, quantile: Vector) => predict(features, quantile) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol)), col($(quantileCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTRegressionModel = {
+ copyValues(new AFTRegressionModel(uid, weights, intercept, scale), extra).setParent(parent)
+ }
+}
+
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ private val beta = weights.slice(1, weights.length)
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
+ gradientBetaSum/totalCnt.toDouble)
+
+ def add(data: (Vector, Double, Double)): this.type = {
+
+ val xi = if (fitIntercept) {
--- End diff --
revise depending on how you decide to set up the `initalWeights`. See comment above.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39067228
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTRegression.scala ---
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile column name.
+ * @group param
+ */
+ final val quantileCol: Param[String] = new Param[String](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantileCol: String = $(quantileCol)
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ } else {
+ SchemaUtils.checkColumnType(schema, $(quantileCol), new VectorUDT)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+@Experimental
+class AFTRegression(override val uid: String)
+ extends Estimator[AFTRegressionModel] with AFTRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (feature, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(feature: Vector, label: Double, censored: Double) =>
+ (feature, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = new DenseVector(Array.fill(numFeatures + 2)(1.0))
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ // println(state.fVals.mkString(","))
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
--- End diff --
I think we need to check if `fitIntercept == true`.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141281303
@yanboliang Let's rename `censoredCol` back to `cencorCol` and fix small issues I mentioned inline. Then this PR should be good to go. We can make another PR to add `quantileCol`.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138277354
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42091/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39130610
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTRegression.scala ---
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile column name.
+ * @group param
+ */
+ final val quantileCol: Param[String] = new Param[String](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantileCol: String = $(quantileCol)
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ } else {
+ SchemaUtils.checkColumnType(schema, $(quantileCol), new VectorUDT)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+@Experimental
+class AFTRegression(override val uid: String)
+ extends Estimator[AFTRegressionModel] with AFTRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (feature, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(feature: Vector, label: Double, censored: Double) =>
+ (feature, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = new DenseVector(Array.fill(numFeatures + 2)(1.0))
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ // println(state.fVals.mkString(","))
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTRegressionModel(uid, realWeights, intercept, scale)
--- End diff --
set `intercept` to be zero if `fitIntercept` is `false`.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141110271
[Test build #42603 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42603/console) for PR 8611 at commit [`dc1d59f`](https://github.com/apache/spark/commit/dc1d59f68ec19da0d35510b2b1aad0df3c8fd2a2).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138872933
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42200/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532405
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
+ Vectors.dense(array)
+ }
+
+ def predict(features: Vector): Double = {
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ lambda
+ }
+
+ override def transform(dataset: DataFrame): DataFrame = {
+ transformSchema(dataset.schema)
+ val predictUDF = udf { features: Vector => predict(features) }
+ dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = false)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegressionModel = {
+ copyValues(new AFTSurvivalRegressionModel(uid, weights, intercept, scale), extra)
+ .setParent(parent)
+ }
+}
+
+/**
+ * AFTAggregator computes the gradient and loss for a AFT loss function,
+ * as used in AFT survival regression for samples in sparse or dense vector in a online fashion.
+ *
+ * The loss function and likelihood function under the AFT model based on:
+ * Lawless, J. F., Statistical Models and Methods for Lifetime Data,
+ * New York: John Wiley & Sons, Inc. 2003.
+ *
+ * Two AFTAggregator can be merged together to have a summary of loss and gradient of
+ * the corresponding joint dataset.
+ *
+ * For random lifetime T_{i} of subjects i = 1, ..., n, with possible right-censoring,
+ * the likelihood function under the AFT model is given as
+ * {{{
+ * L(\beta,\sigma)=\prod_{i=1}^n[\frac{1}{\sigma}f_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})]^{\delta_{i}}S_{0}
+ * (\frac{\log{t_{i}}-x^{'}\beta}{\sigma})^{1-\delta_{i}}
+ * }}}
+ * Using \epsilon_{i}=\frac{\log{t_{i}}-x^{'}\beta}{\sigma}, the log-likelihood function
+ * assumes the form
+ * {{{
+ * \iota(\beta,\sigma)=\sum_{i=1}^{n}[-\delta_{i}\log\sigma+
+ * \delta_{i}\log{f_{0}}(\epsilon_{i})+(1-\delta_{i})\log{S_{0}(\epsilon_{i})}]
+ * }}}
+ * Where S_{0}(\epsilon_{i}) is the baseline survivor function
+ * and f_{0}(\epsilon_{i}) is corresponding density function.
+ * The most commonly used log-linear survival regression method is based on the Weibull
+ * distribution of the survival time. The Weibull distribution for lifetime corresponding
+ * to extreme value distribution for log of the lifetime,
+ * and the S_{0}(\epsilon) function is
+ * {{{
+ * S_{0}(\epsilon_{i})=\exp(-e^{\epsilon_{i}})
+ * }}}
+ * the f_{0}(\epsilon_{i}) function is
+ * {{{
+ * f_{0}(\epsilon_{i})=e^{\epsilon_{i}}\exp(-e^{\epsilon_{i}})
+ * }}}
+ * The log-likelihood function for Weibull distribution is
+ * {{{
+ * \iota(\beta,\sigma)=
+ * -\sum_{i=1}^n[\delta_{i}\log\sigma-\delta_{i}\epsilon_{i}+e^{\epsilon_{i}}]
+ * }}}
+ * Due to minimizing the negative log-likelihood equivalent to maximum a posteriori probability,
+ * the loss function we use to optimize is -\iota(\beta,\sigma).
+ * The gradient functions for \beta and \log\sigma respectively are
+ * {{{
+ * \frac{\partial (-\iota)}{\partial \beta}=
+ * \sum_{1=1}^{n}[\delta_{i}-e^{\epsilon_{i}}]\frac{x_{i}}{\sigma}
+ * }}}
+ * {{{
+ * \frac{\partial (-\iota)}{\partial (\log\sigma)}=
+ * \sum_{i=1}^{n}[\delta_{i}+(\delta_{i}-e^{\epsilon_{i}})\epsilon_{i}]
+ * }}}
+ * @param weights The the log of scale parameter,
+ * the intercept and weights/coefficients corresponding to the features.
+ * @param fitIntercept Whether to fit an intercept term.
+ */
+private class AFTAggregator(weights: BDV[Double], fitIntercept: Boolean)
+ extends Serializable {
+
+ private val beta = weights.slice(1, weights.length)
+ private val sigma = math.exp(weights(0))
+
+ private var totalCnt: Long = 0L
+ private var lossSum = 0.0
+ private var gradientBetaSum = BDV.zeros[Double](beta.length)
+ private var gradientLogSigmaSum = 0.0
+
+ def count: Long = totalCnt
+ def loss: Double = if (totalCnt == 0) 1.0 else lossSum / totalCnt
+ // Here we optimize loss function over beta and log(sigma)
+ def gradient: BDV[Double] = BDV.vertcat(BDV(Array(gradientLogSigmaSum / totalCnt.toDouble)),
+ gradientBetaSum/totalCnt.toDouble)
+
+ /**
+ * Add a new training data to this AFTAggregator, and update the loss and gradient
+ * of the objective function.
+ *
+ * @param data The (features, label, censored) triple for one data point to be added
+ * into this aggregator.
+ * @return This AFTAggregator object.
+ */
+ def add(data: (Vector, Double, Double)): this.type = {
--- End diff --
This method becomes more readable if we define a private case class to wrap `(Vector, Double, Double)`.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532361
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
--- End diff --
We might have trouble with serialization in Python. Shall we make it `DoubleArrayParam`? It should be dense anyway.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138116045
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138277353
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:
https://github.com/apache/spark/pull/8611
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39105688
--- Diff: mllib/src/test/scala/org/apache/spark/ml/regression/AFTRegressionSuite.scala ---
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.ml.feature.OneHotEncoder
+import org.apache.spark.ml.param.ParamsSuite
+import org.apache.spark.ml.util.MLTestingUtils
+import org.apache.spark.mllib.linalg.{Vector, Vectors}
+import org.apache.spark.mllib.random.{ExponentialGenerator, WeibullGenerator}
+import org.apache.spark.mllib.util.TestingUtils._
+import org.apache.spark.mllib.util.MLlibTestSparkContext
+import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.functions._
+
+import scala.util.Random
+
+case class AFTExamplePoint(stage: Double, time: Double, age: Int, year: Int, censored: Double)
--- End diff --
make this private?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138521700
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42128/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by rotationsymmetry <gi...@git.apache.org>.
Github user rotationsymmetry commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39065614
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTRegression.scala ---
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{DenseVector, Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile column name.
+ * @group param
+ */
+ final val quantileCol: Param[String] = new Param[String](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantileCol: String = $(quantileCol)
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ } else {
+ SchemaUtils.checkColumnType(schema, $(quantileCol), new VectorUDT)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+@Experimental
+class AFTRegression(override val uid: String)
+ extends Estimator[AFTRegressionModel] with AFTRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
--- End diff --
Please provide documentation for public API. Similar for other setters.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141096732
[Test build #42603 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42603/consoleFull) for PR 8611 at commit [`dc1d59f`](https://github.com/apache/spark/commit/dc1d59f68ec19da0d35510b2b1aad0df3c8fd2a2).
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39537937
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
+ val intercept: Double,
+ val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ def setQuantile(value: Vector): this.type = set(quantile, value)
+
+ def quantilePredict(features: Vector): Vector = {
+ require(hasQuantile, "AFTSurvivalRegressionModel quantilePredict must set quantile vector")
+ // scale parameter of the Weibull distribution
+ val lambda = math.exp(weights.toBreeze.dot(features.toBreeze) + intercept)
+ // shape parameter of the Weibull distribution
+ val k = 1 / scale
+ val array = $(quantile).toArray.map { q => lambda * math.exp(math.log(-math.log(1-q)) / k) }
--- End diff --
space around operators:
~~scala
val array = $(quantile).toArray.map { q =>
lambda * math.exp(math.log(-math.log(1 - q)) / k)
}
~~~
~~~
Give `array` a better name?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39537611
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extracts (features, label, censored) from input dataset.
+ */
+ protected[ml] def extractCensoredLabeledPoints(
+ dataset: DataFrame): RDD[(Vector, Double, Double)] = {
+ dataset.select($(featuresCol), $(labelCol), $(censorCol))
+ .map { case Row(features: Vector, label: Double, censored: Double) =>
+ (features, label, censored)
+ }
+ }
+
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractCensoredLabeledPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, weights vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val realWeights = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, realWeights, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+class AFTSurvivalRegressionModel private[ml] (
+ override val uid: String,
+ val weights: Vector,
--- End diff --
rename `weights` to `coefficients`, as discussed in https://issues.apache.org/jira/browse/SPARK-10592
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-140360296
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42484/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138872927
Merged build finished. Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138521533
[Test build #42128 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42128/console) for PR 8611 at commit [`28ca4c0`](https://github.com/apache/spark/commit/28ca4c02f3765b345bb39f457635fbecb6971f49).
* This patch **passes all tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class AFTRegression(override val uid: String)`
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138116046
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/42073/
Test PASSed.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39811774
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,447 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.{Since, Experimental}
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.mllib.linalg.BLAS
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for accelerated failure time (AFT) regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * The value of this column could be 0 or 1.
+ * If the value is 1, it means the event has occurred i.e. uncensored; otherwise it censored.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val censoredCol: Param[String] = new Param(this, "censoredCol", "censored column name")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getCensoredCol: String = $(censoredCol)
+
+ /**
+ * Param for quantile probabilities array.
+ * Values of the quantile probabilities array should be in the range [0, 1].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val quantileProbabilities: DoubleArrayParam = new DoubleArrayParam(this, "quantile",
+ "quantile probabilities array", (t: Array[Double]) => t.forall(ParamValidators.inRange(0, 1)))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getQuantileProbabilities: Array[Double] = $(quantileProbabilities)
+
+ /** Checks whether the input has quantile probabilities array. */
+ protected[regression] def hasQuantileProbabilities: Boolean = {
+ isDefined(quantileProbabilities) && $(quantileProbabilities).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censoredCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named accelerated failure time (AFT) model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegression @Since("1.6.0") (@Since("1.6.0") override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ @Since("1.6.0")
+ def this() = this(Identifiable.randomUID("aftSurvReg"))
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setCensoredCol(value: String): this.type = set(censoredCol, value)
+ setDefault(censoredCol -> "censored")
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ @Since("1.6.0")
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
+
+ /**
+ * Extract [[featuresCol]], [[labelCol]] and [[censoredCol]] from input dataset,
+ * and put it in an RDD with strong types.
+ */
+ protected[ml] def extractAFTPoints(
+ dataset: DataFrame): RDD[AFTPoint] = {
+ dataset.select($(featuresCol), $(labelCol), $(censoredCol)).map {
+ case Row(features: Vector, label: Double, censored: Double) =>
+ AFTPoint(features, label, censored)
+ }
+ }
+
+ @Since("1.6.0")
+ override def fit(dataset: DataFrame): AFTSurvivalRegressionModel = {
+ validateAndTransformSchema(dataset.schema, fitting = true)
+ val instances = extractAFTPoints(dataset)
+ val handlePersistence = dataset.rdd.getStorageLevel == StorageLevel.NONE
+ if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
+
+ val costFun = new AFTCostFun(instances, $(fitIntercept))
+ val optimizer = new BreezeLBFGS[BDV[Double]]($(maxIter), 10, $(tol))
+
+ val numFeatures = dataset.select($(featuresCol)).take(1)(0).getAs[Vector](0).size
+ /*
+ The weights vector has three parts:
+ the first element: Double, log(sigma), the log of scale parameter
+ the second element: Double, intercept of the beta parameter
+ the third to the end elements: Doubles, regression coefficients vector of the beta parameter
+ */
+ val initialWeights = Vectors.zeros(numFeatures + 2)
+
+ val states = optimizer.iterations(new CachedDiffFunction(costFun),
+ initialWeights.toBreeze.toDenseVector)
+
+ val weights = {
+ val arrayBuilder = mutable.ArrayBuilder.make[Double]
+ var state: optimizer.State = null
+ while (states.hasNext) {
+ state = states.next()
+ arrayBuilder += state.adjustedValue
+ }
+ if (state == null) {
+ val msg = s"${optimizer.getClass.getName} failed."
+ throw new SparkException(msg)
+ }
+
+ val rawWeights = state.x.toArray.clone()
+ rawWeights
+ }
+
+ if (handlePersistence) instances.unpersist()
+
+ val coefficients = Vectors.dense(weights.slice(2, weights.length))
+ val intercept = weights(1)
+ val scale = math.exp(weights(0))
+ val model = new AFTSurvivalRegressionModel(uid, coefficients, intercept, scale)
+ copyValues(model.setParent(this))
+ }
+
+ @Since("1.6.0")
+ override def transformSchema(schema: StructType): StructType = {
+ validateAndTransformSchema(schema, fitting = true)
+ }
+
+ @Since("1.6.0")
+ override def copy(extra: ParamMap): AFTSurvivalRegression = defaultCopy(extra)
+}
+
+/**
+ * :: Experimental ::
+ * Model produced by [[AFTSurvivalRegression]].
+ */
+@Experimental
+@Since("1.6.0")
+class AFTSurvivalRegressionModel private[ml] (
+ @Since("1.6.0") override val uid: String,
+ @Since("1.6.0") val coefficients: Vector,
+ @Since("1.6.0") val intercept: Double,
+ @Since("1.6.0") val scale: Double)
+ extends Model[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams {
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /** @group setParam */
+ @Since("1.6.0")
+ def setQuantileProbabilities(value: Array[Double]): this.type = set(quantileProbabilities, value)
+
+ @Since("1.6.0")
+ def predictQuantiles(features: Vector): Vector = {
--- End diff --
We should add a string param called `quantileCol`, which defaults to `""`. If this is set, we should append two columns to the output: 1. prediction, 2. quantiles. We can do this in a follow-up PR.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by mengxr <gi...@git.apache.org>.
Github user mengxr commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39532370
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
--- End diff --
Use the same tolerance as in linear regression, `1e-3`?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-141094736
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [SPARK-8518] [ML] Log-linear models for surviv...
Posted by yanboliang <gi...@git.apache.org>.
Github user yanboliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/8611#discussion_r39749414
--- Diff: mllib/src/main/scala/org/apache/spark/ml/regression/AFTSurvivalRegression.scala ---
@@ -0,0 +1,400 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.ml.regression
+
+import scala.collection.mutable
+
+import breeze.linalg.{DenseVector => BDV}
+import breeze.optimize.{CachedDiffFunction, DiffFunction, LBFGS => BreezeLBFGS}
+
+import org.apache.spark.{SparkException, Logging}
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.ml.{Model, Estimator}
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{Row, DataFrame}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{DoubleType, StructType}
+import org.apache.spark.storage.StorageLevel
+
+/**
+ * Params for Accelerated Failure Time regression.
+ */
+private[regression] trait AFTSurvivalRegressionParams extends Params
+ with HasFeaturesCol with HasLabelCol with HasPredictionCol with HasMaxIter
+ with HasTol with HasFitIntercept {
+
+ /**
+ * Param for censored column name.
+ * @group param
+ */
+ final val censorCol: Param[String] = new Param[String](this, "censorCol", "censored column name")
+
+ /** @group getParam */
+ final def getCensorCol: String = $(censorCol)
+
+ /**
+ * Param for quantile vector.
+ * @group param
+ */
+ final val quantile: Param[Vector] = new Param[Vector](this,
+ "quantileCol", "quantile column name")
+
+ /** @group getParam */
+ final def getQuantile: Vector = $(quantile)
+
+ /** Checks whether the input has quantile vector. */
+ protected[ml] def hasQuantile: Boolean = {
+ isDefined(quantile) && $(quantile).size != 0
+ }
+
+ /**
+ * Validates and transforms the input schema with the provided param map.
+ * @param schema input schema
+ * @param fitting whether this is in fitting or prediction
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(
+ schema: StructType,
+ fitting: Boolean): StructType = {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ if (fitting) {
+ SchemaUtils.checkColumnType(schema, $(censorCol), DoubleType)
+ SchemaUtils.checkColumnType(schema, $(labelCol), DoubleType)
+ }
+ SchemaUtils.appendColumn(schema, $(predictionCol), DoubleType)
+ }
+}
+
+/**
+ * :: Experimental ::
+ * Fit a parametric survival regression model named Accelerated failure time model
+ * ([[https://en.wikipedia.org/wiki/Accelerated_failure_time_model]])
+ * based on the Weibull distribution of the survival time.
+ */
+@Experimental
+class AFTSurvivalRegression(override val uid: String)
+ extends Estimator[AFTSurvivalRegressionModel] with AFTSurvivalRegressionParams with Logging {
+
+ def this() = this(Identifiable.randomUID("aftReg"))
+
+ /** @group setParam */
+ def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+ /** @group setParam */
+ def setLabelCol(value: String): this.type = set(labelCol, value)
+
+ /** @group setParam */
+ def setCensorCol(value: String): this.type = set(censorCol, value)
+ setDefault(censorCol -> "censored")
+
+ /** @group setParam */
+ def setPredictionCol(value: String): this.type = set(predictionCol, value)
+
+ /**
+ * Set if we should fit the intercept
+ * Default is true.
+ * @group setParam
+ */
+ def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
+ setDefault(fitIntercept -> true)
+
+ /**
+ * Set the maximum number of iterations.
+ * Default is 100.
+ * @group setParam
+ */
+ def setMaxIter(value: Int): this.type = set(maxIter, value)
+ setDefault(maxIter -> 100)
+
+ /**
+ * Set the convergence tolerance of iterations.
+ * Smaller value will lead to higher accuracy with the cost of more iterations.
+ * Default is 1E-6.
+ * @group setParam
+ */
+ def setTol(value: Double): this.type = set(tol, value)
+ setDefault(tol -> 1E-6)
--- End diff --
AFAIK the default tolerance of both [```LogisticRegression```](https://github.com/apache/spark/blob/43c7ec6384e51105dedf3a53354b6a3732cc27b2/mllib/src/main/scala/org/apache/spark/ml/classification/LogisticRegression.scala#L91) and [```LinearRegression```](https://github.com/apache/spark/blob/43c7ec6384e51105dedf3a53354b6a3732cc27b2/mllib/src/main/scala/org/apache/spark/ml/regression/LinearRegression.scala#L100) are ```1E-6```.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request: [WIP] [SPARK-8518] [ML] Log-linear models for ...
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:
https://github.com/apache/spark/pull/8611#issuecomment-138270187
Merged build triggered.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org