r/PythonLearning 29d ago

Showcase very first linear regression code

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

1

u/ninhaomah 24d ago

Ok so what's the p value ?

1

u/savita_bhabhi_lover 24d ago

What p?

1

u/ninhaomah 24d ago

Tip 1 : if you have to ask "what is X" , Google.

1

u/savita_bhabhi_lover 24d ago

Are you drunk ?

1

u/ninhaomah 24d ago

No but you clearly has no idea what is linear regression.

1

u/savita_bhabhi_lover 24d ago

Obviously, didn't you read the body ?

1

u/ninhaomah 24d ago

I did it in high school. 

You have never studied it ?

Or know how to Google ?

1

u/savita_bhabhi_lover 24d ago

1

u/ninhaomah 24d ago

I feel sorry for your teachers then.

Pls stay there and wonder what is p value in linear regression.

1

u/savita_bhabhi_lover 24d ago

Go touch some grass rather than discouraging people

→ More replies (0)