This blog focuses on using Spark's MLIIB to build machine learning models and predict new data, as shown in the following process:
Loading data
For data loading or saving, Mllib provides the Mlutils package, which is helper methods to Load,save and pre-process data used in MLLib. The data in the blog is based on the data sample_libsvm_data.txt provided in Spark, which has 100 data samples and 658 features. Specific data forms:
Load LIBSVM
JavaRDD<LabeledPoint> lpdata = MLUtils.loadLibSVMFile(sc, this.libsvmFile).toJavaRDD();
The Labeledpoint data type is corresponding to the Libsvmfile format file, in the following format:
lable (double type), vector (vector type)
Conversion Dataframe Data types
JavaRDD<Row> jrow = lpdata.map(newnew StructType(new StructField[]{ new StructField("label"false, Metadata.empty()), new StructField("features"newfalse, Metadata.empty()), new SQLContext(sc);DataFrame df = jsql.createDataFrame(jrow, schema);
Dataframe:dataframe is a distributed dataset that is organized as a named column. Conceptually, it is the same as a table in a relational database or a data frame in 1 python (or R), but more optimized than they are. Dataframe can be constructed from a structured data file, hive table, external database, or an existing rdd.
Sqlcontext:spark the entry for all functions of SQL is the SqlContext class, or the subclass of SqlContext. In order to create a basic sqlcontext, a sparkcontext is required.
Feature Extraction
Feature normalization processing
StandardScaler scaler = new StandardScaler().setInputCol("features").setOutputCol("normFeatures").setWithStd(true);DataFrame scalerDF = scaler.fit(df).transform(df);scaler.save(this.scalerModelPath);
Using Chi-square statistic to make feature extraction
Chisqselector selector = new Chisqselector (). Setnumtopfeatures( -). Setfeaturescol("Normfeatures"). Setlabelcol("Label"). Setoutputcol("Selectedfeatures");Chisqselectormodel Chimodel = Selector. Fit(SCALERDF);DataFrame SELECTEDDF = Chimodel. Transform(SCALERDF). Select("Label","Selectedfeatures");Chimodel. Save(This. Featureselectedmodelpath);
Training machine learning model (with SVM as an example)
//Convert to Labeledpoint data type, training modeljavardd<row> selectedrows = Selecteddf.javardd (); javardd<labeledpoint> trainset = Selectedrows.map (NewRowtolabel ());//Training the SVM model and savingintNumiteration = $; Svmmodel model = Svmwithsgd.train (Trainset.rdd (), numiteration); Model.clearthreshold (); Model.save (SC, This. Mlmodelpath);//Labeledpoint data type into rowStatic class labeledpointtorow implements Function<labeledpoint, Row> { PublicRow Call (Labeledpoint p) throws Exception {Doublelabel = P.label (); Vector vector = p.features ();returnRowfactory.create (label, Vector); } }convert//rows data type to LabeledpointStatic class Rowtolabel implements Function<Row, labeledpoint > { PublicLabeledpoint Call (Row R) throws Exception {Vector features = R.getas (1);DoubleLabel = R.getdouble (0);return NewLabeledpoint (label, features); } }
Test a new sample
Before testing a new sample, it is necessary to do the data conversion and feature extraction of the sample, all just training the model, in addition to preserving the machine learning model, also need to save the feature extraction of the intermediate model. The specific code is as follows:
//Initialize sparksparkconf conf =NewSparkconf (). Setappname ("SVM"). Setmaster ("Local"); Conf.Set("Spark.testing.memory","2147480000"); Sparkcontext sc =NewSparkcontext (conf);//Load test datajavardd<labeledpoint> testData = Mlutils.loadlibsvmfile (SC, This. Predictdatapath). Tojavardd ();//Conversion dataframe data typeJavardd<row> Jrow =testdata.map (NewLabeledpointtorow ()); Structtype schema =NewStructtype (Newstructfield[]{NewStructfield ("Label", Datatypes.doubletype,false, Metadata.empty ()),NewStructfield ("Features",NewVectorudt (),false, Metadata.empty ()),}); SqlContext Jsql =NewSqlContext (SC);D ataframe df = jsql.createdataframe (jrow, schema);//Data NormalizationStandardscaler Scaler = Standardscaler.load ( This. Scalermodelpath);D Ataframe SCALERDF = Scaler.fit (DF). Transform (DF);//Feature SelectionChisqselectormodel Chimodel = Chisqselectormodel.load ( This. Featureselectedmodelpath);D Ataframe selecteddf = Chimodel.transform (SCALERDF).Select("Label","Selectedfeatures");
Test Data Set
Svmmodel Svmmodel = Svmmodel.load (SC, This. Mlmodelpath); Javardd<tuple2<double, double>> predictresult = Testset.map (NewPrediction (Svmmodel));p redictresult.collect ();Static class prediction implements Function<labeledpoint, Tuple2 <double , double>> {Svmmodel model; PublicPrediction (Svmmodel model) { This. model = model; } PublicTuple2<double, double> Call (Labeledpoint p) throws Exception {Double score = model.predict (P.features ()) ;return NewTuple2<double, double> (Score, P.label ()); } }
Calculation accuracy Rate
Doubleaccuracy = Predictresult.filter (NewPredictandscore ()).Count() *1.0/Predictresult.Count(); SYSTEM.OUT.PRINTLN (accuracy);Static class predictandscore implements Function<Tuple2< Double, double;, Boolean> { PublicBoolean Call (tuple2<double, double> t) throws Exception {DoubleScore = T._1 ();Doublelabel = T._2 (); System.out.print ("Score:"+ score +", Label:"+ label);if(Score >=0.0&& label >=0.0)return true;Else if(Score <0.0&& Label <0.0)return true;Else return false; } }
Specific code, put on my github: https://github.com/Quincy1994/MachineLearning/
Mllib Learning Summary for Spark (Java edition)