liblinear-java
repository·main·Indexed 43 days ago
https://github.com/bwaldvogel/liblinear-javaA Java port of the C++ LIBLINEAR library for efficient large-scale linear classification, regression, and outlier detection. Version 2.44 requires Java 11 or later. It provides core API methods such as Linear.train(), Linear.predict(), and Linear.predictProbability(), as well as CLI tools for training and prediction using the LIBSVM data format.
What's inside liblinear-java
- The library documentation notes that users should consider the distinction between LIBLINEAR and LIBSVM (though specific comparison details are contained in the subsequent segment of the README).
When to use LIBLINEAR instead of LIBSVM
mainLIBLINEAR is optimized for large-scale regularized linear classification, regression, and outlier detection. It is particularly effective for datasets with a very large number of features where nonlinear mappings (kernels) might not significantly improve performance.
Use LIBLINEAR when:
- You have large-scale data with many features (e.g., document classification).
- You want to efficiently train on much larger datasets using linear classification/regression.
Use LIBSVM when:
- You are a beginner.
- Your datasets are not large.
Warning: While generally fast, the default solver may be slow if data is not scaled or if the parameter
Cis very large.Quick Start with LIBLINEAR CLI
mainAfter installation, you can use the
trainandpredictprograms to manage models via the command line.Data Format Requirements:
- Follow the LIBSVM data format.
- Crucial: Feature indices must start from 1 (not 0).
Basic Workflow:
- Train: Run
train [training_set_file]to generate a.modelfile. - Predict: Run
predict [test_file] [model_file] [output_file]to generate predictions in the output file.
Example using sample data (
heart_scale):# Train the model train heart_scale # Predict using a test set and output results to 'output' predict heart_scale.t heart_scale.model outputtrain heart_scale predict heart_scale.t heart_scale.model outputInstall liblinear-java via Maven
mainAdd the following dependency to your
pom.xmlto use the library in your Maven project. Ensure you are using Java 11 or later, as it is the only requirement.<dependency> <groupId>de.bwaldvogel</groupId> <artifactId>liblinear</artifactId> <version>2.44</version> </dependency>API: Training and Cross-Validation
mainThe core C API for training models and performing cross-validation.
trainConstructs and returns a linear model based on the provided problem and parameters.model* train(const struct problem *prob, const struct parameter *param);cross_validationConducts n-fold cross validation. Predicted labels for the validation process are stored in thetargetarray.void cross_validation(const problem *prob, const parameter *param, int nr_fold, double *target);find_parametersConducts cross validation multiple times to find the bestCandpparameters.void find_parameters(const struct problem *prob, const struct parameter *param, int nr_fold, double start_C, double start_p, double *best_C, double *best_p, double *best_score);Important: Always call
check_parameter()before callingtrain()orcross_validation()to ensure parameters are within the feasible range.API: Prediction and Model Inspection
mainFunctions for using a trained model to predict values or inspect its properties.
Prediction Functions
double predict(const model *model_, const feature_node *x);: Returns the predicted class (classification) or function value (regression).double predict_values(const struct model *model_, const struct feature_node *x, double* dec_values);: Returns decision values indec_values. The number of values returned (nr_w) depends on the model type.double predict_probability(const struct model *model_, const feature_node *x, double* prob_estimates);: Returns probability estimates inprob_estimates. Supported for logistic regression only.
Model Inspection
int get_nr_feature(const model *model_): Returns the number of attributes.int get_nr_class(const model *model_): Returns the number of classes (returns 2 for regression).void get_labels(const model *model_, int* label): Copies class labels into thelabelarray.double get_decfun_coef(const model *model_, int feat_idx, int label_idx): Returns the coefficient for a specific feature and class.feat_idxstarts from 1;label_idxstarts from 0.double get_decfun_bias(const model *model_, int label_idx): Returns the bias term for a specific class.double get_decfun_rho(const model *model_): Returns therhobias term (one-class SVM only).
Core API methods for training and prediction
mainThe library provides three primary methods for programmatic usage, mirroring the original C++ LIBLINEAR implementation:
Linear.train(...): Used to train a model on a given dataset.Linear.predict(...): Used to predict the label for a given feature vector.Linear.predictProbability(...): Used to predict the probability of a label for a given feature vector.
API: Data Structures and Memory Management
mainKey structures used to define problems and parameters, and how to manage their memory.
struct problemDefines the training data:int l: Number of training data.int n: Number of features (including bias ifbias >= 0).int *y: Array of target values.struct feature_node **x: Array of pointers to sparse feature representations.double bias: Bias value.
struct parameterDefines model parameters:int solver_type: The solver to use (e.g.,L2R_LR,ONECLASS_SVM).double eps: Stopping tolerance.double C: Cost of constraint violation.double nu: Parameter for one-class SVM.int nr_weight,int *weight_label,double* weight: Used for class-specific penalties.
Memory Management
void free_model_content(struct model *model_ptr): Frees memory used by model entries.void free_and_destroy_model(struct model **model_ptr_ptr): Frees memory and destroys the model structure.void destroy_param(struct parameter *param): Frees a parameter set.struct model *load_model(const char *model_file_name): Loads a model from a file.int save_model(const char *model_file_name, const struct model *model_): Saves a model to a file.
Reference: `train` command options
mainThe
traincommand is used to construct a linear model from a training set.Usage:
train [options] training_set_file [model_file]Options:
-s type: Set solver type (default 1).- Classification:
0: L2-regularized logistic regression (primal)1: L2-regularized L2-loss SVC (dual)2: L2-regularized L2-loss SVC (primal)3: L2-regularized L1-loss SVC (dual)4: SVC by Crammer and Singer5: L1-regularized L2-loss SVC6: L1-regularized logistic regression7: L2-regularized logistic regression (dual)
- Regression:
11: L2-regularized L2-loss SVR (primal)12: L2-regularized L2-loss SVR (dual)13: L2-regularized L1-loss SVR (dual)
- Outlier Detection:
21: One-class SVM (dual)
- Classification:
-c cost: Set parameterC(default 1).-p epsilon: Set epsilon in loss function of epsilon-SVR (default 0.1).-n nu: Set parameternuof one-class SVM (default 0.5).-e epsilon: Set termination tolerance (default varies by solver).-B bias: Ifbias >= 0, instancexbecomes[x; bias]; if< 0, no bias term added (default -1).-R: Do not regularize the bias (only for specific primal solvers: -s 0, 2, 5, 6, 11; requires-B 1).-wi weight: Adjust parameterCfor different classes.-v n: n-fold cross validation mode.-C: Find best parameters via cross validation (supported for-s 0,-s 2, and-s 11).-q: Quiet mode (no output).
train [options] training_set_file [model_file]Reference: `predict` command options
mainThe
predictcommand is used to test a model against a test set.Usage:
predict [options] test_file model_file output_fileOptions:
-b probability_estimates: Output probability estimates (0 or 1, default 0). Currently supported for logistic regression only.-q: Quiet mode (no output).
predict [options] test_file model_file output_fileUse SolverMCSVM_CS for multi-class SVM training
mainThe
SolverMCSVM_CSclass implements a coordinate descent algorithm for multi-class support vector machines using the Crammer and Singer approach. It is used to solve the optimization problem for multi-class classification by finding the weight vectorwthat minimizes the objective function subject to constraints on the dual variablesalphaand the regularization parameterC.To use this solver, you must provide a
Problemobject containing the training data, the number of classes, aCarray (regularization parameters per instance), a stopping toleranceeps, and aRandominstance for the coordinate descent shuffling.// Note: This is a conceptual usage based on the constructor signature // as the specific Problem and Linear class definitions are in other files. SolverMCSVM_CS solver = new SolverMCSVM_CS( prob, // de.bwaldvogel.liblinear.Problem nr_class, // int: number of classes C, // double[]: regularization parameters eps, // double: stopping tolerance random // java.util.Random ); double[] w = new double[prob.n * nr_class]; solver.solve(w);SolverMCSVM_CS constructor parameters
mainThe
SolverMCSVM_CSconstructor requires the following parameters:Parameter Type Description probProblemThe training problem containing features x, labelsy, number of featuresn, and number of samplesl.nr_classintThe total number of classes in the dataset. Cdouble[]An array of regularization parameters for each sample. epsdoubleThe stopping tolerance for the optimization algorithm. randomRandomA random number generator used for shuffling indices during coordinate descent.