0% found this document useful (0 votes)
8 views

Linear regression

This document provides a Python program that implements linear regression using scikit-learn. It generates sample data, splits it into training and testing sets, trains a linear regression model, and evaluates its performance using mean squared error and R-squared score. The results are visualized with a scatter plot and a regression line.

Uploaded by

Navin Kumar
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)
8 views

Linear regression

This document provides a Python program that implements linear regression using scikit-learn. It generates sample data, splits it into training and testing sets, trains a linear regression model, and evaluates its performance using mean squared error and R-squared score. The results are visualized with a scatter plot and a regression line.

Uploaded by

Navin Kumar
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

Program:
import numpy as np

import matplotlib.pyplot as plt

from sklearn.linear_model import LinearRegression

from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_squared_error, r2_score

# Generate sample data

np.random.seed(0)

X = np.random.rand(100, 1)

y = 2 + 3 * X + np.random.randn(100, 1) * 0.1

# Split the data into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create and train the model

model = LinearRegression()

model.fit(X_train, y_train)

# Make predictions

y_pred = model.predict(X_test)

# Evaluate the model

mse = mean_squared_error(y_test, y_pred)

r2 = r2_score(y_test, y_pred)

print(f"Intercept: {model.intercept_[0]:.2f}")

print(f"Slope: {model.coef_[0][0]:.2f}")

print(f"Mean squared error: {mse:.2f}")


print(f"R-squared score: {r2:.2f}")

# Plot the results

plt.scatter(X_test, y_test, color='black')

plt.plot(X_test, y_pred, color='blue', linewidth=3)

plt.xlabel('X')

plt.ylabel('y')

plt.title('Linear Regression')

plt.show()

You might also like