簡體   English   中英

使用Eclipse IDE在Java中實現ID3算法。 但是表現出錯誤

[英]implementation of ID3 algorithm in java using Eclipse IDE. But showingerror

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import ca.pfv.spmf.algorithms.classifiers.decisiontree.id3.AlgoID3;
import ca.pfv.spmf.algorithms.classifiers.decisiontree.id3.DecisionTree;

public class MainTestID3 {

    public static void main(String [] arg) throws IOException{
        // Read input file and run algorithm to create a decision tree
        AlgoID3 algo = new AlgoID3();
        // There is three parameters:
        // - a file path
        // - the "target attribute that should be used to create the decision tree
        // - the separator that was used in the file to separate values (by default it is a space)
        DecisionTree tree = algo.runAlgorithm(fileToPath("id3.txt"), "result", " ");
        algo.printStatistics();

        // print the decision tree:
        tree.print();

        // Use the decision tree to make predictions
        // For example, we want to predict the class of an instance:
        String [] instance = {null, "T_M", "P_M", "C_M", "F_M", "H_M", "N_M", "I_M"};
        String prediction = tree.predictTargetAttributeValue(instance);
        System.out.println("The class that is predicted you can play: " + prediction);
    }

    public static String fileToPath(String filename) throws UnsupportedEncodingException{
        URL url = MainTestID3.class.getResource(filename);
         return java.net.URLDecoder.decode(url.getPath(),"UTF-8");
    }
}

這是顯示的錯誤:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0  at ca.pfv.spmf.algorithms.classifiers.decisiontree.id3.AlgoID3.runAlgorithm(AlgoID3.java:88)    at ca.pfv.spmf.test.M

看一下ID3代碼,看起來目標屬性在文件中或在對runAlgorithm()的調用中可能拼寫不正確。 id3.txt的第一行應在id3.txt包含"result"

您遇到的錯誤來自以下行中的AlgoID3.java

 remainingAttributes[pos++] = i; 

在這段代碼中:

  allAttributes = line.split(separator); // make an array to store the attributes except the target attribute int[] remainingAttributes = new int[allAttributes.length - 1]; int pos = 0; // for each attribute for (int i = 0; i < allAttributes.length; i++) { // if it is the target attribute if (allAttributes[i].equals(targetAttribute)) { // save the position of the target attribute. It will be useful // later. indexTargetAttribute = i; } else { // otherwise add the attribute to the array of attributes remainingAttributes[pos++] = i; } } 

targetAttribute情況下, targetAttribute應該是“結果”。 如果未找到匹配項,則由於remainingAttribute屬性數組的長度為(allAttributes-1),因此將獲得ArrayIndexOutOfBoundException ...

當然,代碼可以檢查這一點並引發顯式異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM