Java 的svm代码
时间: 2023-07-09 07:52:53 浏览: 138
以下是一个简单的Java SVM分类器的示例代码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import libsvm.*;
public class SVMClassifier {
public static void main(String[] args) throws IOException {
List<Double> y = new ArrayList<Double>();
List<svm_node[]> x = new ArrayList<svm_node[]>();
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.trim().split("\\s+");
double label = Double.parseDouble(parts[0]);
svm_node[] features = new svm_node[parts.length - 1];
for (int i = 1; i < parts.length; i++) {
String[] indexValue = parts[i].split(":");
features[i - 1] = new svm_node();
features[i - 1].index = Integer.parseInt(indexValue[0]);
features[i - 1].value = Double.parseDouble(indexValue[1]);
}
y.add(label);
x.add(features);
}
reader.close();
svm_problem problem = new svm_problem();
problem.l = y.size();
problem.x = new svm_node[problem.l][];
problem.y = new double[problem.l];
for (int i = 0; i < problem.l; i++) {
problem.x[i] = x.get(i);
problem.y[i] = y.get(i);
}
svm_parameter param = new svm_parameter();
param.svm_type = svm_parameter.C_SVC;
param.kernel_type = svm_parameter.RBF;
param.gamma = 0.5;
param.nu = 0.5;
param.cache_size = 20000;
param.C = 1;
param.eps = 0.001;
svm_model model = svm.svm_train(problem, param);
// Test the model
Random rand = new Random();
int correct = 0;
for (int i = 0; i < 100; i++) {
int index = rand.nextInt(y.size());
svm_node[] testFeatures = x.get(index);
double trueLabel = y.get(index);
double predictedLabel = svm.svm_predict(model, testFeatures);
if (predictedLabel == trueLabel) {
correct++;
}
}
System.out.println("Accuracy: " + (correct / 100.0));
}
}
```
在上面的代码中,我们首先读取一个LIBSVM格式的训练数据集,并将其转换为libsvm库使用的数据结构。然后,我们定义一个SVM参数对象,设置一些参数,例如SVM类型、内核类型、惩罚系数等等。最后,我们使用训练数据和SVM参数来训练一个SVM模型,并使用随机生成的测试数据集来测试该模型的准确性。
阅读全文