0% found this document useful (0 votes)
4 views1 page

3) Linearreg

The document contains a Python script that implements linear regression using NumPy. It calculates the slope and intercept based on a given dataset and plots the data points along with the best fit line using Matplotlib. The example dataset consists of five points, and the script outputs the calculated slope and intercept values.

Uploaded by

Esprit Lawrence
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

3) Linearreg

The document contains a Python script that implements linear regression using NumPy. It calculates the slope and intercept based on a given dataset and plots the data points along with the best fit line using Matplotlib. The example dataset consists of five points, and the script outputs the calculated slope and intercept values.

Uploaded by

Esprit Lawrence
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import numpy as np

import matplotlib.pyplot as plt

def linear_regression(x, y):


# Number of data points
n = len(x)

# Calculate means of x and y


mean_x = np.mean(x)
mean_y = np.mean(y)

# Calculate the coefficients (slope and intercept)


numerator = np.sum((x - mean_x) * (y - mean_y))
denominator = np.sum((x - mean_x) ** 2)
slope = numerator / denominator
intercept = mean_y - slope * mean_x

return slope, intercept

# Example dataset
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.2, 2.8, 4.5, 3.7, 5.5])

# Perform linear regression


slope, intercept = linear_regression(x, y)
print(f"Slope: {slope:.2f}")
print(f"Intercept: {intercept:.2f}")

# Predicted values
y_pred = slope * x + intercept

# Plot the data and the regression line


plt.scatter(x, y, color='blue', label='Data Points')
plt.plot(x, y_pred, color='red', label='Best Fit Line')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Linear Regression')
plt.legend()
plt.grid()
plt.show()

You might also like