如何结合两个对象元素

时间:2019-06-27 10:08:13

标签: scala predictionio

我想将两个单独的结果合并为一个结果。 我的第一个结果是第一个算法的项目得分:

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

我的第二个结果是第二个算法的规则得分:

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

您可以看到第一个结果有一个空列表。此列表填充在第二个结果中。这也适用于项目得分,反之亦然。

服务类别仅接受两个结果之一,但不合并。

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)
}

当我点击查询时,现在我只得到一个结果:

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

预期的输出(algorithm1的ItemScore和algorithm2的Rule结合):

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)))))

1 个答案:

答案 0 :(得分:3)

像这样尝试列表串联++

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)

输出

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