linear-regression-ass
November 10, 2024
[1]: import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
# Step 1: Generate random data points
np.random.seed(0) # For reproducibility
x = np.random.rand(20, 1) * 10 # Random x values between 0 and 10
y = 2.5 * x + np.random.randn(20, 1) * 2 # y = 2.5x + some noise
# Step 2: Fit a linear regression model
model = LinearRegression()
model.fit(x, y)
slope = model.coef_[0][0] # m
intercept = model.intercept_[0] # b
# Step 3: Print the equation of the line
print(f"Equation of the line: y = {slope:.2f}x + {intercept:.2f}")
# Step 4: Predict y-value for x = 21
x_new = np.array([[21]])
y_pred_21 = model.predict(x_new)[0][0]
print(f"Predicted y-value for x=21: {y_pred_21:.2f}")
# Step 5: Plot original data, regression line, and forecasted point
plt.scatter(x, y, color='blue', label='Data points')
plt.plot(x, model.predict(x), color='red', label='Regression line')
plt.scatter(21, y_pred_21, color='green', marker='o', s=100, label=f'Forecasted␣
↪point (x=21, y={y_pred_21:.2f})')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Linear Regression on Random Data')
plt.show()
# Step 6: Calculate R-squared value
y_pred = model.predict(x)
1
r2 = r2_score(y, y_pred)
print(f"R-squared value: {r2:.2f}")
Equation of the line: y = 2.69x + -1.08
Predicted y-value for x=21: 55.35
R-squared value: 0.91