Linear regression with Python
Linear regression is a popular machine learning algorithm used to predict the relationship between two variables. In this case, we will use Python to implement a simple linear regression model.
Step 1: Import necessary libraries and load the dataset
Step 2: Split the data into training and testing sets
Step 3: Fit the linear regression model to the training data and make predictions
Step 4: Visualize the results
By following these steps, you can easily implement a simple linear regression model in Python and visualize the results.
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Load the dataset data = pd.read_csv('data.csv') X = data['X'].values y = data['y'].values
Step 2: Split the data into training and testing sets
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 3: Fit the linear regression model to the training data and make predictions
from sklearn.linear_model import LinearRegression # Reshape X_train and X_test to 2D arrays X_train = X_train.reshape(-1, 1) X_test = X_test.reshape(-1, 1) # Fit the model model = LinearRegression() model.fit(X_train, y_train) # Make predictions y_pred = model.predict(X_test)
Step 4: Visualize the results
plt.scatter(X_test, y_test, color='blue') plt.plot(X_test, y_pred, color='red', linewidth=2) plt.xlabel('X') plt.ylabel('y') plt.title('Linear Regression') plt.show()
By following these steps, you can easily implement a simple linear regression model in Python and visualize the results.
Comments
Post a Comment