0
0
ML Pythonprogramming~5 mins

First ML prediction (linear regression) in ML Python

Choose your learning style9 modes available
Introduction
Linear regression helps us find a simple line that best fits data points so we can predict new values easily.
You want to predict house prices based on size.
Estimating sales based on advertising budget.
Predicting temperature changes over time.
Forecasting student scores from study hours.
Understanding relationship between weight and height.
Syntax
ML Python
from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
X_train and y_train are your training data features and targets.
predict() gives the model's output for new input data.
Examples
Train a model to learn y = 2 * x and predict y for x=5.
ML Python
from sklearn.linear_model import LinearRegression

X_train = [[1], [2], [3], [4]]
y_train = [2, 4, 6, 8]

model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict([[5]])
Predict values for multiple inputs after training.
ML Python
from sklearn.linear_model import LinearRegression

X_train = [[10], [20], [30]]
y_train = [15, 25, 35]

model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict([[25], [35]])
Sample Program
This program trains a linear regression model to predict exam scores based on hours studied. It then predicts the score for 6 hours.
ML Python
from sklearn.linear_model import LinearRegression

# Training data: hours studied vs exam score
X_train = [[1], [2], [3], [4], [5]]
y_train = [50, 55, 65, 70, 75]

# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)

# Predict score for 6 hours studied
X_test = [[6]]
prediction = model.predict(X_test)

print(f"Predicted score for 6 hours studied: {prediction[0]:.2f}")
OutputSuccess
Important Notes
Linear regression assumes a straight-line relationship between input and output.
Make sure your input data is in the correct shape (2D array) for sklearn.
The model learns coefficients that multiply inputs to predict outputs.
Summary
Linear regression finds a line that best fits your data points.
You train the model with known inputs and outputs.
Then you use the model to predict new outputs from new inputs.