Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Visualizing Linear Regression with Matplotlib in AI


Description: This example demonstrates how to perform linear regression on a dataset and visualize the results using matplotlib. The example fits a linear model to data and shows the relationship between the independent variable and the dependent variable.

1: Install Required Libraries

First, ensure you have numpy, scikit-learn, and matplotlib installed. You can install these using pip:

pip install numpy scikit-learn matplotlib

2: Create the Python Script

Create a Python script (e.g., linear_regression_ai.py) with the following code:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Generate some synthetic data for training
# Here we create a simple linear relationship y = 3x + 2 with some noise
np.random.seed(42)
X = 2 * np.random.rand(100, 1)
y = 3 * X + 2 + np.random.randn(100, 1)

# Create a linear regression model and fit it to the data
model = LinearRegression()
model.fit(X, y)

# Predict values using the model
X_new = np.array([[0], [2]])
y_predict = model.predict(X_new)

# Plot the original data and the regression line
plt.scatter(X, y, color='blue', label='Data points')
plt.plot(X_new, y_predict, color='red', label='Regression line')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression in AI')
plt.legend()
plt.show()


Explanation

1: Import Libraries:

2: Generate Synthetic Data:

3: Fit the Model:

4: Make Predictions:

5: Plot the Data and Regression Line:



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java