Linear Regression using Gradient Descent method
Gradient Descent Method
Step 1: Import the necessary libraries
import numpy as npimport pandas as pd
import matplotlib.pyplot as plt
Step 2: Load the CSV Data
# Load the datasetdata = pd.read_csv('house_data.csv')
# Extract the features (X) and target variable (y)
X = data['Size'].values
y = data['Price'].values
# Reshape X to be a 2D array
X = X.reshape(-1, 1)
# Add a column of ones to X for the intercept
X_b = np.c_[np.ones((X.shape[0], 1)), X]
X_b = np.c_[np.ones((X.shape[0], 1)), X]
Step 3: Initialize Parameters
# Initialize the parameters
theta = np.random.randn(2)
# Random initialization of theta
(intercept and slope)
learning_rate = 0.01
n_iterations = 1000
m = len(y) # Number of training examples
Step 4: Implement the Gradient Descent Algorithm
# Gradient Descent
for iteration in range(n_iterations):
gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y)
theta = theta - learning_rate * gradients
Step 5: Make Predictions
# Make predictions
y_pred = X_b.dot(theta)
Step 6: Visualize the Results
# Plot the data and the regression line
plt.scatter(X, y, color='blue', label='Data')
plt.plot(X, y_pred, color='red', label='Regression Line')
plt.xlabel('Size (Square Feet)')
plt.ylabel('Price (Dollars)')
plt.legend()
plt.show()
Comments