### Configure Dataset with Fields Source: https://github.com/metarank/lightgbm4j/blob/main/README.md Full example showing how to set feature names and label fields for a dataset created from a matrix. ```java String[] columns = new String[] { "Age","BMI","Glucose","Insulin","HOMA","Leptin","Adiponectin","Resistin","MCP.1" }; double[] values = new double[] { 71,30.3,102,8.34,2.098344,56.502,8.13,4.2989,200.976, 66,27.7,90,6.042,1.341324,24.846,7.652055,6.7052,225.88, 75,25.7,94,8.079,1.8732508,65.926,3.74122,4.49685,206.802, 78,25.3,60,3.508,0.519184,6.633,10.567295,4.6638,209.749, 69,29.4,89,10.704,2.3498848,45.272,8.2863,4.53,215.769, 85,26.6,96,4.462,1.0566016,7.85,7.9317,9.6135,232.006, 76,27.1,110,26.211,7.111918,21.778,4.935635,8.49395,45.843, 77,25.9,85,4.58,0.960273333,13.74,9.75326,11.774,488.829, 45,21.30394858,102,13.852,3.4851632,7.6476,21.056625,23.03408,552.444, 45,20.82999519,74,4.56,0.832352,7.7529,8.237405,28.0323,382.955, 49,20.9566075,94,12.305,2.853119333,11.2406,8.412175,23.1177,573.63, 34,24.24242424,92,21.699,4.9242264,16.7353,21.823745,12.06534,481.949, 42,21.35991456,93,2.999,0.6879706,19.0826,8.462915,17.37615,321.919, 68,21.08281329,102,6.2,1.55992,9.6994,8.574655,13.74244,448.799, 51,19.13265306,93,4.364,1.0011016,11.0816,5.80762,5.57055,90.6, 62,22.65625,92,3.482,0.790181867,9.8648,11.236235,10.69548,703.973 }; float[] labels = new float[] { 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1 }; LGBMDataset dataset = LGBMDataset.createFromMat(values, 16, columns.length, true, "", null); dataset.setFeatureNames(columns); dataset.setField("label", labels); return dataset; ``` -------------------------------- ### Low-level SWIG JNI interface example Source: https://github.com/metarank/lightgbm4j/blob/main/README.md Demonstrates the manual memory management and buffer handling required when using the raw SWIG-generated JNI interface. ```java SWIGTYPE_p_float dataBuffer = new_floatArray(input.length); for (int i = 0; i < input.length; i++) { floatArray_setitem(dataBuffer, i, input[i]); } int result = <...> if (result < 0) { delete_floatArray(dataBuffer); throw new Exception(LGBM_GetLastError()); } else { delete_floatArray(dataBuffer); <...> } ``` -------------------------------- ### Install native library dependencies Source: https://github.com/metarank/lightgbm4j/blob/main/README.md Commands to install required OpenMP libraries on MacOS and Debian Linux. ```bash brew install libomp ``` ```bash apt install libgomp1 ``` -------------------------------- ### Train Model with File-based Datasets Source: https://github.com/metarank/lightgbm4j/blob/main/README.md Full training loop example using datasets loaded from CSV files. ```java // cancer dataset from https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Coimbra // with labels altered to fit the [0,1] range LGBMDataset train = LGBMDataset.createFromFile("cancer.csv", "header=true label=name:Classification", null); LGBMDataset test = LGBMDataset.createFromFile("cancer-test.csv", "header=true label=name:Classification", train); LGBMBooster booster = LGBMBooster.create(train, "objective=binary label=name:Classification"); booster.addValidData(test); for (int i=0; i<10; i++) { booster.updateOneIter(); double[] evalTrain = booster.getEval(0); double[] evalTest = booster.getEval(1); System.out.println("train: " + eval[0] + " test: " + ); } booster.close(); train.close(); test.close(); ``` -------------------------------- ### Native library override logs Source: https://github.com/metarank/lightgbm4j/blob/main/README.md Example log output indicating that the library successfully loaded custom native binaries from the path specified by the LIGHTGBM_NATIVE_LIB_PATH environment variable. ```text LIGHTGBM_NATIVE_LIB_PATH is set: loading /home/user/code/LightGBM/lib_lightgbm.so LIGHTGBM_NATIVE_LIB_PATH is set: loading /home/user/code/LightGBM/lib_lightgbm_swig.so ``` -------------------------------- ### Custom Objective Function (MSE) Source: https://github.com/metarank/lightgbm4j/blob/main/README.md Implement a custom objective function for LightGBM4j by providing gradients and hessians. Use 'objective=none' and specify an evaluation metric. This example demonstrates Mean Squared Error (MSE). ```java LGBMDataset dataset = LGBMDataset.createFromFile("cancer.csv", "header=true label=name:Classification", null); LGBMBooster booster = LGBMBooster.create(dataset, "objective=none metric=rmse label=name:Classification"); // actual ground truth label values float y[] = dataset.getFieldFloat("label"); for (int it=0; it<10; it++) { // predictions for current iteration double[] yhat = booster.getPredict(0); // 0 - training dataset float[] grad = new float[y.length]; float[] hess = new float[y.length]; for (int i=0; i 0); double pred2 = booster.predictForMatSingleRow(new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, PredictionType.C_API_PREDICT_NORMAL); assertTrue(pred2 > 0); } dataset.close(); booster.close(); ``` -------------------------------- ### Add Maven Dependency for LightGBM4j Source: https://context7.com/metarank/lightgbm4j/llms.txt Include this Maven dependency to add LightGBM4j to your project. It includes pre-built native libraries for all supported platforms. ```xml io.github.metarank lightgbm4j 4.6.0-2 ``` -------------------------------- ### LGBMBooster.predictForMatSingleRow Source: https://context7.com/metarank/lightgbm4j/llms.txt Optimized prediction method for single samples. Re-uses internal predictor structures for better performance in serving scenarios. ```APIDOC ## POST /predictForMatSingleRow ### Description Optimized prediction method for single samples. Re-uses internal predictor structures for better performance in serving scenarios. ### Method POST ### Endpoint /predictForMatSingleRow ### Parameters #### Request Body - **features** (double[] or float[]) - Required - Array of features for a single sample. - **prediction_type** (PredictionType) - Required - The type of prediction to perform (e.g., NORMAL, RAW_SCORE). ### Request Example ```json { "features": [71.0, 30.3, 102.0, 8.34, 2.098, 56.5, 8.13, 4.29, 200.9], "prediction_type": "C_API_PREDICT_NORMAL" } ``` ### Response #### Success Response (200) - **prediction** (double) - The prediction value for the single sample. #### Response Example ```json { "prediction": 0.12345 } ``` ``` -------------------------------- ### Serialize and Deserialize Models Source: https://context7.com/metarank/lightgbm4j/llms.txt Convert models to strings for storage or network transmission and reload them for inference. ```java // Train a model LGBMDataset dataset = LGBMDataset.createFromFile( "src/test/resources/cancer.csv", "header=true label=name:Classification", null ); LGBMBooster booster = LGBMBooster.create(dataset, "objective=binary label=name:Classification"); for (int i = 0; i < 10; i++) booster.updateOneIter(); // Save model to string String modelString = booster.saveModelToString( 0, // start iteration (0 = from beginning) 0, // num iterations (0 = all iterations) LGBMBooster.FeatureImportanceType.GAIN // importance type for saved model ); // Save to file if needed // Files.writeString(Path.of("model.txt"), modelString); booster.close(); dataset.close(); // Later: Load model from string LGBMBooster loadedBooster = LGBMBooster.loadModelFromString(modelString); // Or load from file // LGBMBooster fileBooster = LGBMBooster.createFromModelfile("model.txt"); // Use loaded model for predictions float[] input = new float[] { 71, 30.3f, 102, 8.34f, 2.098f, 56.5f, 8.13f, 4.29f, 200.9f }; double prediction = loadedBooster.predictForMatSingleRow( input, PredictionType.C_API_PREDICT_NORMAL ); System.out.println("Loaded model prediction: " + prediction); loadedBooster.close(); ``` -------------------------------- ### LGBMBooster.predictForMat Source: https://context7.com/metarank/lightgbm4j/llms.txt Make predictions on a batch of samples provided as a matrix array. Supports multiple prediction types including probabilities, raw scores, leaf indices, and SHAP values. ```APIDOC ## POST /predictForMat ### Description Make predictions on a batch of samples provided as a matrix array. Supports multiple prediction types including probabilities, raw scores, leaf indices, and SHAP values. ### Method POST ### Endpoint /predictForMat ### Parameters #### Request Body - **input** (float[]) - Required - Array of input features in row-major order. - **rows** (int) - Required - Number of samples (rows) in the input matrix. - **columns** (int) - Required - Number of features (columns) in the input matrix. - **row_major** (boolean) - Required - Specifies if the input matrix is in row-major format. - **prediction_type** (PredictionType) - Required - The type of prediction to perform (e.g., NORMAL, RAW_SCORE, LEAF_INDEX, CONTRIB). ### Request Example ```json { "input": [71.0, 30.3, 102.0, 8.34, 2.098, 56.5, 8.13, 4.29, 200.9, 45.0, 21.3, 102.0, 13.8, 3.48, 7.64, 21.0, 23.0, 552.4], "rows": 2, "columns": 9, "row_major": true, "prediction_type": "C_API_PREDICT_NORMAL" } ``` ### Response #### Success Response (200) - **predictions** (double[]) - An array of prediction values. #### Response Example ```json { "predictions": [0.12345, 0.67890] } ``` ``` -------------------------------- ### Single-Row Predictions with LGBMBooster.predictForMatSingleRow Source: https://context7.com/metarank/lightgbm4j/llms.txt Use predictForMatSingleRow for optimized single-sample predictions, ideal for serving scenarios. It accepts both double[] and float[] input types and allows specifying prediction types. ```java import com.microsoft.ml.lightgbm.PredictionType; // Load trained model LGBMDataset dataset = LGBMDataset.createFromFile( "src/test/resources/cancer.csv", "header=true label=name:Classification", null ); LGBMBooster booster = LGBMBooster.create(dataset, "objective=binary label=name:Classification"); for (int i = 0; i < 10; i++) booster.updateOneIter(); // Single row prediction with double[] input double[] featuresDouble = new double[] { 71, 30.3, 102, 8.34, 2.098, 56.5, 8.13, 4.29, 200.9 }; double predDouble = booster.predictForMatSingleRow( featuresDouble, PredictionType.C_API_PREDICT_NORMAL ); System.out.println("Prediction (double): " + predDouble); // Single row prediction with float[] input float[] featuresFloat = new float[] { 71, 30.3f, 102, 8.34f, 2.098f, 56.5f, 8.13f, 4.29f, 200.9f }; double predFloat = booster.predictForMatSingleRow( featuresFloat, PredictionType.C_API_PREDICT_NORMAL ); System.out.println("Prediction (float): " + predFloat); // Get raw score instead of probability double rawScore = booster.predictForMatSingleRow( featuresDouble, PredictionType.C_API_PREDICT_RAW_SCORE ); System.out.println("Raw score: " + rawScore); dataset.close(); booster.close(); ``` -------------------------------- ### Set Special Fields on Dataset with LGBMDataset.setField Source: https://context7.com/metarank/lightgbm4j/llms.txt Set special fields like labels, weights, groups (for ranking), and position (for position bias) on a dataset. Labels and weights require `float[]`, while group and position require `int[]`. ```java // Create dataset for ranking task float[] matrix = new float[] { // query group 1 1.0f, 2.0f, // doc1 features 3.0f, 4.0f, // doc2 features // query group 2 1.0f, 2.0f, // doc1 features 3.0f, 4.0f // doc2 features }; LGBMDataset dataset = LGBMDataset.createFromMat(matrix, 4, 2, true, "", null); // Set relevance labels (float[]) dataset.setField("label", new float[] { 1.0f, 0.0f, 1.0f, 0.0f }); // Set query groups - each value indicates docs per group (int[]) dataset.setField("group", new int[] { 2, 2 }); // Set position bias classes for position-aware LTR training (int[]) dataset.setField("position", new int[] { 0, 1, 0, 1 }); // Optional: set sample weights (float[]) dataset.setField("weight", new float[] { 1.0f, 1.0f, 0.5f, 0.5f }); dataset.close(); ``` -------------------------------- ### Analyze Feature Importance Source: https://context7.com/metarank/lightgbm4j/llms.txt Retrieve gain or split-count importance metrics to evaluate feature contribution to the model. ```java // Train model LGBMDataset dataset = LGBMDataset.createFromFile( "src/test/resources/cancer.csv", "header=true label=name:Classification", null ); LGBMBooster booster = LGBMBooster.create(dataset, "objective=binary label=name:Classification"); for (int i = 0; i < 10; i++) booster.updateOneIter(); // Get feature names String[] featureNames = booster.getFeatureNames(); // Get importance by gain (total gain from splits using each feature) double[] gainImportance = booster.featureImportance( 0, // num iterations (0 = all) LGBMBooster.FeatureImportanceType.GAIN ); // Get importance by split count (number of times each feature is used) double[] splitImportance = booster.featureImportance( 0, LGBMBooster.FeatureImportanceType.SPLIT ); // Print feature importances System.out.println("Feature Importance (Gain):"); for (int i = 0; i < featureNames.length; i++) { System.out.printf(" %s: %.4f (gain), %.0f (splits)%n", featureNames[i], gainImportance[i], splitImportance[i]); } // Get number of features and classes int numFeatures = booster.getNumFeature(); int numClasses = booster.getNumClasses(); System.out.println("Features: " + numFeatures + ", Classes: " + numClasses); dataset.close(); booster.close(); ``` -------------------------------- ### LGBMBooster.featureImportance Source: https://context7.com/metarank/lightgbm4j/llms.txt Retrieves feature importance scores to evaluate the contribution of each feature to the model's predictions. ```APIDOC ## Java Method: featureImportance ### Description Calculates and returns the importance scores for features based on gain or split count. ### Parameters - **numIterations** (int) - Required - Number of iterations to consider. - **importanceType** (FeatureImportanceType) - Required - The metric to use (GAIN or SPLIT). ### Response - **importanceScores** (double[]) - An array of importance scores corresponding to the model features. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.