diff --git a/crh_LinearRegression.py b/crh_LinearRegression.py new file mode 100644 index 0000000000000000000000000000000000000000..400348cc6657e9d792325e9d5708fbe8fc6071db --- /dev/null +++ b/crh_LinearRegression.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Nov 17 20:17:16 2021 + +Provides functions for calculating the coeffs (m,c) of the +linear regression y=mx+c for a given set of point-data [x,y] + +flag: plot + +@author: hoefert +""" + +## https://www.mathematik.de/algebra/74-erste-hilfe/algebra/matrizen/2432-anwendungen-der-matrizenrechnung + +import matplotlib.pyplot as plt +import numpy as np + + +def linearRegression(x, y, plot = False): + # creating the LES A'A ( m c)' = A'y + # with A = (x , 1) + + # creating LES (over determined) + n = len(x) + A= np.ones((n,2)) + A[:,0] = np.transpose(x) + b = np.transpose(y) + + M = np.matmul(A.T,A) + + bTrans = np.matmul(A.T,b) + [m,c] = np.linalg.solve(M,bTrans) + + if plot: + plotLinearRegression(x, y, m, c) + + return m,c + + +def logLinearRegression(x, y, plot = False): + + xLog = np.log10(x) + yLog = np.log10(y) + + m,c = linearRegression(xLog,yLog) + + if plot: + plotLog10LinearRegression(x, y, m, c) + + return m,c + + +def plotLinearRegression(x,y,m,c): + xLin = np.linspace(min(x),max(x),100) + yLin = xLin*m+c + plt.plot(x,y,'o') + plt.plot(xLin,yLin,linewidth=2) + plt.grid('both') + plt.show() + + +def plotLog10LinearRegression(x,y,m,c, plotLog = False): + plt.plot(x,y,'o') + xLin = np.linspace(min(x),max(x),100) + yLin = 10**c*xLin**m + plt.plot(xLin,yLin,linewidth=2) + if plotLog: + plt.xscale('log') + plt.yscale('log') + plt.grid('both') + plt.show() + + +