我有一个文本,我想通过使用 java API 添加功能来进行训练。查看示例,构建训练集的主要类是svm_problem。看起来svm_node代表一个特征(索引是特征,值 Strong> 是特征的权重)。
我所做的是拥有一个 map (只是为了简化问题)来保持功能和索引之间的关联。对于我的每个 Weight> 示例,我都会创建一个新节点:
svm_node currentNode = new svm_node();
int index = feature.getIndexInMap();
double value = feature.getWeight();
currentNode.index = index;
currentNode.value = value;
我的直觉正确吗? svm_problem.y 指的是什么?它指的是标签的索引吗? svm_problem.l 只是两个向量的长度吗?
最佳答案
你的直觉非常接近,但 svm_node 是一种模式而不是特征。变量 svm_problem.y 是一个包含每个模式标签的数组,svm_problem.l 是训练集的大小。
此外,请注意 svm_parameter.nr_weight 是每个标签的权重(如果您有不平衡的训练集,则很有用),但如果您不打算使用它,则必须将该值设置为零。
让我向您展示一个简单的 C++ 示例:
#include "svm.h"
#include <iostream>
using namespace std;
int main()
{
svm_parameter params;
params.svm_type = C_SVC;
params.kernel_type = RBF;
params.C = 1;
params.gamma = 1;
params.nr_weight = 0;
params.p= 0.0001;
svm_problem problem;
problem.l = 4;
problem.y = new double[4]{1,-1,-1,1};
problem.x = new svm_node*[4];
{
problem.x[0] = new svm_node[3];
problem.x[0][0].index = 1;
problem.x[0][0].value = 0;
problem.x[0][1].index = 2;
problem.x[0][1].value = 0;
problem.x[0][2].index = -1;
}
{
problem.x[1] = new svm_node[3];
problem.x[1][0].index = 1;
problem.x[1][0].value = 1;
problem.x[1][1].index = 2;
problem.x[1][1].value = 0;
problem.x[1][2].index = -1;
}
{
problem.x[2] = new svm_node[3];
problem.x[2][0].index = 1;
problem.x[2][0].value = 0;
problem.x[2][1].index = 2;
problem.x[2][1].value = 1;
problem.x[2][2].index = -1;
}
{
problem.x[3] = new svm_node[3];
problem.x[3][0].index = 1;
problem.x[3][0].value = 1;
problem.x[3][1].index = 2;
problem.x[3][1].value = 1;
problem.x[3][2].index = -1;
}
for(int i=0; i<4; i++)
{
cout << problem.y[i] << endl;
}
svm_model * model = svm_train(&problem, ¶ms);
svm_save_model("mymodel.svm", model);
for(int i=0; i<4; i++)
{
double d = svm_predict(model, problem.x[i]);
cout << "Prediction " << d << endl;
}
/* We should free the memory at this point.
But this example is large enough already */
}
关于machine-learning - LibSvm 使用 JAVA api 添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22480993/