Code:
import numpy as np
import matplotlib.pyplot as plt
# Data points
X = np.array([70, 80, 90, 100, 110, 120, 130, 140, 150, 160])
Y = np.array([7, 7, 8, 9, 12, 12, 15, 14, 13, 17])
# Number of data points
n = len(X)
# Calculate the sums needed for the slope (w1) and intercept (w0)
sum_X = np.sum(X)
sum_Y = np.sum(Y)
sum_XY = np.sum(X * Y)
sum_X2 = np.sum(X**2)
# Calculate w1 (slope) and w0 (intercept)
w1 = (n * sum_XY - sum_X * sum_Y) / (n * sum_X2 - sum_X**2)
w0 = (sum_Y - w1 * sum_X) / n
print(f"Slope (w1): {w1}")
print(f"Intercept (w0): {w0}")
# Predict Y for a given X (e.g., X = 210)
X_new = 210
Y_pred = w0 + w1 * X_new
print(f"Predicted Y for X = {X_new}: {Y_pred}")
# Plotting the graph
plt.scatter(X, Y, color='blue', label='Data points') # Scatter plot for the data points
plt.plot(X, w0 + w1 * X, color='red', label='Regression line') # Regression line
# Adding labels and title
plt.xlabel('X values')
plt.ylabel('Y values')
plt.title('Linear Regression Line')
plt.legend()
# Show the plot
plt.show()
# import numpy as np
# import matplotlib.pyplot as plt
# # Data points
# X = np.array([70, 80, 90, 100, 110, 120, 130, 140, 150, 160])
# Y = np.array([7, 7, 8, 9, 12, 12, 15, 14, 13, 17])
# # Number of data points
# n = len(X)
# # Calculate the sums needed for the slope (w1) and intercept (w0)
# sum_X = np.sum(X)
# sum_Y = np.sum(Y)
# sum_XY = np.sum(X * Y)
# sum_X2 = np.sum(X**2)
# # Calculate w1 (slope) and w0 (intercept)
# w1 = (n * sum_XY - sum_X * sum_Y) / (n * sum_X2 - sum_X**2)
# w0 = (sum_Y - w1 * sum_X) / n
# print(f"Slope (w1): {w1}")
# print(f"Intercept (w0): {w0}")
# # Predict Y for a given X (e.g., X = 210)
# X_new = 210
# Y_pred = w0 + w1 * X_new
# print(f"Predicted Y for X = {X_new}: {Y_pred}")
# # Plotting
# # Create a range of X values for plotting the regression line
# X_line = np.linspace(min(X), max(X_new, max(X)), 100)
# Y_line = w0 + w1 * X_line
# # Plot the data points
# plt.scatter(X, Y, color='blue', label='Data Points')
# # Plot the regression line
# plt.plot(X_line, Y_line, color='red', label='Regression Line')
# # Plot the prediction for X_new
# plt.scatter(X_new, Y_pred, color='green', marker='x', s=100, label=f'Prediction at X
= {X_new}')
# # Labels and title
# plt.xlabel('X')
# plt.ylabel('Y')
# plt.title('Linear Regression')
# # Show legend
# plt.legend()
# # Display the plot
# plt.show()
Output:
Slope (w1): 0.10909090909090909
Intercept (w0): -1.1454545454545453
Predicted Y for X = 210: 21.763636363636362