Github user mengxr commented on a diff in the pull request:

    https://github.com/apache/spark/pull/1814#discussion_r15920617
  
    --- Diff: mllib/src/main/scala/org/apache/spark/mllib/feature/IDF.scala ---
    @@ -177,18 +115,72 @@ private object IDF {
         private def isEmpty: Boolean = m == 0L
     
         /** Returns the current IDF vector. */
    -    def idf(): BDV[Double] = {
    +    def idf(): Vector = {
           if (isEmpty) {
             throw new IllegalStateException("Haven't seen any document yet.")
           }
           val n = df.length
    -      val inv = BDV.zeros[Double](n)
    +      val inv = new Array[Double](n)
           var j = 0
           while (j < n) {
             inv(j) = math.log((m + 1.0)/ (df(j) + 1.0))
             j += 1
           }
    -      inv
    +      Vectors.dense(inv)
         }
       }
     }
    +
    +/**
    + * :: Experimental ::
    + * Represents an IDF model that can transform term frequency vectors.
    + */
    +@Experimental
    +class IDFModel private[mllib] (val idf: Vector) extends Serializable {
    +
    +  /**
    +   * Transforms term frequency (TF) vectors to TF-IDF vectors.
    +   * @param dataset an RDD of term frequency vectors
    +   * @return an RDD of TF-IDF vectors
    +   */
    +  def transform(dataset: RDD[Vector]): RDD[Vector] = {
    +    val bcIdf = dataset.context.broadcast(idf)
    +    dataset.mapPartitions { iter =>
    +      val thisIdf = bcIdf.value
    +      iter.map { v =>
    +        val n = v.size
    +        v match {
    +          case sv: SparseVector =>
    +            val nnz = sv.indices.size
    +            val newValues = new Array[Double](nnz)
    +            var k = 0
    +            while (k < nnz) {
    +              newValues(k) = sv.values(k) * thisIdf(sv.indices(k))
    +              k += 1
    +            }
    +            Vectors.sparse(n, sv.indices, newValues)
    +          case dv: DenseVector =>
    +            val newValues = new Array[Double](n)
    +            var j = 0
    +            while (j < n) {
    +              newValues(j) = dv.values(j) * thisIdf(j)
    +              j += 1
    +            }
    +            Vectors.dense(newValues)
    +          case other =>
    +            throw new UnsupportedOperationException(
    --- End diff --
    
    We might want to use different error messages. In that case, having a util 
function doesn't save us much.


---
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 [email protected] or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to