I am trying to copy the first attribute of my training dataset, and copy the corresponding from Test set for book-keeping purpose. My code compiles successfully. But I am not able to run it.
I get the following errorwhen run java WekaRF
Exception in thread "main" java.lang.NoClassDefFoundError: weka/core/converters/CSVLoader
at WekaRF.main(WekaRF.java:17)
Caused by: java.lang.ClassNotFoundException: weka.core.converters.CSVLoader
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
If I run, java -cp weka-3-8-1/weka.jar WekaRF, I get
Error: Could not find or load main class WekaRF
My code is given below
import java.io.*;
import java.util.Random;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.RandomForest;
import weka.core.Instances;
import weka.filters.unsupervised.attribute.Remove;
import weka.core.converters.*;
public class WekaRF {
public static void main(String[] args) {
int percent = 60;
Instances data = null;
try {
CSVLoader loader = new CSVLoader();
loader.setSource(new File("../../rf.csv"));
data = loader.getDataSet();
} catch (Exception e) {
e.printStackTrace();
return;
}
int TrainSize = (int) Math.round(data.numInstances() * percent/ 100);
int TestSize = data.numInstances() - TrainSize;
Instances Train = new Instances(data, 0, TrainSize);
Instances Test = new Instances(data, TrainSize, TestSize);
System.out.println(Test.attribute(0).name());
Remove remove = new Remove();
String[] options = new String[2];
options[0] = "-R";
options[1] = "1";
remove.setOptions(options);
remove.setInputFormat(data2);
Test = Filter.useFilter(Test, remove);
Train.setClassIndex(Train.numAttributes() - 1);
}
}
Your classpath does not include current directory so java didn't see your WekaRF class.
Try to use java -cp .;weka-3-8-1/weka.jar WekaRF instead.
Notice dot at the start of -cp argument. It denotes current directory.
Upd: Character used to separate individual class path entries is operation system-depended. Windows uses ; and most other systems use :. The actual path separator can be retrieved by querying java.io.File::pathSeparator field.
Related
I want to do some work with weka in java. I've added the weka-src.jar and the weka-dev-3.7.10 jar in the java build path and my code doesn't show any error before running it. After I run the code it gives me the following error
Error: Unable to initialize main class selection.ClustererExecution
Caused by: java.lang.NoClassDefFoundError: weka/filters/Filter
Here is my code:
package selection;
import weka.clusterers.ClusterEvaluation;
import weka.clusterers.SimpleKMeans;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.*;
import weka.filters.unsupervised.attribute.Remove;
public class ClustererExecution {
public static void main(String[] args) {
try {
//Loading data
Instances data = DataSource.read("/Data_Cortex_Nuclear.arff");
System.out.println("The number of attributes is: " + data.numAttributes() + " while the number of instances is: " + data.numInstances());
data.setClassIndex(data.numAttributes()-1);
System.out.println("The class index is: " + data.classIndex());
//Create copy without class attribute
Remove rem = new Remove();
rem.setAttributeIndices("" + (data.classIndex() + 1));
rem.setInputFormat(data);
Instances dataClusterer = Filter.useFilter(data, rem);
//Build clusterer
SimpleKMeans clusterer = new SimpleKMeans();
clusterer.setMaxIterations(100);
clusterer.setNumClusters(8);
clusterer.buildClusterer(dataClusterer);
//Evaluate clusterer with original data
ClusterEvaluation eval = new ClusterEvaluation();
eval.setClusterer(clusterer);
eval.evaluateClusterer(data);
System.out.println(eval.clusterResultsToString());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Does anyone know how to fix the error?I am using eclipse if that makes any difference. Thank you!
As said in the comments below by Zastai, you added the weka jars to the build path, but the relevant weka jar needs to be in the classpath as well.
Hi everyone tried different ways to run a groovy in java with no luck, had read some documentation but things aren't that clear at the moment.
Anyone may know how to run this groovy?
package com.test.dev.search;
public class SearchQueryBase implements SearchQuery {
public QueryString getMatterQuery( SearchFilter filter ) {
String[] terms = filter.getSearchTerm().toLowerCase().split( " " );
...
...
...
}
}
This is a .groovy file (the one from above), I've tried the follow to run it without luck.
Down here is the Java class in which I want to run the above Groovy and execute getMatterQuery() to see the output from java main.
public static void main(String args[]) throws CGException {
String TEMPLATE_PACKAGE_PREFIX = "<path_to_groovy_file.";
String templateFileName = TEMPLATE_PACKAGE_PREFIX + "SearchQueryBase";
SearchFilter test = null;
Binding binding = new Binding();
binding.setVariable("filter", test);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate(templateFileName);
System.out.println("Finish");
}
EDIT #1
This is the error I'm getting when I run it;
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: Common for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
1.
the GroovyShell.evaluate(java.lang.String scriptText) accepts string as a groovy text (content), and you try to call it with filename instead. use shell.evaluate( new File(templateFileName) )
2.
you can continue using shell.evaluate( new File(...) ) but keep in your groovy file only content of the method getMatterQuery():
String[] terms = filter.getSearchTerm().toLowerCase().split( " " );
...
...
...
so you'll have groovy script, and your code should work
3.
if you want to keep groovy as a class and call the method getMatterQuery() from this class with parameter, then your java code should be like this:
import groovy.lang.*;
...
public static void main(String[]s)throws Exception{
GroovyClassLoader cl=new GroovyClassLoader();
//path to base folder where groovy classes located
cl.addClasspath(path_to_groovy_root);
//the groovy file with SearchQueryBase.groovy
//must be located in "com/test/dev/search" subfolder under path_to_groovy_root
Class c = cl.loadClass("com.test.dev.search.SearchQueryBase");
SearchQuery o = (SearchQuery) c.newInstance();
System.out.println( o.getMatterQuery(test) );
}
I'm trying to install the JWKTL library into a Java project.
JWKTL Getting started
Now I downloaded the dump file as described, and parsed it into a new directory.
My code is:
package main;
import java.io.File;
import java.util.List;
import de.tudarmstadt.ukp.jwktl.JWKTL;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEdition;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEntry;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryPage;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryRelation;
import de.tudarmstadt.ukp.jwktl.api.PartOfSpeech;
import de.tudarmstadt.ukp.jwktl.api.RelationType;
public class Main {
final static String PATH_TO_DUMP_FILE = "/GetWords/enwiktionary-20160601-pages-articles-multistream.xml";
final static String TARGET_DIRECTORY = "/GetWords/";
final static boolean OVERWRITE_EXISTING_FILES = true;
/**
* Simple example which parses an English dump file and prints the entries for the word <i>Wiktionary</i>
* #param args name of the dump file, output directory for parsed data, ISO language code of the Wiktionary entry language (en/de), boolean value that specifies if existing parsed data should be deleted
*/
public static void main(String[] args) throws Exception {
File dumpFile = new File(PATH_TO_DUMP_FILE);
File outputDirectory = new File(TARGET_DIRECTORY);
boolean overwriteExisting = OVERWRITE_EXISTING_FILES;
JWKTL.parseWiktionaryDump(dumpFile, outputDirectory, overwriteExisting);
IWiktionaryEdition wkt = JWKTL.openEdition(TARGET_DIRECTORY);
//TODO: Query the data you need.
// Close the database connection.
wkt.close();
}
}
But the line: IWiktionaryEdition wkt = JWKTL.openEdition(TARGET_DIRECTORY); throws an error: The method openEdition(File) in the type JWKTL is not applicable for the arguments (String), when I try to enter the dump_file as
java.io.File
the program throws the following error:
Exception in thread "main" de.tudarmstadt.ukp.jwktl.api.WiktionaryException: Unable to establish a db connection
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.<init>(BerkeleyDBWiktionaryEdition.java:228)
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.<init>(BerkeleyDBWiktionaryEdition.java:205)
at de.tudarmstadt.ukp.jwktl.JWKTL.openEdition(JWKTL.java:98)
at de.tudarmstadt.ukp.jwktl.JWKTL.openEdition(JWKTL.java:89)
at main.Main.main(Main.java:31)
Caused by: java.lang.IllegalArgumentException: Malformed \uxxxx encoding.
at java.util.Properties.loadConvert(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at com.sleepycat.je.dbi.DbConfigManager.applyFileConfig(DbConfigManager.java:388)
at com.sleepycat.je.Environment.setupHandleConfig(Environment.java:323)
at com.sleepycat.je.Environment.<init>(Environment.java:260)
at com.sleepycat.je.Environment.<init>(Environment.java:212)
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.connect(BerkeleyDBWiktionaryEdition.java:241)
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.<init>(BerkeleyDBWiktionaryEdition.java:224)
... 4 more
Does anybody know how to fix this?
I use Java 8 in Eclipse Mars.
I installed these libs:
jwktl-1.0.1.jar
je-6.4.25.jar
apache-ant-1.8.2.jar
Thank you!
I solved it...
It was too simple:
The sulution is:
File f = new File(TARGET_DIRECTORY);
IWiktionaryEdition wkt = JWKTL.openEdition(f);
Best regards!
This is my program code and it give the errors mentioned at the end of the document, when i run the program. FYI, no compilation errors occur.
Program
package javaapplication3;
/**
*
* #author ashish
*/
import org.neuroph.core.*;
import org.neuroph.core.data.DataSet;
import org.neuroph.core.data.DataSetRow;
import org.neuroph.nnet.*;
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// create new perceptron network
NeuralNetwork neuralNetwork = new Perceptron(2, 1);
// create training set
DataSet trainingSet =
new DataSet(2, 1);
// add training data to training set (logical OR function)
trainingSet. addRow (new DataSetRow (new double[]{0, 0},new double[{0}));
trainingSet. addRow (new DataSetRow (new double[]{0, 1},new double[{1}));
trainingSet. addRow (new DataSetRow (new double[]{1, 0},new double[{1}));
trainingSet. addRow (new DataSetRow (new double[]{1, 1},new double[{1}));
// learn the training set
neuralNetwork.learn(trainingSet);
// save the trained network into file
neuralNetwork.save("or_perceptron.nnet");
/*// load the saved network
NeuralNetwork neuralNetwork =
NeuralNetwork.createFromFile(“or_perceptron.nnet”);
// set network input
neuralNetwork.setInput(1, 1);
// calculate network
neuralNetwork.calculate();
// get network output
double[] networkOutput = neuralNetwork.getOutput();
*/ }
}
Error This is the runtime error which i cannot solve. I tried slf4j folder by adding it to the libraries but that didnt work also. Please help me.
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.neuroph.core.learning.LearningRule.<init>(LearningRule.java:65)
at org.neuroph.core.learning.IterativeLearning.<init>(IterativeLearning.java:72)
at org.neuroph.core.learning.SupervisedLearning.<init>(SupervisedLearning.java:82)
at org.neuroph.nnet.learning.LMS.<init>(LMS.java:44)
at org.neuroph.nnet.learning.PerceptronLearning.<init>(PerceptronLearning.java:40)
at org.neuroph.nnet.learning.BinaryDeltaRule.<init>(BinaryDeltaRule.java:48)
at org.neuroph.nnet.Perceptron.createNetwork(Perceptron.java:114)
at org.neuroph.nnet.Perceptron.<init>(Perceptron.java:56)
at javaapplication3.JavaApplication3.main(JavaApplication3.java:24)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 9 more
C:\Users\ashish\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
You should add the path to slf4j jar (or folder that contains .class files) to the classpath.
See here how: http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
I said in this question that I had some problem loading ptx modules in JCuda and after #talonmies's idea, I implemented a JCuda version of his solution to load multiple ptx files and load them as a single module. Here is the related part of the code:
import static jcuda.driver.JCudaDriver.cuLinkAddFile;
import static jcuda.driver.JCudaDriver.cuLinkComplete;
import static jcuda.driver.JCudaDriver.cuLinkCreate;
import static jcuda.driver.JCudaDriver.cuLinkDestroy;
import static jcuda.driver.JCudaDriver.cuModuleGetFunction;
import static jcuda.driver.JCudaDriver.cuModuleLoadData;
import jcuda.driver.CUjitInputType;
import jcuda.driver.JITOptions;
import jcuda.driver.CUlinkState;
import jcuda.driver.CUfunction;
public class JCudaTestJIT{
private CUmodule module;
private CUfunction functionKernel;
public void prepareModule(){
String ptxFileName4 = "file4.ptx";
String ptxFileName3 = "file3.ptx";
String ptxFileName2 = "file2.ptx";
String ptxFileName1 = "file1.ptx";
CUlinkState linkState = new CUlinkState();
JITOptions jitOptions = new JITOptions();
cuLinkCreate(jitOptions, linkState);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName4, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName3, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName2, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName1, jitOptions);
long sizeOut = 32768;
byte[] image = new byte[32768];
Pointer cubinOut = Pointer.to(image);
cuLinkComplete(linkState, cubinOut, (new long[]{sizeOut}));
module = new CUmodule();
// Load the module from the image buffer
cuModuleLoadData(module, cubinOut.getByteBuffer(0, 32768).array());
cuLinkDestroy(linkState);
functionKernel = new CUfunction();
cuModuleGetFunction(functionKernel, module, "kernel");
}
// Other methods
}
But I got the error of CUDA_ERROR_INVALID_IMAGE at calling cuModuleLoadData method. While debugging it, I saw that after calling cuLinkComplete method and pass the image array as the output, the array is still unchanged and clear. Am I passing the output parameter correctly? Is this how one can pass a variable by reference in JCuda?
I had never written a single line of Java code until 30 minutes ago, let alone used JCUDA before, but an almost literal line-by-line translation of the native C++ code I gave you here seems to work perfectly:
import static jcuda.driver.JCudaDriver.*;
import java.io.*;
import jcuda.*;
import jcuda.driver.*;
public class JCudaRuntimeTest
{
public static void main(String args[])
{
JCudaDriver.setExceptionsEnabled(true);
cuInit(0);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
CUlinkState linkState = new CUlinkState();
JITOptions jitOptions = new JITOptions();
cuLinkCreate(jitOptions, linkState);
String ptxFileName2 = "test_function.ptx";
String ptxFileName1 = "test_kernel.ptx";
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName2, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName1, jitOptions);
long sz[] = new long[1];
Pointer image = new Pointer();
cuLinkComplete(linkState, image, sz);
System.out.println("Pointer: " + image);
System.out.println("CUBIN size: " + sz[0]);
CUmodule module = new CUmodule();
cuModuleLoadDataEx(module, image, 0, new int[0], Pointer.to(new int[0]));
cuLinkDestroy(linkState);
CUfunction functionKernel = new CUfunction();
String kernelname = "_Z6kernelPfS_S_S_";
cuModuleGetFunction(functionKernel, module, kernelname);
System.out.println("Function: " + functionKernel);
}
}
which works like this:
> nvcc -ptx -arch=sm_21 test_function.cu
test_function.cu
> nvcc -ptx -arch=sm_21 test_kernel.cu
test_kernel.cu
> javac -cp ".;jcuda-0.7.0a.jar" JCudaRuntimeTest.java
> java -cp ".;jcuda-0.7.0a.jar" JCudaRuntimeTest
Pointer: Pointer[nativePointer=0xa5a13a8,byteOffset=0]
CUBIN size: 5924
Function: CUfunction[nativePointer=0xa588160]
The key here seems to be to use cuModuleLoadDataEx, noting that the return values from cuLinkComplete are a system pointer to the linked CUBIN and the size of the image returned as a long[]. As per the C++ code, the pointer is just passed directly to the module data load.
As a final comment, it would have been much simpler and easier if you had posted a proper repro case that could be been directly hacked on, rather than making me learn the rudiments of JCUDA and Java before I could create a useful repro case and get it to work. The documentation for JCUDA is basic, but complete, and against the working C++ example already provided, it only took a couple of minutes of reading to see how to do this.