---
execute:
eval: false
echo: true
warning: false
format:
html:
code-fold: false
---In [1]:
Importing the libraries for a linear regression.
In [1]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegressionGenerating the data.
In [2]:
X = np.random.uniform(-5, 5, 100).reshape(-1, 1)
y = 2.5 * X.squeeze() + 1.0 + np.random.normal(0, 2, 100)Creating and fitting the model.
In [3]:
model = LinearRegression()
model.fit(X, y)LinearRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
LinearRegression()
Printing the coefficients.
In [4]:
A = model.coef_[0]
b = model.intercept_
print(f"y_hat = {A:.2f} * x + {b:.2f}")y_hat = 2.51 * x + 0.86
Plotting the final result.
In [5]:
plt.figure(figsize=(8, 5))
plt.scatter(X, y, color='blue', alpha=0.6, label='Observations')
plt.plot(X, model.predict(X), color='red', linewidth=2, label=f'y_hat = {A:.2f}x + {b:.2f}')
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()