|
@@ -0,0 +1,196 @@
|
|
|
+package com.tzld.piaoquan.recommend.model
|
|
|
+
|
|
|
+import com.alibaba.fastjson.JSON
|
|
|
+import com.tzld.piaoquan.recommend.model.produce.util.RosUtil
|
|
|
+import com.tzld.piaoquan.recommend.utils.{MyHdfsUtils, ParamUtils}
|
|
|
+import ml.dmlc.xgboost4j.scala.spark.XGBoostRegressor
|
|
|
+import org.apache.commons.lang.math.NumberUtils
|
|
|
+import org.apache.commons.lang3.StringUtils
|
|
|
+import org.apache.hadoop.io.compress.GzipCodec
|
|
|
+import org.apache.spark.ml.evaluation.RegressionEvaluator
|
|
|
+import org.apache.spark.ml.feature.VectorAssembler
|
|
|
+import org.apache.spark.rdd.RDD
|
|
|
+import org.apache.spark.sql.types.DataTypes
|
|
|
+import org.apache.spark.sql.{Dataset, Row, SparkSession}
|
|
|
+
|
|
|
+import java.util
|
|
|
+import scala.io.Source
|
|
|
+
|
|
|
+/**
|
|
|
+ * 推荐 ros 回归模型,加权损失函数
|
|
|
+ */
|
|
|
+object recsys_01_ros_reg_weight_xgb_train {
|
|
|
+ def main(args: Array[String]): Unit = {
|
|
|
+ val spark = SparkSession
|
|
|
+ .builder()
|
|
|
+ .appName(this.getClass.getName)
|
|
|
+ .getOrCreate()
|
|
|
+ val sc = spark.sparkContext
|
|
|
+
|
|
|
+
|
|
|
+ val param = ParamUtils.parseArgs(args)
|
|
|
+ val featureFile = param.getOrElse("featureFile", "20250306_ros_feature_232.txt")
|
|
|
+ val trainPath = param.getOrElse("trainPath", "/dw/recommend/model/43_recsys_ros_data_bucket/20250301")
|
|
|
+ val testPath = param.getOrElse("testPath", "/dw/recommend/model/43_recsys_ros_data_bucket/20250302")
|
|
|
+ val savePath = param.getOrElse("savePath", "/dw/recommend/model/44_recsys_ros_predict/")
|
|
|
+ val featureFilter = param.getOrElse("featureFilter", "XXXXXX").split(",").filter(_.nonEmpty)
|
|
|
+ val eta = param.getOrElse("eta", "0.01").toDouble
|
|
|
+ val gamma = param.getOrElse("gamma", "0.0").toDouble
|
|
|
+ val max_depth = param.getOrElse("max_depth", "5").toInt
|
|
|
+ val num_round = param.getOrElse("num_round", "100").toInt
|
|
|
+ val num_worker = param.getOrElse("num_worker", "20").toInt
|
|
|
+ val func_object = param.getOrElse("func_object", "reg:squarederror")
|
|
|
+ val func_metric = param.getOrElse("func_metric", "rmse")
|
|
|
+ val repartition = param.getOrElse("repartition", "20").toInt
|
|
|
+ val modelPath = param.getOrElse("modelPath", "/dw/recommend/model/45_recommend_model/20250310_ros_reg_1000")
|
|
|
+ val modelFile = param.getOrElse("modelFile", "model.tar.gz")
|
|
|
+
|
|
|
+ val loader = getClass.getClassLoader
|
|
|
+ val resourceUrl = loader.getResource(featureFile)
|
|
|
+ val content =
|
|
|
+ if (resourceUrl != null) {
|
|
|
+ val content = Source.fromURL(resourceUrl).getLines().mkString("\n")
|
|
|
+ Source.fromURL(resourceUrl).close()
|
|
|
+ content
|
|
|
+ } else {
|
|
|
+ ""
|
|
|
+ }
|
|
|
+ println(content)
|
|
|
+
|
|
|
+ val features = content.split("\n")
|
|
|
+ .map(r => r.replace(" ", "").replaceAll("\n", ""))
|
|
|
+ .filter(r => r.nonEmpty || !featureFilter.contains(r))
|
|
|
+ println("features.size=" + features.length)
|
|
|
+
|
|
|
+ val trainData = createData(
|
|
|
+ sc.textFile(trainPath),
|
|
|
+ features
|
|
|
+ )
|
|
|
+ println("recsys ros:train data size:" + trainData.count())
|
|
|
+
|
|
|
+ var fields = Array(
|
|
|
+ DataTypes.createStructField("label", DataTypes.DoubleType, true)
|
|
|
+ ) ++ features.map(f => DataTypes.createStructField(f, DataTypes.DoubleType, true))
|
|
|
+
|
|
|
+ fields = fields ++ Array(
|
|
|
+ DataTypes.createStructField("logKey", DataTypes.StringType, true),
|
|
|
+ DataTypes.createStructField("weight", DataTypes.DoubleType, true)
|
|
|
+ )
|
|
|
+ val schema = DataTypes.createStructType(fields)
|
|
|
+
|
|
|
+
|
|
|
+ val trainDataSet: Dataset[Row] = spark.createDataFrame(trainData, schema)
|
|
|
+ val vectorAssembler = new VectorAssembler().setInputCols(features).setOutputCol("features")
|
|
|
+ val xgbInput = vectorAssembler.transform(trainDataSet).select("features", "label", "weight").persist()
|
|
|
+ val xgbRegressor = new XGBoostRegressor()
|
|
|
+ .setEta(eta)
|
|
|
+ .setGamma(gamma)
|
|
|
+ .setMissing(0.0f)
|
|
|
+ .setMaxDepth(max_depth)
|
|
|
+ .setNumRound(num_round)
|
|
|
+ .setSubsample(0.8)
|
|
|
+ .setColsampleBytree(0.8)
|
|
|
+ .setObjective(func_object)
|
|
|
+ .setEvalMetric(func_metric)
|
|
|
+ .setFeaturesCol("features")
|
|
|
+ .setLabelCol("label")
|
|
|
+ .setWeightCol("weight")
|
|
|
+ .setNthread(1)
|
|
|
+ .setNumWorkers(num_worker)
|
|
|
+ .setSeed(2024)
|
|
|
+ .setMinChildWeight(1)
|
|
|
+ val model = xgbRegressor.fit(xgbInput)
|
|
|
+
|
|
|
+ if (modelPath.nonEmpty && modelFile.nonEmpty) {
|
|
|
+ model.write.overwrite.save(modelPath)
|
|
|
+ }
|
|
|
+
|
|
|
+ // 评测数据
|
|
|
+ val testData = createData(
|
|
|
+ sc.textFile(testPath),
|
|
|
+ features
|
|
|
+ )
|
|
|
+ val testDataSet = spark.createDataFrame(testData, schema)
|
|
|
+ println("recsys ros testDataSet schema")
|
|
|
+ testDataSet.printSchema()
|
|
|
+
|
|
|
+ val testDataSetTrans = vectorAssembler.transform(testDataSet).select("features", "label", "logKey")
|
|
|
+ println("recsys ros testDataSetTrans schema")
|
|
|
+ testDataSetTrans.printSchema()
|
|
|
+
|
|
|
+
|
|
|
+ val predictions = model.transform(testDataSetTrans)
|
|
|
+
|
|
|
+ // 保存评估结果
|
|
|
+ println("recsys ros:columns:" + predictions.columns.mkString(",")) //[label, features, prediction]
|
|
|
+ val saveData = predictions.select("label", "prediction", "logKey").rdd
|
|
|
+ .map(r => {
|
|
|
+ (r.get(0), r.get(1), r.get(2)).productIterator.mkString("\t")
|
|
|
+ })
|
|
|
+ val hdfsPath = savePath
|
|
|
+ if (hdfsPath.nonEmpty && hdfsPath.startsWith("/dw/recommend/model/")) {
|
|
|
+ println("删除路径并开始数据写入:" + hdfsPath)
|
|
|
+ MyHdfsUtils.delete_hdfs_path(hdfsPath)
|
|
|
+ saveData.repartition(repartition).saveAsTextFile(hdfsPath, classOf[GzipCodec])
|
|
|
+ } else {
|
|
|
+ println("路径不合法,无法写入:" + hdfsPath)
|
|
|
+ }
|
|
|
+
|
|
|
+ // 计算rmse
|
|
|
+ val evaluator = new RegressionEvaluator()
|
|
|
+ .setLabelCol("label")
|
|
|
+ .setPredictionCol("prediction")
|
|
|
+ .setMetricName("rmse")
|
|
|
+ val rmse = evaluator.evaluate(predictions.select("label", "prediction"))
|
|
|
+ println("recsys nor: rmse:" + rmse)
|
|
|
+
|
|
|
+ sc.textFile(hdfsPath).map(r => {
|
|
|
+ val rList = r.split("\t")
|
|
|
+ val vid = JSON.parseObject(rList(2)).getString("vid")
|
|
|
+ val label = rList(0).toDouble
|
|
|
+ val score = rList(1).toDouble
|
|
|
+ (vid, (1, label, RosUtil.inverseLog(label), score, RosUtil.inverseLog(score)))
|
|
|
+ }).reduceByKey {
|
|
|
+ case (c1, c2) => (
|
|
|
+ c1._1 + c2._1,
|
|
|
+ c1._2 + c2._2,
|
|
|
+ c1._3 + c2._3,
|
|
|
+ c1._4 + c2._4,
|
|
|
+ c1._5 + c2._5
|
|
|
+ )
|
|
|
+ }.map {
|
|
|
+ case (vid, (all, label, originLabel, score, originScore)) =>
|
|
|
+ (vid, all, label / all, score / all, originLabel / all, originScore / all)
|
|
|
+ }
|
|
|
+ .collect()
|
|
|
+ .sortBy(-_._2)
|
|
|
+ .take(200)
|
|
|
+ .map(_.productIterator.mkString("\t"))
|
|
|
+ .foreach(println)
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ def createData(data: RDD[String], features: Array[String]): RDD[Row] = {
|
|
|
+ data.map(r => {
|
|
|
+ val line: Array[String] = StringUtils.split(r, '\t')
|
|
|
+ val logKey = line(0)
|
|
|
+
|
|
|
+ val label: Double = NumberUtils.toDouble(line(1))
|
|
|
+
|
|
|
+ val map: util.Map[String, Double] = new util.HashMap[String, Double]
|
|
|
+ for (i <- 2 until line.length) {
|
|
|
+ val fv: Array[String] = StringUtils.split(line(i), ':')
|
|
|
+ map.put(fv(0), NumberUtils.toDouble(fv(1), 0.0))
|
|
|
+ }
|
|
|
+
|
|
|
+ val v: Array[Any] = new Array[Any](features.length + 3)
|
|
|
+ v(0) = label
|
|
|
+ for (i <- 0 until features.length) {
|
|
|
+ v(i + 1) = map.getOrDefault(features(i), 0.0d)
|
|
|
+ }
|
|
|
+ v(features.length + 1) = logKey
|
|
|
+ v(features.length + 2) = if (label == 0) 1.5 else 3.0 // 设置权重
|
|
|
+ Row(v: _*)
|
|
|
+ })
|
|
|
+ }
|
|
|
+}
|