# Linear Regression in Python - ML From Scratch 02

In this Machine Learning from Scratch Tutorial, we are going to implement the Linear Regression algorithm, using only built-in Python modules and numpy. We will also learn about the concept and the math behind this popular ML algorithm.

All algorithms from this course can be found on GitHub together with example tests.

### Further readings:

- https://ml-cheatsheet.readthedocs.io/en/latest/linear_regression.html
- https://ml-cheatsheet.readthedocs.io/en/latest/gradient_descent.html

## Implementation

```
import numpy as np
class LinearRegression:
def __init__(self, learning_rate=0.001, n_iters=1000):
self.lr = learning_rate
self.n_iters = n_iters
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
# init parameters
self.weights = np.zeros(n_features)
self.bias = 0
# gradient descent
for _ in range(self.n_iters):
y_predicted = np.dot(X, self.weights) + self.bias
# compute gradients
dw = (1 / n_samples) * np.dot(X.T, (y_predicted - y))
db = (1 / n_samples) * np.sum(y_predicted - y)
# update parameters
self.weights -= self.lr * dw
self.bias -= self.lr * db
def predict(self, X):
y_approximated = np.dot(X, self.weights) + self.bias
return y_approximated
```

**Join My Newsletter! **Get Python and ML tips emailed directly to your inbox. Each month you’ll get a summary of all the content I created, including the newest videos, articles, promotions, tips, and more.

# TensorFlow 2 Beginner

Learn all the necessary basics to get started with TensorFlow 2 and Keras.

# PyTorch Beginner

Learn all the necessary basics to get started with this deep learning framework.

# ML From Scratch

Implement popular Machine Learning algorithms from scratch using only built-in Python modules and numpy.