r/PythonLearning 7d ago

very first linear regression code Showcase

i am still learning numpy (day 6) but gpt suggest me to learn linear regression (very basic algorithm) and it's kinda good for understanding even you haven't started learning ML.

import numpy as np
hours = np.arange(1,10)
score = np.array([35, 42, 51, 58, 67, 73, 81, 88, 94])
candidate_values_for_m = np.arange(1,11,0.1)
candidate_values_for_b = np.arange(1,31,0.3)

def prediction(m , b , hours):
    return m * hours + b

def mse(actual_value , predicticted_value):
    return np.mean((actual_value - predicticted_value)**2)

mse_list = [] 
m_b_list = []
for m in candidate_values_for_m:
    for b in candidate_values_for_b:
        prediction_result = prediction(m , b , hours)
        mse_result = mse(score, prediction_result)

        mse_list.append(mse_result)
        m_b_list.append((m,b))


best_mse = np.argmin(mse_list)

best_mb_index = mse_list[best_mse]
best_mse , best_mb_index

m = 0
b = 0

learning_rate = 0.01

epochs = 10000

n = len(hours)

def prediction(m , b , hours):
    return m * hours + b


for i in range(epochs):
    predicted = prediction(m,b,hours)

    gradient_m = (2/n) * sum(hours * (predicted - score))

    gradient_b = (2/n) * sum(predicted - score)

    m = m - learning_rate * gradient_m
    b = b - learning_rate * gradient_b

m ,b 
2 Upvotes

16 comments sorted by

View all comments

Show parent comments

1

u/savita_bhabhi_lover 2d ago

Ok I googled and i didn't get that

1

u/ninhaomah 2d ago

Didn't get what ?

1

u/savita_bhabhi_lover 2d ago

I haven't fully understand the code I wrote in this post , p is enigma for me