Created
June 8, 2023 09:31
-
-
Save romanbsd/c08ee82c0200a77d634836c8eac153c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression; | |
public class PolynomialRegressionExample { | |
public static void main(String[] args) { | |
// Define your input data (x and y values) | |
double[][] data = { | |
{1.0, 2.3}, | |
{2.0, 4.5}, | |
{3.0, 6.7}, | |
// Add more data points as needed | |
}; | |
// Create arrays to hold the independent variables (x values) and the dependent variable (y values) | |
double[] x = new double[data.length]; | |
double[] y = new double[data.length]; | |
for (int i = 0; i < data.length; i++) { | |
x[i] = data[i][0]; | |
y[i] = data[i][1]; | |
} | |
// Perform the polynomial regression | |
int degree = 2; // Degree of the polynomial (second order) | |
double[][] xPoly = createPolynomialMatrix(x, degree); // Create the polynomial matrix | |
OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression(); | |
regression.newSampleData(y, xPoly); // Fit the model | |
// Get the estimated parameters | |
double[] parameters = regression.estimateRegressionParameters(); | |
// Print the fitted parameters | |
System.out.println("Fitted Parameters:"); | |
for (int i = 0; i < parameters.length; i++) { | |
System.out.println("Parameter " + i + ": " + parameters[i]); | |
} | |
} | |
private static double[][] createPolynomialMatrix(double[] x, int degree) { | |
int numDataPoints = x.length; | |
double[][] polyMatrix = new double[numDataPoints][degree + 1]; | |
for (int i = 0; i < numDataPoints; i++) { | |
double xi = x[i]; | |
for (int j = 0; j <= degree; j++) { | |
polyMatrix[i][j] = Math.pow(xi, j); | |
} | |
} | |
return polyMatrix; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment