|
| 1 | +package com.thealgorithms.machinelearning; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | + |
| 5 | +class LinearRegression { |
| 6 | + private ArrayList<Double> dependentX = new ArrayList<Double>(); |
| 7 | + private ArrayList<Double> independentY = new ArrayList<Double>(); |
| 8 | + private double m; |
| 9 | + private double c; |
| 10 | + |
| 11 | + public LinearRegression(ArrayList<Double> dependentX, ArrayList<Double> independentY) { |
| 12 | + this.dependentX = dependentX; |
| 13 | + this.independentY = independentY; |
| 14 | + this.Equate(); |
| 15 | + } |
| 16 | + |
| 17 | + private double Sumation(ArrayList<Double> arr){ |
| 18 | + double sum = 0.0; |
| 19 | + |
| 20 | + for(int i = 0; i < arr.size(); i++){ |
| 21 | + sum += arr.get(i); |
| 22 | + } |
| 23 | + |
| 24 | + return sum; |
| 25 | + } |
| 26 | + |
| 27 | + private ArrayList<Double> MultiplyNumber(ArrayList<Double> arr1, ArrayList<Double> arr2) { |
| 28 | + ArrayList<Double> temp = new ArrayList<Double>(); |
| 29 | + for(int i = 0; i < arr1.size(); i++) { |
| 30 | + temp.add((arr1.get(i) * arr2.get(i))); |
| 31 | + } |
| 32 | + return temp; |
| 33 | + } |
| 34 | + |
| 35 | + private void Equate(){ |
| 36 | + int n = dependentX.size(); |
| 37 | + this.m = (n * Sumation(MultiplyNumber(independentY, dependentX)) - (Sumation(dependentX) * Sumation(independentY))); |
| 38 | + this.m = this.m / (n * (Sumation(MultiplyNumber(dependentX, dependentX))) - (Sumation(dependentX) * Sumation(dependentX))); |
| 39 | + |
| 40 | + this.c = (Sumation(independentY) * Sumation(MultiplyNumber(dependentX, dependentX)) - (Sumation(dependentX) * Sumation(MultiplyNumber(independentY, dependentX)))); |
| 41 | + this.c = this.c / (n * (Sumation(MultiplyNumber(dependentX, dependentX))) - (Sumation(dependentX) * Sumation(dependentX))); |
| 42 | + } |
| 43 | + |
| 44 | + public double getM(){ |
| 45 | + return this.m; |
| 46 | + } |
| 47 | + |
| 48 | + public double getC(){ |
| 49 | + return this.c; |
| 50 | + } |
| 51 | + |
| 52 | + public double PredictForX(double x) { |
| 53 | + return (this.m * x) + this.c; |
| 54 | + } |
| 55 | +} |
0 commit comments