Monday, 13 October 2025

Python Coding challenge - Day 787| What is the output of the following Python Code?

 


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

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)