Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linear regression with a forced non-zero y-intercept

I would like to run a linear regression with the y-intercept forced to 0.115. This is the code I tried. I set to fit_intercept=True to get a non-zero y-intercept, but can I set it to a value?

Also, how can I get the best fit line to be plotted rather than a line connecting each point?

Thanks in advance.

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from sklearn.metrics import r2_score
from sklearn.linear_model import LinearRegression
x=np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]).reshape(-1,1)
y=np.array([0.113, 0.116, 0.130, 0.150, 0.150, 0.160, 0.180, 0.210, 0.220, 0.260, 0.280])
regression=LinearRegression(fit_intercept=True).fit(x,y)
r_sq=round(regression.score(x,y),4)
m=round(regression.coef_[0],4)
b=round(regression.intercept_,4)
print("r_sq:", r_sq,"m:",m,"b:",b)
plt.figure()
plt.scatter(x,y)
plt.title('A')
plt.ylabel('X')
plt.xlabel('Y')
plt.plot(x,y,'r--',label='measured')
plt.legend(loc='best')
like image 757
Qwynes Avatar asked Oct 15 '25 18:10

Qwynes


1 Answers

Subtract the y intercept you want to fix from your data and set fit_intercept=False.

For example

import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression

x = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]).reshape(-1, 1)
y = np.array([0.113, 0.116, 0.130, 0.150, 0.150, 0.160, 0.180, 0.210, 0.220, 0.260, 0.280])

fig, ax = plt.subplots()

for fit, y_intercept in zip((True, False), (0.0, 0.115)):
    regression = LinearRegression(fit_intercept=fit)
    regression.fit(x, y - y_intercept)

    r_sq = regression.score(x, y - y_intercept)
    m = regression.coef_[0]
    b = regression.intercept_ + y_intercept

    print(f"Fit intercept: {regression.fit_intercept}")
    print(f"r_sq: {r_sq:0.4f}\nm: {m:0.4f}\nb: {b:0.4f}")

    ax.plot(x, y, "bo")
    ax.plot(
        x,
        regression.predict(x) + y_intercept,
        "r" + "--" * fit,
        label=f"Fit Intercept: {regression.fit_intercept}",
    )

ax.set_title("A")
ax.set_ylabel("X")
ax.set_xlabel("Y")

ax.legend(loc="best")

plt.show()

Which prints:

Fit intercept: True
r_sq: 0.9473
m: 0.0017
b: -0.0192
Fit intercept: False
r_sq: 0.9112
m: 0.0014
b: 0.0000
like image 179
David Hoffman Avatar answered Oct 17 '25 09:10

David Hoffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!