└── LinearRegression /LinearRegression: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class LinearRegression { 4 | private double[] x; 5 | private double[] y; 6 | private double slope; 7 | private double intercept; 8 | 9 | public LinearRegression(double[] x, double[] y) { 10 | if (x.length != y.length) { 11 | throw new IllegalArgumentException("Input arrays must have the same length"); 12 | } 13 | this.x = x; 14 | this.y = y; 15 | fit(); 16 | } 17 | 18 | private void fit() { 19 | double xMean = Arrays.stream(x).average().orElseThrow(); 20 | double yMean = Arrays.stream(y).average().orElseThrow(); 21 | 22 | double numerator = 0; 23 | double denominator = 0; 24 | 25 | for (int i = 0; i < x.length; i++) { 26 | numerator += (x[i] - xMean) * (y[i] - yMean); 27 | denominator += Math.pow(x[i] - xMean, 2); 28 | } 29 | 30 | slope = numerator / denominator; 31 | intercept = yMean - slope * xMean; 32 | } 33 | 34 | public double predict(double xInput) { 35 | return slope * xInput + intercept; 36 | } 37 | 38 | public static void main(String[] args) { 39 | double[] x = {1, 2, 3, 4, 5}; 40 | double[] y = {2, 4, 5, 4, 5}; 41 | 42 | LinearRegression model = new LinearRegression(x, y); 43 | 44 | System.out.println("Slope: " + model.slope); 45 | System.out.println("Intercept: " + model.intercept); 46 | 47 | double xInput = 6; 48 | System.out.println("Predicted value for x=" + xInput + ": " + model.predict(xInput)); 49 | } 50 | } 51 | --------------------------------------------------------------------------------