2013-02-21 2 views
2

마호트를 분류하여 분류하고 싶습니다. 나를 위해이 텍스트는 데이터베이스에서오고 있으며 나는 실제로 mahout 교육을 위해 파일에 저장하고 싶지 않습니다. MIA 소스 코드를 확인한 후 다음과 같은 코드를 매우 기본적인 교육 과제로 변경했습니다. mahout 예제의 일반적인 문제점은 20 개의 뉴스 그룹을 사용하는 cmd 프롬프트에서 mahout을 사용하는 방법을 보여 주거나 코드가 Hadoop Zookeeper 등에 많은 의존성이 있음을 나타냅니다. 누군가가 내 코드 또는 포인트를 볼 수 있다면 정말 감사 할 것입니다. 나에게 모델을 훈련시키고 그것을 사용하는 방법을 보여주는 아주 간단한 튜토리얼로 넘어 간다.단순한 마호 마트 분류 예

learningAlgorithm.getBest();이 항상 null을 반환하기 때문에 지금 다음 코드에서 나는 if (best != null)을 결코 지나치지 않고 있습니다!

전체 코드를 게시 죄송합니다

하지만 다른 옵션

public class Classifier { 

    private static final int FEATURES = 10000; 
    private static final TextValueEncoder encoder = new TextValueEncoder("body"); 
    private static final FeatureVectorEncoder bias = new ConstantValueEncoder("Intercept"); 
    private static final String[] LEAK_LABELS = {"none", "month-year", "day-month-year"}; 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws Exception { 
     int leakType = 0; 
     // TODO code application logic here 
     AdaptiveLogisticRegression learningAlgorithm = new AdaptiveLogisticRegression(20, FEATURES, new L1()); 
     Dictionary newsGroups = new Dictionary(); 
     //ModelDissector md = new ModelDissector(); 
     ListMultimap<String, String> noteBySection = LinkedListMultimap.create(); 
     noteBySection.put("good", "I love this product, the screen is a pleasure to work with and is a great choice for any business"); 
     noteBySection.put("good", "What a product!! Really amazing clarity and works pretty well"); 
     noteBySection.put("good", "This product has good battery life and is a little bit heavy but I like it"); 

     noteBySection.put("bad", "I am really bored with the same UI, this is their 5th version(or fourth or sixth, who knows) and it looks just like the first one"); 
     noteBySection.put("bad", "The phone is bulky and useless"); 
     noteBySection.put("bad", "I wish i had never bought this laptop. It died in the first year and now i am not able to return it"); 


     encoder.setProbes(2); 
     double step = 0; 
     int[] bumps = {1, 2, 5}; 
     double averageCorrect = 0; 
     double averageLL = 0; 
     int k = 0; 
     //------------------------------------- 
     //notes.keySet() 
     for (String key : noteBySection.keySet()) { 
      System.out.println(key); 
      List<String> notes = noteBySection.get(key); 
      for (Iterator<String> it = notes.iterator(); it.hasNext();) { 
       String note = it.next(); 


       int actual = newsGroups.intern(key); 
       Vector v = encodeFeatureVector(note); 
       learningAlgorithm.train(actual, v); 

       k++; 
       int bump = bumps[(int) Math.floor(step) % bumps.length]; 
       int scale = (int) Math.pow(10, Math.floor(step/bumps.length)); 
       State<AdaptiveLogisticRegression.Wrapper, CrossFoldLearner> best = learningAlgorithm.getBest(); 
       double maxBeta; 
       double nonZeros; 
       double positive; 
       double norm; 

       double lambda = 0; 
       double mu = 0; 
       if (best != null) { 
        CrossFoldLearner state = best.getPayload().getLearner(); 
        averageCorrect = state.percentCorrect(); 
        averageLL = state.logLikelihood(); 

        OnlineLogisticRegression model = state.getModels().get(0); 
        // finish off pending regularization 
        model.close(); 

        Matrix beta = model.getBeta(); 
        maxBeta = beta.aggregate(Functions.MAX, Functions.ABS); 
        nonZeros = beta.aggregate(Functions.PLUS, new DoubleFunction() { 

         @Override 
         public double apply(double v) { 
          return Math.abs(v) > 1.0e-6 ? 1 : 0; 
         } 
        }); 
        positive = beta.aggregate(Functions.PLUS, new DoubleFunction() { 

         @Override 
         public double apply(double v) { 
          return v > 0 ? 1 : 0; 
         } 
        }); 
        norm = beta.aggregate(Functions.PLUS, Functions.ABS); 

        lambda = learningAlgorithm.getBest().getMappedParams()[0]; 
        mu = learningAlgorithm.getBest().getMappedParams()[1]; 
       } else { 
        maxBeta = 0; 
        nonZeros = 0; 
        positive = 0; 
        norm = 0; 
       } 
       System.out.println(k % (bump * scale)); 
       if (k % (bump * scale) == 0) { 

        if (learningAlgorithm.getBest() != null) { 
         System.out.println("----------------------------"); 
         ModelSerializer.writeBinary("c:/tmp/news-group-" + k + ".model", 
           learningAlgorithm.getBest().getPayload().getLearner().getModels().get(0)); 
        } 

        step += 0.25; 
        System.out.printf("%.2f\t%.2f\t%.2f\t%.2f\t%.8g\t%.8g\t", maxBeta, nonZeros, positive, norm, lambda, mu); 
        System.out.printf("%d\t%.3f\t%.2f\t%s\n", 
          k, averageLL, averageCorrect * 100, LEAK_LABELS[leakType % 3]); 
       } 
      } 

     } 
     learningAlgorithm.close(); 
    } 

    private static Vector encodeFeatureVector(String text) { 
     encoder.addText(text.toLowerCase()); 
     //System.out.println(encoder.asString(text)); 
     Vector v = new RandomAccessSparseVector(FEATURES); 
     bias.addToVector((byte[]) null, 1, v); 
     encoder.flush(1, v); 
     return v; 
    } 
} 
보지 않았다
+0

제안 된 수정 사항으로 원본 코드 샘플을 업데이트 할 수 있습니까? 예를 적용하면 도움이됩니다. 감사. – Eugen

답변

2

당신의 아주 좋은 사람들에 질문을 직접 제안 귀하의 특징 벡터에 단어를 올바르게 추가해야합니다. 다음 코드와 같습니다 :

 bias.addToVector((byte[]) null, 1, v); 

기대하는 바가 없습니다. 단지 null 바이트를 가중치 1을 가진 특징 벡터에 추가합니다.

WordValueEncoder.addToVector(byte[] originalForm, double w, Vector data) 메소드에 대한 래퍼를 호출하고 있습니다.

메모 맵 값에서 단어 값을 반복해서 확인하고 그에 따라 피쳐 벡터에 추가하십시오.

0

오늘 나에게 이런 일이 일어났습니다. 내가 본 것처럼 코드를 가지고 노는 동안 초기 샘플이 거의 없다는 것을 알 수 있습니다. ,

learningAlgorithm.setInterval(1); 
learningAlgorithm.setAveragingWindow(1); 

이 방법 : 내 문제는이 알고리즘은 적응 알고리즘이기 때문에, 나는 그렇지 않으면 새로운 최고의 모델을 찾을 수 없을 것 같은 매우 낮은 것으로 "적응"에 대한 간격과 창을 설정하는 데 필요한 것이 었습니다 알고리즘은 예제 코드에 6 개의 벡터 만 있기 때문에 어떤 1 개의 벡터를 볼 때마다 "적응"하도록 강요받을 수 있습니다.