This article mainly includes the following content:
1) Model Training Data Generation (demo)
2) model Training (spark+java), data stored in HDFs
3) Predictive Data Generation (demo)
4) use the resulting model for text Categorization.
first, Training Data Generation
There are usually two types of input data formats for the Spark Mllib model training, one called the LIBSVM format, as Follows:
Label Index1:value1 Index2:value2
Label is the category label, Indexx is the index of the eigenvector, and value is the value of the corresponding Dimension.
Another format style is as Follows:
Label f1,f2,f3,..., FN
FX for feature values
Two formats of files, respectively, can be by method:
Org.apache.spark.mllib.util.MLUtils.loadLibSVMFile
Org.apache.spark.mllib.util.MLUtils.loadLabeledData
Read.
We use the first format Here.
The data file for this format is now formally Generated. During the model training phase, data training is read directly from this File. I'll Talk about that Later.
We assume here that for the text, we have extracted the keyword as a feature. The list of features is as Follows:
features = [w1,w2,w3,..., wn]
At the same time, the Text's subject (category) set is:
topics = [t1,t2,... tm]
Then there are a lot of simple processing (participle, go to stop word, etc.) to get training data, the format of each line is probably as Follows:
T2 w1,w23,w34,w1,...
We directly take the word frequency as the value of the Feature. The following is a Python code that generates the LIBSVM format, for informational purposes only:
For info in result:sstr ="" topic_name = info[0]#主题名 content =STR (info[1]). Split ()#处理后的文本内容 (word List)index = Topics. index (channel_name) sstr + = str ( Index) features_val = "for i,word in enumerate (features): freq = Content. count (word) if freq:features_val + = "features_val + = str (i+1) + str (freq) if not Features_val:continue sstr + = Features_val #bayes_data. write (sstr+ "\ N") Print n n + = 1 hdfs_client.write_list (sstr_lst,bayes_data_path) #写到hdfs指定路径
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
This way, the training data is generated even if it is Completed.
second, Model Training
This is a simple step. There are examples from the Spark official web site, which can be used directly. Now post the slightly adjusted Java code:
PublicStaticvoidTraining (javasparkcontext Jsc) {String path ="data/libsvm_data.txt"; javardd<labeledpoint> inputdata = mlutils.loadlibsvmfile (jsc.sc (), path). tojavardd (); javardd<labeledpoint>[] tmp = Inputdata.randomsplit (Newdouble[]{0.6,0.4},12345); javardd<labeledpoint> training = tmp[0];Training set javardd<labeledpoint> test = tmp[1];Test setFinal Naivebayesmodel model = Naivebayes.train (training.rdd ()); javapairrdd<double, double> Predictionandlabel = Test.maptopair (New pairfunction<labeledpoint, Double, double> () {@Overridepublic tuple2<double, double> call (LabeledPoint p) {return new tuple2<double, double> (model.predict (p.features ( )), P.label ()); } }); double accuracy = predictionandlabel.filter (new Function< tuple2<double, double>, boolean> () { @Override Public Boolean call (tuple2<double, double> pl) {return Pl. _1 (). equals (pl._2 ()); }}). count ()/(double) test.count (); //system.out.println (accuracy); //Save and load model Model.save (jsc.sc (), target/tmp/ Naivebayesmodel "); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21st
- 22
- 23
- 24
- 25
How do I perform this task?
The complete code can be found on the spark project, or at the end of this article, with the added code, which is basically all.
Package (jar) the project where the code is located, such as packaged as Xx.jar.
Then execute the command:
Spark-submit–class "yourclass" –master Yarn Xx.jar
You can do it. packing, have already spark-submit command not to tell the details?
Model Training is completed, the evaluation results of the model can be printed (accuracy rate), and the model is saved to Hdfs. Note that the above two paths refer to the path on the Hdfs.
Iii. using models to classify text
The text data generation process that shows the classifications is not introduced. The same as model data Generation. Basically is to your article participle, and then converted to LIBSVM format files, put on Hdfs. The following code is categorized directly below:
PublicStaticvoidPredict (javasparkcontext jsc) {naivebayesmodel Samemodel = naivebayesmodel.load (jsc.sc (), "target/tmp/naivebayesmodel"); String Path = "/data/pred_data.txt"; javardd<string> Rdd = Jsc.textfile (path); for (String features:rdd.collect ()) {//system.out.println ( features); string[] feature_str_lst = features.split (double[] feature_lst = new double [feature_str_lst.length]; for (int i = 0;i<feature_str_ Lst.length;i++) {feature_lst[i] = double.parsedouble (feature_str_lst[i]);} System. out.println (samemodel.predict (vectors.dense (feature_lst)));} }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
After executing the results normally you will see the following output: (the box is the predicted Category)
Not yet, do you have a full demo?
The code main () method is also affixed to you:
public static void main(String[] args){ SparkConf sparkConf = new SparkConf().setAppName("JavaNaiveBayesExample"); JavaSparkContext jsc = new JavaSparkContext(sparkConf); //training(jsc); predict(jsc); }
All right. It's not easy to Tell. The implementation is simple, the algorithm principle is very simple. Be interested to study it YOURSELF.
Text classification based on naive Bayes (with full code (spark/java)