weka Exception ArrayIndexOutOfBoundsException:15 at weka.core.DenseInstance.value double pred = tree.classifyInstance(unlabeled.instance(i))

时间:2017-03-15 09:52:16

标签: java exception weka

我的程序中有一个例外 我在netbeans中使用weka,我从Mysql获得我的训练和测试数据 我的连接中没有任何问题,我的属性名称和位置在taining和测试中都是相同的。

我搜索了很多退出此例外情况,我没有找到任何可用的解决方案:(

帮帮我PLZ。

这是我的代码:

public class RandomForestModel {

    public static void main(String[] args) throws Exception {
        InstanceQuery query = new InstanceQuery();
        query.setUsername("root");
        query.setPassword("");
        query.setQuery("SELECT * FROM dataset.dataset");
        Instances inst = query.retrieveInstances();
        inst.setClassIndex(inst.numAttributes() - 1);

        RandomForest tree = new RandomForest(); // new instance of tree
        tree.buildClassifier(inst); // build classifier

        // evaluate classifier and print some statistics
        Evaluation eval = new Evaluation(inst);
        eval.crossValidateModel(tree, inst, 10, new Random(1)); // Cross-validation
        System.out.println(eval.toSummaryString("\nResults\n======\n", false));

        /* Gets Testdata from DB */

        InstanceQuery Test = new InstanceQuery();
        // Test.setDatabaseURL("jdbc:mysql://127.0.0.1:3306/dataset");
        Test.setUsername("root");
        Test.setPassword("");
        Test.setQuery("SELECT HaveAutisticChild FROM dataset.testingdata"); // Read
                                                                            // table
        Instances unlabeled = Test.retrieveInstances(); // into data
        // set class attribute
        unlabeled.setClassIndex(unlabeled.numAttributes() - 1);

        // create copy
        Instances labeled = new Instances(unlabeled);
        // label instances
        for (int i = 0; i < unlabeled.numInstances(); i++) {
            double pred = tree.classifyInstance(unlabeled.instance(i));
            labeled.instance(i).setClassValue(pred);

            // print class label
            System.out.println(pred + " -> "
                    + unlabeled.classAttribute().value((int) pred));
        }

    }
}

我在第117行遇到了这个错误:(

ll7:      double pred = tree.classifyInstance(unlabeled.instance(i));

例外:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
    at weka.core.DenseInstance.value(DenseInstance.java:347)
    at weka.core.AbstractInstance.isMissing(AbstractInstance.java:319)
    at weka.classifiers.trees.RandomTree$Tree.distributionForInstance(RandomTree.java:950)
    at weka.classifiers.trees.RandomTree.distributionForInstance(RandomTree.java:728)
    at weka.classifiers.meta.Bagging.distributionForInstance(Bagging.java:814)
    at weka.classifiers.AbstractClassifier.classifyInstance(AbstractClassifier.java:173)
    at RandomForestModel.main(RandomForestModel.java:117)

这是我在arff文件中的数据,但我使用的是相同数据的Mysql版本 培训

@relation LastVerData

@attribute MAgeAtConception {Young,Middle_aged,Senior}
@attribute FAgeAtConception {Young,Senior,Middle_aged}
@attribute MOccupationalStatus {House-wife,Employee,Retired}
@attribute MNatureOfWorking {None,Exposed-to-chemicals,Exposed-to-radiation}
@attribute KinshipBetweenCouples {No-relationship,Distant-relative,First-Cousin}
@attribute FamilyHousingNear {None,Main-street,Chemical-Factory,Plastic-Factory,Oil-Refinery}
@attribute FSmoking {Non-smoker,Shisha,Smokes,Electronic-cigarettes,Hasheesh,Shammah}
@attribute FHealthStatus {Healthy,Obesity,Food_Allergies,Kidney_problems,Epilepsy,Hypertension,Asthma,Heart_problems,Diabetes,Arthritis,Liver_problems,Migraine,Anemia,Lupus}
@attribute MHealthStatus {Anemia,Obesity,Healthy,Asthma,Liver_problems,Heart_problems,Epilepsy,Food_Allergies,Hypertension,Migraine,Diabetes,Kidney_problems,Arthritis}
@attribute HaveLanguageDelayChild {No,Yes}
@attribute HaveOveractiveChild {No,Yes}
@attribute HaveDistractedChild {No,Yes}
@attribute PlanningforPregnancy {Yes,No}
@attribute UseNaturHerbsBefPreg {No,Indian-Installment,Marjoram,Cumin,Rashad,Rosemary,Miramiah,Khawajoa,Madina-Herb,Green-tea,Yansoon,Cinnamon,Shammar,Helbah,Mint,Saffron,ladys-mantle,Zaatar,Amlaj,Murr,Herbs-Weight-Loss,Chamomile}
@attribute MVaccinBefPreg {No,Measles,Seasonal_Flu,Hepatitis_B_virus,Needle-bombing-egg,Hajj_Vaccination,Corticosterone,Tetanus}
@attribute TakeMedicineBefPreg {No,Anemia-Therapy,Thyroxine,Antidepressants,F,Psychological-Therapies,Contraceptive,Antibiotic,Diabetes_Therapy,Fertilization,PCOS,Painkiller,Dostinex,Aspirin,Colon_Therapy,Asthma-Therapy,Duphaston,Regulate-Menstruation,C_V-D,'Cod- liver-oil',Cypro-Vita,Hormonal-Therapy-Progesterone,Vaginitis-Therapy,Anti-inflammatory,Hair-Vitamins,Roaccutane,Triple-Fat-Therapy,Cholesterol,Antipyretic,Breast-feeding-Therapy,Gestagens}
@attribute PregCondition {Normal,By_dope_pregnancy,After_frequent_miscarriages,IVF,Artificial_Iinsemination}
@attribute ShortPI {Yes,No}
@attribute MSmokedDurPreg {Non-Smoker,Smokes,Shisha}
@attribute MEmotionalStatusDurPreg {Regular,Happiness,Unhappiness}
@attribute AvgUseMobilDurPreg {More-than-Four-hour,Half-to-hour,Less-than-Half-hour,Two-to-four-hour,one-to-Two-hour}
@attribute MHealttStatusDurPreg {Healthy,Iron_Deficiency,Intestinal_Catarrh,Seasonal_flu,Dryness,Herpes,'Eye virus',Skin_Allergy,Infections_in_urine,Allergy,Chickenpox,Bacteria_in_blood,Kidney_Problems,Peptic_Ulcer,Facial_Palsy,Hepatitis,Cholecystitis,'Hard breathing',Anemia,Tonsillitis,Average_Bleeding,Diabetes_Pregnancy,Pus_in_the_urine,'Deficiencies_in_the _placenta',Appendix,Colon,Hypertension,Albumin,Meningitis}
@attribute UseNaturHerbDurPreg {No,Miramiah,Marjoram,Green-tea,Murr,Cumin,Yansoon,Chamomile,Angelica,Mint,Cinnamon,Shammar,Zaatar,Helbah,Rashad,Rosemary}
@attribute TakeSuppDurPreg {F,None,V-D,F_C,I,C_I,F_I,Pregrancy-multivitamin,C,Vitamin-C,F_C_I_V-D,F_C_I,'Cod- liver-oil',F_C_V-D,F_I_V-D,F_V-D,I_V-D}
@attribute TakeMedicDurPreg {No,Thyroxine,Revitalization,Antibiotic,Gestagens,Painkiller,Antipyretic,Antihistamine,Corticosterone,Hypertension,Diabetes_therapy,Aspirin,Gallstones_therapy,Chickenpox_Therapy,Anemia-Therapy,Contraceptive,Epilepsy_Therapy,Abdominal_Colic_Therapy,Colon_Therapy,Progesterone,Antibiotic_Vaginitis,Flu_Therapy,Fizzing_Vaginitis,Antiacide,Regulate_Menstruation,Asthma_Therapy,Drop_Nasal_Congestion,Diabetes_Therapy,Swine_Flu_Therapy,Blood-thinners,Anti-inflammatory,Constipation_Therapy,Appendix_Therapy,Acidity_Therapy,Anti-congestionandAllergies,catch-cold_Therapy,Dostinex}
@attribute MVaccinDurPreg {No,Seasonal_Flu,Hajj_Vaccination,Measles,Tetanus,Oxygen_needle_for_fetus,Fetus_food_deliveries_needle,Needle_for_prevention_of_poisoning,Corticosterone,Gestagens,AB_negative_blood,Needle_for_deformation_of_fetus_intestines,Meningitis,For_Complete_fetal_lung,Hepatitis}
@attribute AccidentDurPreg {No,Falling,Sliding,Car_Accident,Hitting}
@attribute BirthTime {On_Time,Postponed_labor,Premature_birth}
@attribute ObstructedLabour {No,Yes}
@attribute DeliveryMethod {Natural_Childbirth,Natural_Childbirth_with_induce_labour_Intravenously,'Cesarean section','Natural_Childbirth_with_induce_labour_Vaginal suppositories'}
@attribute PeriodOfBF {BottleOnly,'Less_than_3 _Month',6_to_12_Month,3_to_6_Month,12_to_18_Month,18_to_24_Month,36_Month}
@attribute HaveAutisticChild {No,Yes}

@data
Young,Young,House-wife,None,...............,Yes

测试

@relation TestingData

@attribute MAgeAtConception {Young,Middle_aged}
@attribute FAgeAtConception {Young,Middle_aged}
@attribute MOccupationalStatus {House-wife,Employee}
@attribute MNatureOfWorking {None}
@attribute KinshipBetweenCouples {Distant-relative,First-Cousin,No-relationship}
@attribute FamilyHousingNear {None,Main-street}
@attribute FSmoking {Non-smoker,Smokes,Shisha,Haseesh}
@attribute FHealthStatus {Healthy,Epilepsy,Obesity,Asthma,Hypertension,Food_Allergies}
@attribute MHealthStatus {Healthy,Obesity,Anemia,Arthritis,Epilepsy,Hypertension}
@attribute HaveLanguageDelayChild {No,Yes}
@attribute HaveOveractiveChild {Yes,No}
@attribute HaveDistractedChild {No,Yes}
@attribute PlanningforPregnancy {No,Yes}
@attribute UseNaturHerbsBefPreg {No,Miramah}
@attribute MVaccinBefPreg {No,Seasonal_Flu}
@attribute TakeMedicineBefPreg {No,Fertilization,Psoriasis_Therapy,Arthritis_Therapy}
@attribute PregCondition {Normal,By_dope_pregnancy}
@attribute ShortPI {No,Yes}
@attribute MSmokedDurPreg {Non-smoker,Smokes}
@attribute MEmotionalStatusDurPreg {Happiness,Unhappiness,Regular}
@attribute AvgUseMobilDurPreg {Less-than-Half-hour,Half-to-hour,one-to-Two-hour,Two-to-four-hour,More-than-Four-hour}
@attribute MHealttStatusDurPreg {Healthy,Seasonal_Flu,Instestinal_Catarrh}
@attribute UseNaturHerbDurPreg {No}
@attribute TakeSuppDurPreg {None,F,F_I,F_I_V-D,I,F_V-D}
@attribute TakeMedicDurPreg {No,Painkiller,Diclofenac,Gestagens,Insulin}
@attribute MVaccinDurPreg {No,Tetanus}
@attribute AccidentDurPreg {No,Falling}
@attribute BirthTime {On_Time,Postponed_labor,Premature_birth}
@attribute ObstructedLabour {No,Yes}
@attribute DeliveryMethod {Natural_Childbirth,Natural_Childbirth_with_induce_labour_Intravenously,'Natural_Childbirth_with_induce_labour_Vaginal suppositories','Cesarean section'}
@attribute PeriodOfBF {3_to_6_Month,'Less_than_3 _Month',12_to_18_Month,BottleOnly,18_to_24_Month,6_to_12_Month}
@attribute HaveAutisticChild {Yes, No}

@data
Young,....,?

从Mysql测试数据 enter image description here

另一个问题,我如何定义从Mysql测试数据的类? 在arff我认为它更容易! 属性及其值存在于文件的末尾,如此

@attribute HaveAutisticChild {Yes, No}
@asettouf说:你没有忘记添加tree.buildClassifier(未标记);

我添加了此语句,并在“main”weka.core.UnsupportedAttributeTypeException: weka.classifiers.trees.RandomTree: Cannot handle unary class!

主题中将错误更改为Exception

0 个答案:

没有答案