Building a Simple Linear Regression Model : ML

Photo by AltumCode on Unsplash

Building a Simple Linear Regression Model : ML

Hands-on tutorial on building a simple machine learning model using Python and scikit-learn. We'll create a basic linear regression model using a sample dataset.

Step 1: Install Required Libraries

Make sure you have Python installed. You can install the necessary libraries using pip:

```bash

pip install numpy pandas scikit-learn matplotlib

```

Step 2: Import Libraries

Create a new Python script or Jupyter Notebook and import the required libraries:

```python

import numpy as np

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

from sklearn.metrics import mean_squared_error

import matplotlib.pyplot as plt

```

Step 3: Load and Explore Data

For this example, let's generate a simple dataset. In a real-world scenario, you would replace this with your dataset.

```python

# Generate a simple dataset

np.random.seed(42)

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

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

# Visualize the data

plt.scatter(X, y)

plt.xlabel('X')

plt.ylabel('y')

plt.show()

```

Step 4: Split Data into Training and Testing Sets

Split the dataset into a training set and a testing set:

```python

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

```

Step 5: Train the Linear Regression Model

Create and train the linear regression model:

```python

model = LinearRegression()

model.fit(X_train, y_train)

```

Step 6: Make Predictions

Use the trained model to make predictions on the test set:

```python

y_pred = model.predict(X_test)

```

Step 7: Evaluate the Model

Evaluate the model's performance using mean squared error:

```python

mse = mean_squared_error(y_test, y_pred)

print(f'Mean Squared Error: {mse}')

```

Step 8: Visualize the Model

Visualize the linear regression line along with the test data:

```python

plt.scatter(X_test, y_test)

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

plt.xlabel('X')

plt.ylabel('y')

plt.show()

```

That's it! You've built a simple linear regression model. This tutorial provides a basic introduction, and you can explore more complex models and datasets as you advance in your machine learning journey.

...

Derek