|
@@ -0,0 +1,166 @@
|
|
|
+package com.tzld.piaoquan.recommend.model
|
|
|
+
|
|
|
+import ml.dmlc.xgboost4j.scala.spark.{XGBoostClassificationModel, XGBoostClassifier}
|
|
|
+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.BinaryClassificationEvaluator
|
|
|
+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
|
|
|
+import scala.util.Random
|
|
|
+
|
|
|
+object train_01_xgb_ad_20250104 {
|
|
|
+ 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", "20240703_ad_feature_name.txt")
|
|
|
+ val trainPath = param.getOrElse("trainPath", "/dw/recommend/model/33_ad_train_data_v4/20240724")
|
|
|
+ val testPath = param.getOrElse("testPath", "/dw/recommend/model/33_ad_train_data_v4/20240725")
|
|
|
+ val savePath = param.getOrElse("savePath", "/dw/recommend/model/34_ad_predict_data/")
|
|
|
+ val featureFilter = param.getOrElse("featureFilter", "XXXXXX").split(",")
|
|
|
+ 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", "binary:logistic")
|
|
|
+ val func_metric = param.getOrElse("func_metric", "auc")
|
|
|
+ val repartition = param.getOrElse("repartition", "20").toInt
|
|
|
+ val negSampleRate = param.getOrElse("negSampleRate", "1").toDouble
|
|
|
+
|
|
|
+ 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)
|
|
|
+
|
|
|
+ var fields = Array(
|
|
|
+ DataTypes.createStructField("label", DataTypes.IntegerType, true)
|
|
|
+ ) ++ features.map(f => DataTypes.createStructField(f, DataTypes.DoubleType, true))
|
|
|
+ fields = fields ++ Array(
|
|
|
+ DataTypes.createStructField("logKey", DataTypes.StringType, true)
|
|
|
+ )
|
|
|
+ val schema = DataTypes.createStructType(fields)
|
|
|
+
|
|
|
+ val trainData = createData4Ad(
|
|
|
+ sc.textFile(trainPath),
|
|
|
+ features,
|
|
|
+ negSampleRate
|
|
|
+ )
|
|
|
+ println("path %s, train data size:%d".format(trainPath, trainData.count()))
|
|
|
+ val trainDataSet: Dataset[Row] = spark.createDataFrame(trainData, schema)
|
|
|
+ val vectorAssembler = new VectorAssembler().setInputCols(features).setOutputCol("features")
|
|
|
+ val xgbInput = vectorAssembler.transform(trainDataSet).select("features", "label")
|
|
|
+
|
|
|
+ val xgbClassifier = new XGBoostClassifier()
|
|
|
+ .setEta(eta)
|
|
|
+ .setGamma(gamma)
|
|
|
+ .setMissing(0.0f)
|
|
|
+ .setMaxDepth(max_depth)
|
|
|
+ .setNumRound(num_round)
|
|
|
+ .setSubsample(0.8)
|
|
|
+ .setColsampleBytree(0.8)
|
|
|
+ .setScalePosWeight(1)
|
|
|
+ .setObjective(func_object)
|
|
|
+ .setEvalMetric(func_metric)
|
|
|
+ .setFeaturesCol("features")
|
|
|
+ .setLabelCol("label")
|
|
|
+ .setNthread(1)
|
|
|
+ .setNumWorkers(num_worker)
|
|
|
+ .setSeed(2024)
|
|
|
+ .setMinChildWeight(1)
|
|
|
+ val model = xgbClassifier.fit(xgbInput)
|
|
|
+
|
|
|
+ val testData = createData4Ad(
|
|
|
+ sc.textFile(testPath),
|
|
|
+ features
|
|
|
+ )
|
|
|
+ val testDataSet = spark.createDataFrame(testData, schema)
|
|
|
+ val testDataSetTrans = vectorAssembler.transform(testDataSet).select("features","label", "logKey")
|
|
|
+ val predictions = model.transform(testDataSetTrans)
|
|
|
+ println("columns:" + predictions.columns.mkString(","))
|
|
|
+ val saveData = predictions.select("label", "rawPrediction", "probability", "logKey").rdd
|
|
|
+ .map(r =>{
|
|
|
+ (r.get(0), r.get(1), r.get(2), r.get(3)).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)
|
|
|
+ }
|
|
|
+
|
|
|
+ val evaluator = new BinaryClassificationEvaluator()
|
|
|
+ .setLabelCol("label")
|
|
|
+ .setRawPredictionCol("probability")
|
|
|
+ .setMetricName("areaUnderROC")
|
|
|
+ val auc = evaluator.evaluate(predictions.select("label", "probability"))
|
|
|
+ println("auc:" + auc)
|
|
|
+
|
|
|
+ // 统计分cid的分数
|
|
|
+ sc.textFile(hdfsPath).map(r=>{
|
|
|
+ val rList = r.split("\t")
|
|
|
+ val cid = rList(3)
|
|
|
+ val score = rList(2).replace("[", "").replace("]", "")
|
|
|
+ .split(",")(1).toDouble
|
|
|
+ val label = rList(0).toDouble
|
|
|
+ (cid, (1, label, score))
|
|
|
+ }).reduceByKey{
|
|
|
+ case (a, b) => (a._1 + b._1, a._2 + b._2, a._3 + b._3)
|
|
|
+ }.map{
|
|
|
+ case (cid, (all, zheng, scores)) =>
|
|
|
+ (cid, all, zheng, scores, zheng / all, scores / all)
|
|
|
+ }.collect().sortBy(_._1).map(_.productIterator.mkString("\t")).foreach(println)
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ def createData4Ad(data: RDD[String], features: Array[String], negativeSampleRate: Double = 1): RDD[Row] = {
|
|
|
+ data.map(r => (r, r.split("\t", 2)(0).toInt, Random.nextDouble()))
|
|
|
+ .filter(r => r._3 < negativeSampleRate || r._2 > 0)
|
|
|
+ .map(r => r._1)
|
|
|
+ .map(r => {
|
|
|
+ val line: Array[String] = StringUtils.split(r, '\t')
|
|
|
+ val label: Int = NumberUtils.toInt(line(0))
|
|
|
+ val map: util.Map[String, Double] = new util.HashMap[String, Double]
|
|
|
+ var cid = "-1"
|
|
|
+ for (i <- 1 until line.length) {
|
|
|
+ val fv: Array[String] = StringUtils.split(line(i), ':')
|
|
|
+ map.put(fv(0), NumberUtils.toDouble(fv(1), 0.0))
|
|
|
+ if (fv(0).startsWith("cid_")) {
|
|
|
+ cid = fv(0).split("_")(1)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ val v: Array[Any] = new Array[Any](features.length + 2)
|
|
|
+ v(0) = label
|
|
|
+ for (i <- features.indices) {
|
|
|
+ v(i + 1) = map.getOrDefault(features(i), 0.0d)
|
|
|
+ }
|
|
|
+ v(features.length + 1) = cid
|
|
|
+ Row(v: _*)
|
|
|
+ })
|
|
|
+ }
|
|
|
+}
|