mahout决策树之Partial Implementation源码分析 part4

今天来说,应该是把所有Partial Implementation的内容分析完了(当然也只是分析了属性是离散值的情况的数据,而非离散的并没有分析),下面就说下Partial Implementation实战的第三部分:TestForest,这个源文件在$MAHOUT_HOME/example/src/main/java/org/apache/mahout/classifier/df/mapreduce里面,打开源码可以看到:

TestForest里面的主要操作如下:

1.设置参数,直接调用 testForest()方法,在testForest()方法中首先确认(1)输出路径不存在;(2)确认forestt存在;(3)确认data存在;

// make sure the output file does not exist
    if (outputPath != null) {
      outFS = outputPath.getFileSystem(getConf());
      if (outFS.exists(outputPath)) {
        throw new IllegalArgumentException("Output path already exists");
      }
    }
    // make sure the decision forest exists
    FileSystem mfs = modelPath.getFileSystem(getConf());
    if (!mfs.exists(modelPath)) {
      throw new IllegalArgumentException("The forest path does not exist");
    }
    // make sure the test data exists
    dataFS = dataPath.getFileSystem(getConf());
    if (!dataFS.exists(dataPath)) {
      throw new IllegalArgumentException("The Test data path does not exist");
    }
2.一般都是使用mapreduce方法,而非单机,所以直接调用mapreduce()方法,mapreduce()方法如下

定义了Classifier 类,然后直接执行其run()方法:

Classifier classifier = new Classifier(modelPath, dataPath, datasetPath, outputPath, getConf());

classifier.run();
3. 打开Classifier源文件,可以看到这个类定义了一个Job,其Mapper为CMapper(属于Classifier的静态内部类),Cmapper的setup() 方法主要是进行一些参数的设定工作,map()方法如下:

3.1 首先获得 数据转换 ,即把Text的输入转为Instance:

Instance instance = converter.convert(line);
3.2 直接调用forest.classify()方法进行对instance的分类:

double prediction = forest.classify(dataset, rng, instance);

3.2.1forest的classify方法是去遍历我们得到的全部的tree,然后每棵树都会有一个预测的分类结果,把这些全部加起来,取次数最多的分类结果

 int[] predictions = new int[dataset.nblabels()];
      for (Node tree : trees) {
        double prediction = tree.classify(instance);
        if (prediction != -1) {
          predictions[(int) prediction]++;
        }
      }
  
 return DataUtils.maxindex(rng, predictions);

3.2.2每一个分类结果都会查询到叶子节点,叶子节点即Leaf直接返回该节点的label值:

public double classify(Instance instance) {
    return label;
  }
3.3 把原始已知的分类结果设置为key,把预测的分类结果设置为value进行输出:

lkey.set(dataset.getLabel(instance));
lvalue.set(Double.toString(prediction));
context.write(lkey, lvalue);
4. 接着Classifier把mapper的输出结果复制到输出路径,并删除Mapper的输出结果;
parseOutput(job);

HadoopUtil.delete(conf, mappersOutputPath);


分享,快乐,成长


转载请注明出处:http://blog.csdn.net/fansy1990


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值