You are on page 1of 3

Name: Ali Raza Roll # MSCS 23030 Course: Machine learning

Assignment#2
Implement GDA for fitting a line in a given dataset. Data is given in a text file. Program will
read data from the text file and fit a line to the data and display the data and line as a
graph. Bring your assignment in printed form.

import numpy as np

import matplotlib.pyplot as plt

# Function to compute the mean squared error

def mean_squared_error(y_true, y_pred):

return np.mean((y_true - y_pred) ** 2)

# Function to perform gradient descent

def gradient_descent(x, y, learning_rate, num_iterations):

m, b = 0.0, 0.0 # Initial values for the slope and intercept

n = len(x)

for _ in range(num_iterations):

# Calculate the gradients

y_pred = m * x + b

gradient_m = (-2/n) * np.sum(x * (y - y_pred))

gradient_b = (-2/n) * np.sum(y - y_pred)

# Update the parameters using the gradients

m -= learning_rate * gradient_m

b -= learning_rate * gradient_b

return m, b
# Read data from the text file

data = np.loadtxt('/content/dataset.txt', delimiter=' ')

x = data[:, 0]

y = data[:, 1]

# Hyperparameters

learning_rate = 0.01

num_iterations = 1000

# Perform gradient descent to fit a line

m, b = gradient_descent(x, y, learning_rate, num_iterations)

# Generate the line using the fitted parameters

x_line = np.linspace(min(x), max(x), 100)

y_line = m * x_line + b

# Plot the data and the fitted line

plt.scatter(x, y, label='Data')

plt.plot(x_line, y_line, color='red', label='Fitted Line')

plt.xlabel('X')

plt.ylabel('Y')

plt.legend()

plt.title('Linear Regression with Gradient Descent')

plt.grid(True)

# Display the plot

plt.show()
# Print the fitted line equation

print(f"Fitted Line: y = {m:.2f}x + {b:.2f}")

print(f"Mean Squared Error: {mean_squared_error(y, m * x + b):.2f}")

Fitted Line: y = 1.10x + 4.73

Mean Squared Error: 0.01

You might also like