Skip to content

Instantly share code, notes, and snippets.

@Bhavya031
Created December 24, 2024 05:58
Show Gist options
  • Save Bhavya031/bf2380569a1cd3e5b51f6ddf06d42dfd to your computer and use it in GitHub Desktop.
Save Bhavya031/bf2380569a1cd3e5b51f6ddf06d42dfd to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
X_b = np.c_[np.ones((100, 1)), X]
theta_best = np.linalg.inv(X_b.T @ X_b) @ (X_b.T @ y)
print("Estimated coefficients (theta):", theta_best.ravel())
X_new = np.array([[0], [2]])
X_new_b = np.c_[np.ones((2, 1)), X_new]
y_pred = X_new_b @ theta_best
plt.scatter(X, y, color="blue", label="Data")
plt.plot(X_new, y_pred, color="red", label="Prediction")
plt.xlabel("X")
plt.ylabel("y")
plt.title("Linear Regression Fit")
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment