0% found this document useful (0 votes)
11 views2 pages

Linear Regression Ass

The document outlines a linear regression analysis using Python, where random data points are generated and a linear model is fitted. It includes steps for predicting a y-value for a given x, plotting the data and regression line, and calculating the R-squared value. The final outputs include the equation of the regression line, a predicted y-value for x=21, and an R-squared value of 0.91.

Uploaded by

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

Linear Regression Ass

The document outlines a linear regression analysis using Python, where random data points are generated and a linear model is fitted. It includes steps for predicting a y-value for a given x, plotting the data and regression line, and calculating the R-squared value. The final outputs include the equation of the regression line, a predicted y-value for x=21, and an R-squared value of 0.91.

Uploaded by

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

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

You might also like