import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# Sample data
X = np.array([[1], [2], [3], [4], [5]]) # Independent variable
y = np.array([2, 3, 5, 7, 11]) # Dependent variable
# 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=0)
# Initialize the Linear Regression model
model = LinearRegression()
# Fit the model using the training data
model.fit(X_train, y_train)
# Make predictions using the testing data
y_pred = model.predict(X_test)
# Print the model coefficients
print(f"Coefficient: {model.coef_[0]}")
print(f"Intercept: {model.intercept_}")
# Visualize the regression line
plt.scatter(X, y, color='blue', label='Data points')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Regression line')
plt.xlabel('Independent variable')
plt.ylabel('Dependent variable')
plt.title('Simple Linear Regression')
plt.legend()
plt.show()
This script creates some sample data, fits a linear regression model, and then plots the data along with the regression line. The coefficients of the model (slope and intercept) are also printed. Adjust the X and y arrays to use your own data.