WEKA API LibSVM ClassPath not found - java

I'm trying to use LibSVM with Weka API.
My System:
Win7
Weka 3.7.12
LibSVM 1.0.6 (Installed via Package Manager)
My Code:
import java.io.File;
import java.util.Random;
import javax.swing.JOptionPane;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.LibSVM;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class LibSVMClassifier {
// Method to build a SVM classifier with a given data file
public static double buildModel(File dataSet){
// new instance of LibSVM
LibSVM clsSVM = new LibSVM();
try {
Instances data = DataSource.read(dataSet.getAbsolutePath());
// Sets the label feature
data.setClassIndex(data.numAttributes()-1);
String opts = "-S 0 -K 0 -D 3 -G 0.0 -R 0.0 -N 0.5 -M 40.0 -C 1.0 -E 0.0010 -P 0.1";
// set the options for the algorithm
clsSVM.setOptions(weka.core.Utils.splitOptions(opts));
Evaluation eval = new Evaluation(data);
eval.crossValidateModel(clsSVM, data, 2, new Random(1));
return eval.pctIncorrect();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
return 100;
}
}
Code is called from here:
double error = LibSVMClassifier.buildModel(trainDataSet);
My problem:
When I run my code and first use my J48 classifier (code at the end) and afterwards the LibSVM everything works fine.
If I run the LibSVM first I get the following error:
java.lang.Exception: libsvm classes not in CLASSPATH!
weka.classifiers.functions.LibSVM.buildClassifier(LibSVM.java:1636)
weka.classifiers.evaluation.Evaluation.crossValidateModel(Evaluation.java:764)
weka.classifiers.Evaluation.crossValidateModel(Evaluation.java:374)
totd.BuildModel.LibSVMClassifier.buildModel(LibSVMClassifier.java:34)
totd.GUI.Gui$5.actionPerformed(Gui.java:215)
If I export the project to a runable jar and use it on another machine without weka installed the error will also occur if I run the J48 algorithm first. So no matter what I can't use the LibSVM on another machine.
I have read through all the other questions regarding this problem, but there was no solution for me. In order to prevent answers that will not help me here some things that wont work:
Explanation how to add a library to the project: Ive used the package
manager from weka to install LibSVM and I added the resulting jar
file for LIBSVM AS WELL AS weka jar file to my build path
Explanation how to use LibSVM with weka gui: I want to use LibSVM together with the weka api in a programmatic way, it already works in weka gui I dont need that!!!
Explanation how to change the classpath for your system: I want to export my project to a jar file and run it on any system I dont have access to the system class path
Possible solutions that I didnt understand but that I think might work if someone explains in detail:
https://stackoverflow.com/a/13766120/5006670 In this post it is mentioned to obtain the .class files from SVNLib (I suppose SVM?) and adding these to my buildpath. I do not understand which files he is speaking about and how I would compile the make file if I were to find it. But it sounds like my error message.
https://weka.wikispaces.com/LibSVM talks about using reflection. Im not sure how this is used
using a batch file to start the jar file together with the LibSVM.jar with -classpath command
J48 Code:
import java.io.File;
import javax.swing.JOptionPane;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.classifiers.trees.J48;
import weka.classifiers.Evaluation;
import java.util.Random;
public class J48Classifier {
// Method to build a J48 classifier with a given data file
public static double buildModel(File dataSet){
// new instance of tree
J48 clsJ48 = new J48();
try {
Instances data = DataSource.read(dataSet.getAbsolutePath());
// Sets the label feature
data.setClassIndex(data.numAttributes()-1);
String[] options = new String[1];
// unpruned tree
options[0] = "-U";
// set the options for the algorithm
clsJ48.setOptions(options);
Evaluation eval = new Evaluation(data);
eval.crossValidateModel(clsJ48, data, 2, new Random(1));
return eval.pctIncorrect();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
return 100;
}
}
My build path

Okay, steps how magic work:
Search for hours and fail
Ask on a forum
Try for 5 more minutes and succeed
SOLUTION:
There are 2! LibSVM.jar files in the weka package folder and you need BOTH.
So for all that try to use LibSVM using weka package manager go to:
(HOME)\wekafiles\packages\LibSVM
There you find the first FIRST LibSVM.jar
now go to:
(HOME)\wekafiles\packages\LibSVM\lib
here you will find libsvm.jar
ADD BOTH OF THESE JAR TO YOUR BUILD PATH!!!
Greetings

Related

Using Batik 1.14 with Java: How to import modules or classes?

The purpose of my project is to create PNG pictures from SVG using specific fonts (I have tried numerous converter services on the web but none of them worked with external fonts, and the JAVA program I have developed 10 years ago does no longer work).
My actual problem is the import of the batik.transcoder components into my program. Currently, it looks as follows:
<code>
// is this the really the parent of JPEGTranscoder / PNGTranscoder??
import javax.imageio.ImageTranscoder;
// Neither org.apache.batik... nor batik... is correct !!??
import org.apache.batik.transcoder.SVGAbstractTranscoder;
import batik.transcoder.TranscoderException;
import batik.transcoder.TranscoderInput;
import batik.transcoder.TranscoderOutput;
import batik.transcoder.PNGTranscoder;
import batik.transcoder.image.JPEGTranscoder;<br>
// or did I import the wrong jars ??
// (taken from batik-1.14 and afterwards from batik-1.7; neither did work!)
public class SVGConverter {
...
// all code lines below return the same error: "... cannot be resolved to a type"
TranscoderInput input = new TranscoderInput(svgURI);
TranscoderOutput output = new TranscoderOutput(ostream);
ImageTranscoder t;
...
t = new JPEGTranscoder();
...
t = new PNGTranscoder();
...
}
</code>
First I tried to import the batik components as modules on the module path but without success. In a contribution to stackoverflow I then found the hint to put the batik components not onto the module path but to the class path (Has batik not been converted into modules?). However, no success either.
I have copied all jar's contained in batik-1.14.zip and later of batik-1.7.zip into the lib directory within the project. No effect whatsoever...
I was using "import org.apache.batik.transcoder.XXX" in my previous program in 2013: Doesn't work any more. But using "import batik.transcoder.XXX" doesn't work either.
Thus, the following questions:
1. Is it correct that batik classes/jars have to be used via the class path?
2. What is the correct package name to address the respective packages and classes?
3. Is it correct to load the corresponding jar's into the lib directory of the project?

GraalVM - embedding python multi-file project in java

I couldn't find a solution create a polyglot source out of multiple files in GraalVM.
What exactly I want to achieve:
I have a python project:
my-project:
.venv/
...libs
__main__.py
src/
__init__.py
Service.py
Example sourcecode:
# __main__.py
from src.Service import Service
lambda url: Service(url)
# src/Service.py
import requests
class Service:
def __init__(self, url):
self.url = url
def invoke(self):
return requests.get(self.url)
This is very simple example, where we've got an entry-point script, project is structured in packages and there is one external library (requests).
It works, when I run it from command-line with python3 __main__.py, but I can't get it work, when embedding it in Java (it can't resolve imports).
Example usage in java:
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import java.io.File;
import java.io.IOException;
public class Runner {
public static void main(String[] args) throws IOException {
Context context = Context.newBuilder("python")
.allowExperimentalOptions(true)
.allowAllAccess(true)
.allowIO(true)
.build();
try (context) {
// load lambda reference:
Value reference = context.eval(Source.newBuilder("python", new File("/path/to/my-project/__main__.py")).build());
// invoke lambda with `url` argument (returns `Service` object)
Value service = reference.execute("http://google.com");
// invoke `invoke` method of `Service` object and print response
System.out.println("Response: " + service.getMember("invoke").execute());
}
}
}
It fails with Exception in thread "main" ModuleNotFoundError: No module named 'src'.
The solution works for javascript project (having similar index.js to __main__.py, its able to resolve imports - GraalVM "sees" other project's files, but somehow it doesn't, when using python.
I found out, that python is able to run zip package with project inside, but this also doesn't work with GraalVM.
Is there any chance to accomplish it? If not, maybe there is a similar tool to webpack for python (if I could create a single-file bundle, it should also work).
Btw, I don't know python at all, so I may missing something.
Thanks for any help!

Undefined function or variable 'BufferedImageLuminanceSource'

I recently used decode_qr from this FEX submission to decode my QR code. It ran quite well one or two weeks ago, but today it generate an error for me:
Undefined function or variable 'BufferedImageLuminanceSource'
Error in decode_qr (line 34);
source = BufferedImageLuminanceSource(jig);
I just checked the zxing repository and found that some files were updated several days ago. So I guess the path of some imported file from the package has been changed.
Here is the importing code from the decode_qr function:
import com.google.zxing.qrcode.*;
import com.google.zxing.client.j2se.*;
import com.google.zxing.*;
import com.google.zxing.common.*;
import com.google.zxing.Result.*;
How can I get it to work again? Do I need to change the import paths?
Here's what I did to get it to work (Win 10 x64, R2017b, ZXing 3.3.1):
Downloaded the latest prebuilt .jar artifacts from Sonatype:
core.
javase.
Added the files to my dynamic java classpath using javaaddpath:
javaaddpath('G:\core-3.3.1.jar');
javaaddpath('G:\javase-3.3.1.jar');
% Verify using: javaclasspath('-dynamic');
Note:
To add folders to the static path, which MATLAB loads at startup, create a javaclasspath.txt file, as described in Static Path.
Generated some example QR code using unitag.io:
Tried to decode it using Lior Shapira's decode_qr:
>> out = decode_qr(qr)
out =
'https://stackoverflow.com/users/3372061/dev-il'
Full code:
function out = q47223578()
javaaddpath('G:\core-3.3.1.jar');
javaaddpath('G:\javase-3.3.1.jar');
% Verify using: javaclasspath('-dynamic');
qr = imread('https://i.stack.imgur.com/mA4eP.png');
out = decode_qr(qr);

Obtianing output of NeurophStudio - import error (java)

I am trying to abtain the output (for example: cat: 0,988; dog: 0.012) from NeurophStudio using java. The neural net recognises the images well. I found the code below. I get errors in the first two import lines. Does anyone know where I can find/download these packages? I searched through all my directories already and didn't find it.
import org.neuroph.core.NeuralNetwork; // ! error
import org.neuroph.contrib.imgrec.ImageRecognitionPlugin; // ! error
import java.util.HashMap;
import java.io.File;
import java.io.IOException;
public class ImageRecognitionSample {
public static void main(String[] args) {
// load trained neural network saved with Neuroph Studio (specify some existing neural network file here)
NeuralNetwork nnet = NeuralNetwork.load("Neural Networks/Iconnet25-8.nnet"); // load trained neural network saved with Neuroph Studio
// get the image recognition plugin from neural network
ImageRecognitionPlugin imageRecognition = (ImageRecognitionPlugin)nnet.getPlugin(ImageRecognitionPlugin.class); // get the image recognition plugin from neural network
try {
// image recognition is done here (specify some existing image file)
HashMap<String, Double> output = imageRecognition.recognizeImage(new File("testimage.png"));
System.out.println(output.toString());
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
source : http://neuroph.sourceforge.net/image_recognition.html
I found the package code here : https://github.com/neuroph/neuroph/tree/master/neuroph-2.9/Core/src/main/java/org/neuroph/core
Problem: this is not downloadable and I will probably need multiple files/entire package.
Does anyone have experience with this? Any solutions?
download neuroph.jar
then locate it to your project
like this
right click on your project
properties
Libraries
add jar/folder
then show the path where you put the neuroph.jar
hope it will help you!!!!

Simple program to call R from Java using Eclipse and Rserve

My application must perform R operations such as:
m = matrix(sample(0:1,100, rep=T),ncol=10)
The results should be available to a Java application.
The Rserve package bridges R to other languages, since it acts as a TCP/IP server. I've read the website but don't know how to make the simplest application that can use Rserve.
What steps are required to make a simple Eclipse application that uses Rserve to execute R commands from Java?
There is a binary version of Rserve in the download section (www.rforge.net/Rserve/files/ I have version R 2.13 and Windows xp, so I need download Windows binary: Rserve_0.6-8.zip (541.3kb, updated: Wed Apr 18 07:00:45 2012)). Copy the file to the directory containing R.DLL. After installed Rserve from CRAN
install.packages("Rserve")
in R (I have RStudio - convenient thing: Download RStudio IDE).
started Rserve is from within R, just type
library(Rserve)
Rserve()
Сheck in Task Manager - Rserve.exe should be run.
After make a Java project in Eclipse, make a directory called lib under that project. Paste
2 jar here RserveEngine.jar and REngine.jar (www.rforge.net/Rserve/files/). Do not forget to add this jars in Properties your java-project. In new class code:
import org.rosuda.REngine.*;
import org.rosuda.REngine.Rserve.*;
public class rserveuseClass {
public static void main(String[] args) throws RserveException {
try {
RConnection c = new RConnection();// make a new local connection on default port (6311)
double d[] = c.eval("rnorm(10)").asDoubles();
org.rosuda.REngine.REXP x0 = c.eval("R.version.string");
System.out.println(x0.asString());
} catch (REngineException e) {
//manipulation
}
}
}
Here are some more detailed instructions for creating an RServe project from scratch:
First Install and get Rserve running in R.
Install R
Add package RServe from CRAN.
In R type: install.packages("Rserve")
For remote access:
Create file: /etc/Rserv.conf
Add the following to Rserv.conf
workdir /tmp/Rserv
remote enable
auth required
plaintext disable
port 6311
maxsendbuf 0 (size in kB, 0 means unlimited use)
In R: run the following commands
library(Rserve)
For Windows:
Rserve()
For Mac:
Rserve(args="--no-save")
An instance of Rserve is now running on localhost port 6311.
Next Create an Rserve project (i'm using eclipse)
For this I'm going to use eclipse:
Download RserveEngine.jar and REngine.jar from here.
Create a java project in eclipse.
Create a lib folder under your project directory. (same level as your src folder)
Copy RserveEngine.jar and REngine.jar into the lib folder.
Add jars to build path: Instructions
Add a package then a main class: call it something like HelloWorldApp.
Add this code to the class
package com.sti.ai;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class HelloWorldApp {
public static void main(String[] args) throws RserveException, REXPMismatchException, FileNotFoundException, IOException {
RConnection c = new RConnection("<host/ip>", 6311);
if(c.isConnected()) {
System.out.println("Connected to RServe.");
if(c.needLogin()) {
System.out.println("Providing Login");
c.login("username", "password");
}
REXP x;
System.out.println("Reading script...");
File file = new File("<file location>");
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
System.out.println(line);
x = c.eval(line); // evaluates line in R
System.out.println(x); // prints result
}
}
} else {
System.out.println("Rserve could not connect");
}
c.close();
System.out.println("Session Closed");
}
}
Finally, run HelloWorldApp.java
For those who are using Maven
REngine
<dependency>
<groupId>org.nuiton.thirdparty</groupId>
<artifactId>REngine</artifactId>
<version>1.7-3</version>
</dependency>
RServe
<dependency>
<groupId>org.rosuda.REngine</groupId>
<artifactId>Rserve</artifactId>
<version>1.8.1</version>
</dependency>
Quick ones, trying to separate tasks:
Rserve can be installed by itself. Start there.
Rserve has sample clients. Try to the Java samples to work.
From there, write your new program.
Eclipse is entirely optional. You do not have to use it. If this is one more step to learn, consider skipping it. Once 1 to 3 are fine, learn how to express build dependencies in Eclipse.
There are two ways to call R from Java - JRI and RServe. This is a plugin that will help you setup RJava on windows. If you are looking for a more production level solution then Rserve serves a better purpose. This example shows how to run a sample RServe program. If you are using RServe then run your command in eval function
REXP m = c.eval("matrix(sample(0:1,100, rep=T),ncol=10)")
There are some default datastructures that you can use to convert m (REXP).

Categories

Resources