-
Notifications
You must be signed in to change notification settings - Fork 393
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Possibility to Return top K positives and top K negatives for LOCO #264
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
84e2387
TopK Strategy Param
mweilsalesforce 9fa76e5
Changing TransformFn
mweilsalesforce 9bce44f
Fix tests
mweilsalesforce 128f62a
Add more tests
mweilsalesforce 0a284bd
Merge branch 'master' into mw/LOCO-improvement
michaelweilsalesforce aea94de
Merge branch 'master' into mw/LOCO-improvement
tovbinm 97bb413
strat -> strategy
mweilsalesforce 2ef84ee
Merge branch 'mw/LOCO-improvement' of https://github.com/salesforce/T…
mweilsalesforce 0cec1c9
getTopKStrategy + method for each strat
mweilsalesforce 756cf0c
use while - it's faster
mweilsalesforce f3de950
Removing redundant lines
mweilsalesforce 19a9199
IndexToExamine
mweilsalesforce ea0069d
posNeg then Absolute
mweilsalesforce fba47ef
Adding withClue
mweilsalesforce 21a653f
diffToExamine
mweilsalesforce dac78ba
Minor changes
mweilsalesforce a137d61
Nicer Pattern match
mweilsalesforce File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -37,18 +37,26 @@ import com.salesforce.op.stages.impl.selector.SelectedModel | |
import com.salesforce.op.stages.sparkwrappers.specific.OpPredictorWrapperModel | ||
import com.salesforce.op.stages.sparkwrappers.specific.SparkModelConverter._ | ||
import com.salesforce.op.utils.spark.OpVectorMetadata | ||
import enumeratum.{Enum, EnumEntry} | ||
import org.apache.spark.annotation.Experimental | ||
import org.apache.spark.ml.Model | ||
import org.apache.spark.ml.linalg.Vectors | ||
import org.apache.spark.ml.param.IntParam | ||
import org.apache.spark.ml.param.{IntParam, Param} | ||
|
||
import scala.collection.mutable.PriorityQueue | ||
|
||
/** | ||
* Creates record level insights for model predictions. Takes the model to explain as a constructor argument. | ||
* The input feature is the feature vector fed into the model. | ||
* @param model model instance that you wish to explain | ||
* @param uid uid for instance | ||
* | ||
* The map's contents are different regarding the value of the topKStrategy param (only for Binary Classification | ||
* and Regression) : | ||
* - If PositiveNegative, returns at most 2 * topK elements : the topK most positive and the topK most negative | ||
* derived features based on the LOCO insight.For MultiClassification, the value is from the predicted class | ||
* (i.e. the class having the highest probability) | ||
* - If Abs, returns at most topK elements : the topK derived features having highest absolute value of LOCO score. | ||
* @param model model instance that you wish to explain | ||
* @param uid uid for instance | ||
*/ | ||
@Experimental | ||
class RecordInsightsLOCO[T <: Model[T]] | ||
|
@@ -61,10 +69,24 @@ class RecordInsightsLOCO[T <: Model[T]] | |
parent = this, name = "topK", | ||
doc = "Number of insights to keep for each record" | ||
) | ||
|
||
def setTopK(value: Int): this.type = set(topK, value) | ||
|
||
def getTopK: Int = $(topK) | ||
|
||
setDefault(topK -> 20) | ||
|
||
final val topKStrategy = new Param[String](parent = this, name = "topKStrategy", | ||
doc = "Whether returning topK based on absolute value or topK positives and negatives. For MultiClassification," + | ||
" the value is from the predicted class (i.e. the class having the highest probability)" | ||
) | ||
|
||
def setTopKStrategy(strategy: TopKStrategy): this.type = set(topKStrategy, strategy.entryName) | ||
|
||
def getTopKStrategy: TopKStrategy = TopKStrategy.withName($(topKStrategy)) | ||
|
||
setDefault(topKStrategy, TopKStrategy.Abs.entryName) | ||
|
||
private val modelApply = model match { | ||
case m: SelectedModel => m.transformFn | ||
case m: OpPredictorWrapperModel[_] => m.transformFn | ||
|
@@ -74,9 +96,55 @@ class RecordInsightsLOCO[T <: Model[T]] | |
|
||
private lazy val featureInfo = OpVectorMetadata(getInputSchema()(in1.name)).getColumnHistory().map(_.toJson(false)) | ||
|
||
private def computeDiffs(i: Int, oldInd: Int, oldVal: Double, featureArray: Array[(Int, Double)], featureSize: Int, | ||
baseScore: Array[Double]): Array[Double] = { | ||
featureArray.update(i, (oldInd, 0)) | ||
val score = modelApply(labelDummy, OPVector(Vectors.sparse(featureSize, featureArray))).score | ||
val diffs = baseScore.zip(score).map { case (b, s) => b - s } | ||
featureArray.update(i, (oldInd, oldVal)) | ||
diffs | ||
} | ||
|
||
private def returnTopPosNeg(filledSize: Int, featureArray: Array[(Int, Double)], featureSize: Int, | ||
baseScore: Array[Double], k: Int, indexToExamine: Int): Seq[(Int, Double, Array[Double])] = { | ||
// Heap that will contain the top K positive LOCO values | ||
val positiveMaxHeap = PriorityQueue.empty(MinScore) | ||
// Heap that will contain the top K negative LOCO values | ||
val negativeMaxHeap = PriorityQueue.empty(MaxScore) | ||
// for each element of the feature vector != 0.0 | ||
// Size of positive heap | ||
var positiveCount = 0 | ||
// Size of negative heap | ||
var negativeCount = 0 | ||
var i = 0 | ||
while (i < filledSize) { | ||
val (oldInd, oldVal) = featureArray(i) | ||
val diffToExamine = computeDiffs(i, oldInd, oldVal, featureArray, featureSize, baseScore) | ||
val max = diffToExamine(indexToExamine) | ||
|
||
if (max > 0.0) { // if positive LOCO then add it to positive heap | ||
positiveMaxHeap.enqueue((i, max, diffToExamine)) | ||
positiveCount += 1 | ||
if (positiveCount > k) { // remove the lowest element if the heap size goes from 5 to 6 | ||
positiveMaxHeap.dequeue() | ||
} | ||
} else if (max < 0.0) { // if negative LOCO then add it to negative heap | ||
negativeMaxHeap.enqueue((i, max, diffToExamine)) | ||
negativeCount += 1 | ||
if (negativeCount > k) { // remove the highest element if the heap size goes from 5 to 6 | ||
negativeMaxHeap.dequeue() | ||
} // Not keeping LOCOs with value 0 | ||
} | ||
i += 1 | ||
} | ||
val topPositive = positiveMaxHeap.dequeueAll | ||
val topNegative = negativeMaxHeap.dequeueAll | ||
(topPositive ++ topNegative) | ||
} | ||
|
||
override def transformFn: OPVector => TextMap = (features) => { | ||
val baseScore = modelApply(labelDummy, features).score | ||
val maxHeap = PriorityQueue.empty(MinScore) | ||
val baseResult = modelApply(labelDummy, features) | ||
val baseScore = baseResult.score | ||
|
||
// TODO sparse implementation only works if changing values to zero - use dense vector to test effect of zeros | ||
val featuresSparse = features.value.toSparse | ||
|
@@ -85,27 +153,47 @@ class RecordInsightsLOCO[T <: Model[T]] | |
val featureSize = featuresSparse.size | ||
|
||
val k = $(topK) | ||
var i = 0 | ||
while (i < filledSize) { | ||
val (oldInd, oldVal) = featureArray(i) | ||
featureArray.update(i, (oldInd, 0)) | ||
val score = modelApply(labelDummy, OPVector(Vectors.sparse(featureSize, featureArray))).score | ||
val diffs = baseScore.zip(score).map{ case (b, s) => b - s } | ||
val max = diffs.maxBy(math.abs) | ||
maxHeap.enqueue((i, max, diffs)) | ||
if (i >= k) maxHeap.dequeue() | ||
featureArray.update(i, (oldInd, oldVal)) | ||
i += 1 | ||
val indexToExamine = baseScore.length match { | ||
case 0 => throw new RuntimeException("model does not produce scores for insights") | ||
case 1 => 0 | ||
case 2 => 1 | ||
case n if (n > 2) => baseResult.prediction.toInt | ||
} | ||
val topPosNeg = returnTopPosNeg(filledSize, featureArray, featureSize, baseScore, k, indexToExamine) | ||
val top = getTopKStrategy match { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
case TopKStrategy.Abs => topPosNeg.sortBy { case (_, v, _) => -math.abs(v) }.take(k) | ||
case TopKStrategy.PositiveNegative => topPosNeg.sortBy { case (_, v, _) => -v } | ||
} | ||
|
||
val top = maxHeap.dequeueAll | ||
top.map{ case (k, _, v) => RecordInsightsParser.insightToText(featureInfo(featureArray(k)._1), v) } | ||
top.map { case (k, _, v) => RecordInsightsParser.insightToText(featureInfo(featureArray(k)._1), v) } | ||
.toMap.toTextMap | ||
} | ||
} | ||
|
||
|
||
private[insights] object MinScore extends Ordering[(Int, Double, Array[Double])] { | ||
/** | ||
* Ordering of the heap that removes lowest score | ||
*/ | ||
private object MinScore extends Ordering[(Int, Double, Array[Double])] { | ||
def compare(x: (Int, Double, Array[Double]), y: (Int, Double, Array[Double])): Int = | ||
y._2 compare x._2 | ||
} | ||
|
||
/** | ||
* Ordering of the heap that removes highest score | ||
*/ | ||
private object MaxScore extends Ordering[(Int, Double, Array[Double])] { | ||
def compare(x: (Int, Double, Array[Double]), y: (Int, Double, Array[Double])): Int = | ||
math.abs(y._2) compare math.abs(x._2) | ||
x._2 compare y._2 | ||
} | ||
|
||
sealed abstract class TopKStrategy(val name: String) extends EnumEntry with Serializable | ||
|
||
object TopKStrategy extends Enum[TopKStrategy] { | ||
val values = findValues | ||
|
||
case object Abs extends TopKStrategy("abs") | ||
|
||
case object PositiveNegative extends TopKStrategy("positive and negative") | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should we remove the
@Experimental
flag already?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no - we want to keep it so we can change things :-) For instance the way of creating this class is still terrible