We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Using least square regression through definition (matrix inversions, dot products and transpose), no library:
#!/bin/python3importmathimportosimportrandomimportreimportsysimportpandasaspdimportnumpyasnpfromscipyimportoptimize#import matplotlib.pyplot as pltfromioimportStringIOif__name__=='__main__':timeCharged=float(input().strip())# Read the data using pandasdata=pd.read_csv('trainingdata.txt',header=None,names=["TimeCharged","TimeLasted"])# training data: Range when not fully charge rangeindex_values=data.query("TimeCharged <= 4.01").index.tolist()x=data.TimeCharged[index_values]y=data.TimeLasted[index_values]# Equation to be solved from book https://pythonnumericalmethods.studentorg.berkeley.edu/notebooks/chapter16.02-Least-Squares-Regression-Derivation-Linear-Algebra.html# y = b1 * f1(x)# A Matrix# Only one linear basis function used. Important: Method allows any kind and number of basis function, as long as beta params are constants# Basis function is evaluated at the input measured values. In this case f1(x) = x A=np.array(x).reshape(-1,1)# Y Matrix: Output measured valuesY=np.array(y).reshape(-1,1)#Hereiswherethemagichappends:Leastsquareregressiontofindbetaparametersbeta_params=np.linalg.inv(A.T@A)@A.T@Y# Make predictioniftimeCharged>4.01:#Batteryfullychargedprint(8)else:predicted_time=timeCharged*beta_params[0][0]print(predicted_time)#Outputthepredictedbatterylife
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Join us
Create a HackerRank account
Be part of a 26 million-strong community of developers
Please signup or login in order to view this challenge
Laptop Battery Life
You are viewing a single comment's thread. Return to all comments →
Using least square regression through definition (matrix inversions, dot products and transpose), no library: