无法使用Java中的Weka访问ML分类的训练数据集

问题描述 投票:0回答:1

我正在尝试使用Java中的Weka(特别是Android Studio)对实例进行分类。最初,我从Desktop Weka GUI保存了一个模型,并尝试将其导入我的项目目录。如果我是正确的,这将无法工作,因为Weka JDK在PC上与Android不同。

现在我试图通过导入训练数据集来训练Android本身的模型(因为我看不到其他选项)。这是我遇到问题的地方。当我运行“Test.java”时,我收到此错误,说明我的源未指定指向第23行,我调用.loadDataset方法。 java.io.IOException:没有指定源但是,显然,我已经指定了一个路径。这是正确的道路吗? I.E.我不确定我做错了什么。我查看了其他示例/博客,但没有详细介绍。

我的最终目标:在android / java中训练模型,并使用weka开发的模型对android / java中的实例进行分类。

我的代码可以在以下链接中找到:

model generator.Java

package com.example.owner.introductoryapplication;

import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.logging.Level;
import java.util.logging.Logger;

import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.core.Instances;
import weka.core.SerializationHelper;
import weka.core.converters.ConverterUtils;

public class ModelGenerator
{
    //String trainingSetPath = "JavaTrainingSet.arff"; //com/example/owner/introductoryapplication/JavaTrainingSet.arff
    //String modelSavedPath = "com/example/owner/introductoryapplication/JavaTrainingSet.csv";

    //Loading dataset from ARFF file and save it to Instances object
    public Instances loadDataset(String path)
    {
        //Declaration and initialization of null training set
        Instances dataset = null;

        //Loading the dataset into the program
        try
        {
            //Read the dataset
            dataset = ConverterUtils.DataSource.read(path);
            if (dataset.classIndex() == -1) {
                dataset.setClassIndex(dataset.numAttributes() - 1);
            }
        } catch (Exception ex) {
            Logger.getLogger(ModelGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }

        return dataset;
    }

    //Building classifier for training set using MultilayerPerceptron (Neural network)
    public Classifier buildClassifier(Instances traindataset) {
        MultilayerPerceptron m = new MultilayerPerceptron();

        try {
            m.buildClassifier(traindataset);

        } catch (Exception ex) {
            Logger.getLogger(ModelGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
        return m;
    }

    //Evaluating the accuracy for the generated model with test set
    public String evaluateModel(Classifier model, Instances traindataset, Instances testdataset) {
        Evaluation eval = null;
        try {
            // Evaluate classifier with test dataset
            eval = new Evaluation(traindataset);
            eval.evaluateModel(model, testdataset);
        } catch (Exception ex) {
            Logger.getLogger(ModelGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
        return eval.toSummaryString("", true);
    }

    //Saving the generated model to a path to use it for future prediction
    public void saveModel(Classifier model, String modelpath) {
        try {
            SerializationHelper.write(modelpath, model);
        } catch (Exception ex) {
            Logger.getLogger(ModelGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

model classifier.Java

package com.example.owner.introductoryapplication;

import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import weka.classifiers.Classifier;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;
import weka.core.SerializationHelper;

public class ModelClassifier
{
    private Attribute Age;
    private Attribute Height;
    private Attribute Weight;
    private Attribute UPDRS;
    private Attribute TUAG;
    private Attribute Speed;
    private Attribute Gender;

    private ArrayList attributes;
    private ArrayList classVal;
    private Instances dataRaw;


    public ModelClassifier() {
        Age = new Attribute("Age");
        Height = new Attribute("Height");
        Weight = new Attribute("Weight");
        UPDRS = new Attribute("UPDRS");
        TUAG = new Attribute("TUAG");
        Speed = new Attribute("Speed");
        Gender = new Attribute("Gender");

        attributes = new ArrayList();
        classVal = new ArrayList();
        classVal.add("PD");
        classVal.add("CO");

        attributes.add(Age);
        attributes.add(Height);
        attributes.add(Weight);
        attributes.add(UPDRS);
        attributes.add(TUAG);
        attributes.add(Speed);
        attributes.add(Gender);

        attributes.add(new Attribute("class", classVal));
        dataRaw = new Instances("TestInstances", attributes, 0);
        dataRaw.setClassIndex(dataRaw.numAttributes() - 1);
    }


    public Instances createInstance(double Age, double Height, double Weight, double UPDRS, double TUAG, double Speed, double Gender, double result) {
        dataRaw.clear();
        double[] instanceValue1 = new double[]{Age, Height, 0};
        dataRaw.add(new DenseInstance(1.0, instanceValue1));
        return dataRaw;
    }


    public String classifiy(Instances insts, String path) {
        String result = "Not classified!!";
        Classifier cls = null;
        try {
            cls = (MultilayerPerceptron) SerializationHelper.read(path);
            result = (String) classVal.get((int) cls.classifyInstance(insts.firstInstance()));
        } catch (Exception ex) {
            Logger.getLogger(ModelClassifier.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }


    public Instances getInstance() {
        return dataRaw;
    }
}

test.Java

package com.example.owner.introductoryapplication;

import com.example.owner.introductoryapplication.ModelGenerator;
import com.example.owner.introductoryapplication.ModelClassifier;

import android.support.v7.app.AppCompatActivity;

import weka.classifiers.functions.MultilayerPerceptron;
import weka.core.Debug;
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Normalize;

public class Test
{
    String DATASETPATH = "com/example/owner/introductoryapplication/JavaTrainingSet.arff";
    String MODElPATH = "com/example/owner/introductoryapplication/model.bin";

    public static void main(String[] args) throws Exception {

        ModelGenerator mg = new ModelGenerator();

        Instances dataset = mg.loadDataset("/com/example/owner/introductoryapplication/JavaTrainingSet.arff");

        Filter filter = new Normalize();

        // divide dataset to train dataset 80% and test dataset 20%
        int trainSize = (int) Math.round(dataset.numInstances() * 0.8);
        int testSize = dataset.numInstances() - trainSize;

        dataset.randomize(new Debug.Random(1));// if you comment this line the accuracy of the model will be droped from 96.6% to 80%

        //Normalize dataset
        filter.setInputFormat(dataset);
        Instances datasetnor = Filter.useFilter(dataset, filter);

        Instances traindataset = new Instances(datasetnor, 0, trainSize);
        Instances testdataset = new Instances(datasetnor, trainSize, testSize);

        // build classifier with train dataset
        MultilayerPerceptron ann = (MultilayerPerceptron) mg.buildClassifier(traindataset);

        // Evaluate classifier with test dataset
        String evalsummary = mg.evaluateModel(ann, traindataset, testdataset);
        System.out.println("Evaluation: " + evalsummary);

        //Save model
        mg.saveModel(ann, "/com/example/owner/introductoryapplication/model.bin");

        //classifiy a single instance
        ModelClassifier cls = new ModelClassifier();
        String classname = cls.classifiy(Filter.useFilter(cls.createInstance(50, 20, 30, 14, 16, 10.42, 2, 0), filter), "/com/example/owner/introductoryapplication/model.bin");
        System.out.println("\n The class name for the instance is: " + classname);
        System.out.println("\n The class name for the instance is: " + classname);

    }
}

我的数据集现在的截图:Current Location of dataset

请在方便的时候告诉我。

java android machine-learning error-handling weka
1个回答
1
投票

详细而详细的答案位于this链接:

简而言之,您必须在res目录中创建一个原始文件夹。然后保存那里的任何文件。您将根据其资源ID访问这些文件。

© www.soinside.com 2019 - 2024. All rights reserved.