Code Explanation:
Import the required library
from sklearn.linear_model import LinearRegression
Explanation:
You import the LinearRegression class from sklearn.linear_model, which is used to create and train a linear regression model.
Linear regression finds the best-fit line that describes the relationship between input (X) and output (y).
Import NumPy for numerical data
import numpy as np
Explanation:
NumPy is a library for handling arrays and performing mathematical operations efficiently.
We’ll use it to create arrays for our input features and target values.
Create the input (feature) array
X = np.array([[1], [2], [3]])
Explanation:
X is a 2D array (matrix) representing the input feature.
Each inner list ([1], [2], [3]) is one data point (feature value).
So here, we have 3 samples:
X = [[1],
[2],
[3]]
Shape of X = (3, 1) → 3 rows (samples), 1 column (feature).
Create the target (output) array
y = np.array([2, 4, 6])
Explanation:
y contains the target values (what we want the model to predict).
Here the relationship is clear: y = 2 * X.
X: 1 → y: 2
X: 2 → y: 4
X: 3 → y: 6
Create and train (fit) the Linear Regression model
model = LinearRegression().fit(X, y)
Explanation:
LinearRegression() creates an empty regression model.
.fit(X, y) trains the model using our data.
The model learns the best-fit line that minimizes prediction error.
In this simple case, it learns the formula:
y=2x+0
(slope = 2, intercept = 0)
Make a prediction for a new input
print(model.predict([[4]])[0])
Explanation:
model.predict([[4]]) asks the trained model to predict y when x = 4.
Since the model learned y = 2x,
y=2×4=8
The result of .predict() is an array (e.g., [8.]), so we use [0] to get the first value.
print() displays it.
Output:
8.0
.png)

0 Comments:
Post a Comment