Search code examples
scalapredictionio

How to combine two object elements


I want to combine two seperate results to one result. My first result is the itemscore from the first algorithm:

PredictedResult(List(ItemScore(140849,0.6259532295250041,0.0,0.0,0.0)),List())

My second result is the Rule score form the second algorithm:

PredictedResult(List(),List(Rule(Set(140855),List(ItemScore(368788,0.0,1.3516984090509725E-5,0.1111111111111111,38.59207094418362)))))

You can see that the first result has an Empty list. This list is filled in the second result. This also applies to the item score, only the other way around.

The serving class is only accepting one of two results, but not combined.

Serving.scala:

package org.template

import org.apache.predictionio.controller.LServing

class Serving
  extends LServing[Query, PredictedResult] {

  override
  def serve(query: Query,
    predictedResults: Seq[PredictedResult]): PredictedResult = {
    println(predictedResults(0))
    println(predictedResults(1))

    // Returning
    predictedResults(0)

    }
}

Engine.json:

    package org.template

import org.apache.predictionio.controller.EngineFactory
import org.apache.predictionio.controller.Engine

// Query most similar (top num) items to the given
case class Query(items: Set[String], num: Int) extends Serializable

case class PredictedResult(itemScores: List[ItemScore], rules: List[Rule])

case class Rule(cond: Set[String], itemScores: List[ItemScore])
  extends Serializable 

case class ItemScore(item: String, score: Double, support: Double, confidence: Double, lift: Double) extends Serializable with
Ordered[ItemScore] {
  def compare(that: ItemScore) = this.score.compare(that.score)
}

When I hit the query, now I get the only one result back:

{"itemScores":[{"item":"140849","score":0.6259532295250041,"support":0.0,"confidence":0.0,"lift":0.0}],"rules":[]}

Expected output (the ItemScore from algorithm1 combined with Rule from algorithm2):

PredictedResult(List(ItemScore(140849,0.6259532295250041,0.0,0.0,0.0)),List(Rule(Set(140855),List(ItemScore(368788,0.0,1.3516984090509725E-5,0.1111111111111111,38.59207094418362)))))

Solution

  • Try list concatenation ++ like so

    case class ItemScore(i: Int)
    case class Rule(s: String, itemScores: List[ItemScore])
    case class PredictedResult(itemScores: List[ItemScore], rules: List[Rule])
    
    val pr1 = PredictedResult(List(ItemScore(1)), Nil)
    val pr2 = PredictedResult(Nil, List(Rule("rule1", List(ItemScore(2)))))
    
    PredictedResult(pr1.itemScores ++ pr2.itemScores, pr1.rules ++ pr2.rules)
    

    which outputs

    res0: PredictedResult = PredictedResult(List(ItemScore(1)),List(Rule(rule1,List(ItemScore(2)))))