Либлинейный формат использования
Я использую.NET реализацию liblinear в своем коде C# с помощью следующего пакета nuget: https://www.nuget.org/packages/Liblinear/
Но в файле readme liblinear формат для x:
struct problem
описывает проблему:
struct problem
{
int l, n;
int *y;
struct feature_node **x;
double bias;
};
where `l` is the number of training data. If bias >= 0, we assume
that one additional feature is added to the end of each data
instance. `n` is the number of feature (including the bias feature
if bias >= 0). `y` is an array containing the target values. (integers
in classification, real numbers in regression) And `x` is an array
of pointers, each of which points to a sparse representation (array
of feature_node) of one training vector.
For example, if we have the following training data:
LABEL ATTR1 ATTR2 ATTR3 ATTR4 ATTR5
----- ----- ----- ----- ----- -----
1 0 0.1 0.2 0 0
2 0 0.1 0.3 -1.2 0
1 0.4 0 0 0 0
2 0 0.1 0 1.4 0.5
3 -0.1 -0.2 0.1 1.1 0.1
and bias = 1, then the components of problem are:
l = 5
n = 6
y -> 1 2 1 2 3
x -> [ ] -> (2,0.1) (3,0.2) (6,1) (-1,?)
[ ] -> (2,0.1) (3,0.3) (4,-1.2) (6,1) (-1,?)
[ ] -> (1,0.4) (6,1) (-1,?)
[ ] -> (2,0.1) (4,1.4) (5,0.5) (6,1) (-1,?)
[ ] -> (1,-0.1) (2,-0.2) (3,0.1) (4,1.1) (5,0.1) (6,1) (-1,?)
Но в примере, показывающем реализацию Java: https://gist.github.com/hodzanassredin/6682771
problem.x <- [|
[|new FeatureNode(1,0.); new FeatureNode(2,1.)|]
[|new FeatureNode(1,2.); new FeatureNode(2,0.)|]
|]// feature nodes
problem.y <- [|1.;2.|] // target values
что означает, что его набор данных:
1 0 1
2 2 0
Таким образом, он не хранит узлы в соответствии с разреженным форматом liblinear. Кто-нибудь знает правильный формат для x для liblinear реализации?
1 ответ
Хотя это не относится именно к библиотеке, которую вы упомянули, я могу предложить вам альтернативу. Платформа Accord.NET Framework недавно включила все алгоритмы LIBLINEAR в свои пространства имен машинного обучения. Это также доступно через NuGet.
В этой библиотеке, прямой синтаксис для создания линейных опорных векторов из в памяти данных
// Create a simple binary AND
// classification problem:
double[][] problem =
{
// a b a + b
new double[] { 0, 0, 0 },
new double[] { 0, 1, 0 },
new double[] { 1, 0, 0 },
new double[] { 1, 1, 1 },
};
// Get the two first columns as the problem
// inputs and the last column as the output
// input columns
double[][] inputs = problem.GetColumns(0, 1);
// output column
int[] outputs = problem.GetColumn(2).ToInt32();
// However, SVMs expect the output value to be
// either -1 or +1. As such, we have to convert
// it so the vector contains { -1, -1, -1, +1 }:
//
outputs = outputs.Apply(x => x == 0 ? -1 : 1);
После того, как проблема создана, можно изучить линейный SVM, используя
// Create a new linear-SVM for two inputs (a and b)
SupportVectorMachine svm = new SupportVectorMachine(inputs: 2);
// Create a L2-regularized L2-loss support vector classification
var teacher = new LinearDualCoordinateDescent(svm, inputs, outputs)
{
Loss = Loss.L2,
Complexity = 1000,
Tolerance = 1e-5
};
// Learn the machine
double error = teacher.Run(computeError: true);
// Compute the machine's answers for the learned inputs
int[] answers = inputs.Apply(x => Math.Sign(svm.Compute(x)));
Это предполагает, однако, что ваши данные уже находятся в памяти. Если вы хотите загрузить свои данные с диска, из файла в разреженном формате libsvm, вы можете использовать класс SparseReader платформы. Пример того, как его использовать, можно найти ниже:
// Suppose we are going to read a sparse sample file containing
// samples which have an actual dimension of 4. Since the samples
// are in a sparse format, each entry in the file will probably
// have a much smaller number of elements.
//
int sampleSize = 4;
// Create a new Sparse Sample Reader to read any given file,
// passing the correct dense sample size in the constructor
//
SparseReader reader = new SparseReader(file, Encoding.Default, sampleSize);
// Declare a vector to obtain the label
// of each of the samples in the file
//
int[] labels = null;
// Declare a vector to obtain the description (or comments)
// about each of the samples in the file, if present.
//
string[] descriptions = null;
// Read the sparse samples and store them in a dense vector array
double[][] samples = reader.ReadToEnd(out labels, out descriptions);
После этого можно использовать samples
а также labels
векторы как входы и выходы задачи соответственно.
Я надеюсь, что это помогает.
Отказ от ответственности: я являюсь автором этой библиотеки. Я отвечаю на этот вопрос в искренней надежде, что он может быть полезен для ФП, поскольку не так давно я столкнулся с такими же проблемами. Если модератор считает, что это похоже на спам, вы можете удалить его. Однако я публикую это только потому, что думаю, что это может помочь другим. Я даже столкнулся с этим вопросом по ошибке, когда искал существующие реализации C# LIBSVM, а не LIBLINEAR.