Spark ML 学习:Pipline

Pipline
  • Piplines:就是一个工作流程,其中包含要按特定顺序运行的一系列PiplineStages(Transformer和Estimators);一个Pipline在结构上包含一个或多个Stage,每个Stage都会完成一个任务(数据处理、数据装换、模型训练、参数设置等)

  • Transformers:将一个DataFrame转换成另一个DataFrame

  • Estimators:主要做模型拟合,用来生成一个transformer。

其他相关概念

  • DataFrame
  • Parameters:所有transformer和Estimators共享用于指定参数的API。
Pipline实例
import org.apache.spark.ml.{Pipeline, PipelineModel}
import org.apache.spark.sql.{DataFrame,   SparkSession}
import org.apache.spark.ml.classification.LogisticRegression
import org.apache.spark.ml.feature.{
  StringIndexer,
  StringIndexerModel,
  VectorAssembler
}
import org.apache.spark.ml.param.ParamMap

 
object piplinetest {

  def main(args: Array[String]): Unit = {

    val spark = SparkSession
      .builder()
      .appName(s"${this.getClass.getSimpleName}")
      .master("local[*]")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .config("spark.shuffle.consolidateFiles", "true")
      .config("spark.io.compression.codec", "snappy")
      .getOrCreate()

    // 加载训练数据
    val training: DataFrame = spark.read
      .option("header", true)
      .option("inferSchema", true)
      .csv("F:\\DataSource\\iris2.csv")

    val ftsNames =
      Array("sepalLength", "sepalWidth", "petalLength", "petalWidth")

    // 数据转换 VectorAssembler是一个转换器,它将给定列表组合为单个向量列。
    val assembler: VectorAssembler = new VectorAssembler()
      .setInputCols(ftsNames)
      .setOutputCol("features")

    // StringIndexerModel
    val stringIndexer: StringIndexerModel = new StringIndexer()
      .setInputCol("class")
      .setOutputCol("label")
      .fit(training)

    // 创建一个LR模型的实例.
    val lr: LogisticRegression = new LogisticRegression()

    // param 设定模型参数
    val paramMap: ParamMap = ParamMap()
      .put(lr.maxIter, 30) // 单个参数 Param.
      .put(lr.regParam -> 0.1, lr.threshold -> 0.55) //多个参数
      .put(lr.featuresCol -> "features")
      .put(lr.labelCol -> "label")

    // 创建一个Pipline
    val pipeline: Pipeline = new Pipeline()
      .setStages(Array(assembler, stringIndexer, lr))

    // 使用Pipline 拟合模型
    val pipelineModel: PipelineModel = pipeline.fit(training, paramMap)

    // 使用模型预测
    pipelineModel
      .transform(training)
      .show()

    spark.stop

  }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值