我正在使用Spark MLlib,并使用逻辑回归模型进行分类。我参考了这个链接:https://spark.apache.org/docs/2.1.0/ml-classification-regression.html#logistic-regression
import org.apache.spark.ml.classification.LogisticRegression;import org.apache.spark.ml.classification.LogisticRegressionModel;import org.apache.spark.sql.Dataset;import org.apache.spark.sql.Row;import org.apache.spark.sql.SparkSession;// 加载训练数据Dataset<Row> training = spark.read().format("libsvm") .load("data/mllib/sample_libsvm_data.txt");LogisticRegression lr = new LogisticRegression() .setMaxIter(10) .setRegParam(0.3) .setElasticNetParam(0.8);// 拟合模型LogisticRegressionModel lrModel = lr.fit(training);// 打印逻辑回归的系数和截距System.out.println("Coefficients: " + lrModel.coefficients() + " Intercept: " + lrModel.intercept());// 我们也可以对二元分类使用多项式家族LogisticRegression mlr = new LogisticRegression() .setMaxIter(10) .setRegParam(0.3) .setElasticNetParam(0.8) .setFamily("multinomial");// 拟合模型LogisticRegressionModel mlrModel = mlr.fit(training);
如果我使用.csv文件作为输入,我不确定这个模型如何识别标签和特征?谁能解释一下?
回答:
最后,我成功解决了这个问题,我需要使用VectorAssembler
或StringIndexer
转换器,在那里我有setInputCol
、setOutputCol
方法,这些方法提供了设置标签和特征的方式。
VectorAssembler assembler = new VectorAssembler() .setInputCols(new String[]{"Lead ID"}) .setOutputCol("features");sparkSession.read().option("header", true).option("inferSchema","true").csv("Book.csv"); dataset = new StringIndexer().setInputCol("Status").setOutputCol("label").fit(dataset).transform(dataset);