| [轉(zhuǎn)帖]在自己的算法中調(diào)用Weka實(shí)現(xiàn)文本分類的一個(gè)例子 
1 介紹:嵌入式機(jī)器學(xué)習(xí),在自己的算法中調(diào)用Weka現(xiàn)文本分類,是一個(gè)小的數(shù)據(jù)挖掘程序,雖然實(shí)用價(jià)值不是很大,但對于Weka的理解和使用是有幫助的。本例子來自《數(shù)據(jù)挖掘:實(shí)用機(jī)器學(xué)習(xí)技術(shù)》第2版(好像是倒數(shù)第三章)。大家可以到http:///blog/message.asp?name=DMman#23691 下載該書察看對算法的詳細(xì)解釋。算法中作了詳細(xì)的注釋,雖然是英文的,但還是比較簡單。下面對例子的使用作了淺顯的介紹,有興趣的朋友可以研究。 2 功能:使用weka中的j48分類器實(shí)現(xiàn)了文本分類的一個(gè)小程序。文本文件通過weka的過濾器StringToWordVector預(yù)處理。 3 注意:把weka.jar加入你的classpath中,才可以通過編譯。 4 使用方法:命令行參數(shù):
 -t 文本文件路徑
 -m 你的模型文件路徑
 -c 可選,類別(hit 或 miss)
 如果提供了-c則用于訓(xùn)練,否則被模型分類,輸出該文本的類型(hit或miss)
  模型是動(dòng)態(tài)建立的,第一次使用命令行必須指定-c參數(shù),才可以建立模型。1) 建立模型
 >java MessageClassifier -t data/1.bmp -m myModel -c hit
 可以看到myModel建立了。然后繼續(xù)訓(xùn)練一下這個(gè)模型。使用的文本實(shí)例越多,模型的分類性能越好
 >java MessageClassifier -t data/2.bmp -m myModel -c hit
 >java MessageClassifier -t data/1.gif -m myModel -c miss
 ......
 2) 使用模型分類
 有了模型,就可以使用它為文本文件分類了,如
 >java MessageClassifier -t data/2.gif -m myModel
 3) 可以使用提供-c參數(shù)的命令繼續(xù)完善模型
   原文件MessageClassifier .java 
 
    
        
            | /** * Java program for classifying text messages into two classes.
 */
 import weka.core.Attribute;
 import weka.core.Instance;
 import weka.core.Instances;
 import weka.core.FastVector;
 import weka.core.Utils;
 import weka.classifiers.Classifier;
 import weka.classifiers.trees.J48;
 import weka.filters.Filter;
 import weka.filters.unsupervised.attribute.StringToWordVector;
 import java.io.*;
 public class MessageClassifier implements Serializable {
 /* The training data gathered so far. */
 private Instances m_Data = null;
 /* The filter used to generate the word counts. */
 private StringToWordVector m_Filter = new StringToWordVector();
 /* The actual classifier. */
 private Classifier m_Classifier = new J48();
 /* Whether the model is up to date. */
 private boolean m_UpToDate;
 /**
 * Constructs empty training dataset.
 */
 public MessageClassifier() throws Exception {
 String nameOfDataset = "MessageClassificationProblem";
 // Create vector of attributes.
 FastVector attributes = new FastVector(2);
 // Add attribute for holding messages.
 attributes.addElement(new Attribute("Message", (FastVector)null));
 // Add class attribute.
 FastVector classValues = new FastVector(2);
 classValues.addElement("miss");
 classValues.addElement("hit");
 attributes.addElement(new Attribute("Class", classValues));
 // Create dataset with initial capacity of 100, and set index of class.
 m_Data = new Instances(nameOfDataset, attributes, 100);
 m_Data.setClassIndex(m_Data.numAttributes() - 1);
 }
 /**
 * Updates data using the given training message.
 */
 public void updateData(String message, String classValue) throws Exception {
 // Make message into instance.
 Instance instance = makeInstance(message, m_Data);
 // Set class value for instance.
 instance.setClassValue(classValue);
 // Add instance to training data.
 m_Data.add(instance);
 m_UpToDate = false;
 }
 /**
 * Classifies a given message.
 */
 public void classifyMessage(String message) throws Exception {
 // Check whether classifier has been built.
 if (m_Data.numInstances() == 0) {
 ////throw new Exception("No classifier available.");
 }
 // Check whether classifier and filter are up to date.
 if (!m_UpToDate) {
 // Initialize filter and tell it about the input format.
 m_Filter.setInputFormat(m_Data);
 // Generate word counts from the training data.
 Instances filteredData = Filter.useFilter(m_Data, m_Filter);
 // Rebuild classifier.
 m_Classifier.buildClassifier(filteredData);
 m_UpToDate = true;
 }
 // Make separate little test set so that message
 // does not get added to string attribute in m_Data.
 Instances testset = m_Data.stringFreeStructure();
 // Make message into test instance.
 Instance instance = makeInstance(message, testset);
 // Filter instance.
 m_Filter.input(instance);
 Instance filteredInstance = m_Filter.output();
 // Get index of predicted class value.
 double predicted = m_Classifier.classifyInstance(filteredInstance);
 // Output class value.
 System.err.println("Message classified as : " +
 m_Data.classAttribute().value((int)predicted));
 }
 /**
 * Method that converts a text message into an instance.
 */
 private Instance makeInstance(String text, Instances data) {
 // Create instance of length two.
 Instance instance = new Instance(2);
 // Set value for message attribute
 Attribute messageAtt = data.attribute("Message");
 instance.setValue(messageAtt, messageAtt.addStringValue(text));
 // Give instance access to attribute information from the dataset.
 instance.setDataset(data);
 return instance;
 }
 /**
 * Main method.
 */
 public static void main(String[] options) {
 try {
 // Read message file into string.
 String messageName = Utils.getOption('m', options);
 if (messageName.length() == 0) {
 throw new Exception("Must provide name of message file.");
 }
 FileReader m = new FileReader(messageName);
 StringBuffer message = new StringBuffer(); int l;
 while ((l = m.read()) != -1) {
 message.append((char)l);
 }
 m.close();
 // Check if class value is given.
 String classValue = Utils.getOption('c', options);
 // If model file exists, read it, otherwise create new one.
 String modelName = Utils.getOption('o', options);
 if (modelName.length() == 0) {
 throw new Exception("Must provide name of model file.");
 }
 MessageClassifier messageCl;
 try {
 ObjectInputStream modelInObjectFile =
 new ObjectInputStream(new FileInputStream(modelName));
 messageCl = (MessageClassifier) modelInObjectFile.readObject();
 modelInObjectFile.close();
 } catch (FileNotFoundException e) {
 messageCl = new MessageClassifier();
 }
 // Check if there are any options left
 Utils.checkForRemainingOptions(options);
 // Process message.
 if (classValue.length() != 0) {
 messageCl.updateData(message.toString(), classValue);
 } else {
 messageCl.classifyMessage(message.toString());
 }
 // Save message classifier object.
 ObjectOutputStream modelOutObjectFile =
 new ObjectOutputStream(new FileOutputStream(modelName));
 modelOutObjectFile.writeObject(messageCl);
 modelOutObjectFile.close();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 }
 |  下載源碼:
 
  點(diǎn)擊下載該文件 |