🧠 AI with Python – 📈 Fit Your First ML Model – Linear Regression


Description:

Why Linear Regression?

Linear regression is often the first step in machine learning because it’s simple yet powerful for continuous predictions like prices, sales, and trends.


How It Works?

It finds the best-fit line for given data, predicting output as:

y = β0 + β1x + ε

Where It’s Useful?

  • Predicting numeric outcomes like house prices or stock trends.
  • Learning basic model evaluation metrics (R², MAE).

Practical Takeaway

Start your ML journey with linear regression. It’s easy to understand, interpret, and sets the foundation for advanced models.


Code Snippet:

# Import Required
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

# Create a simple dataset
data = {
    'YearsExperience': [1, 2, 3, 4, 5, 6],
    'Salary': [35000, 40000, 50000, 60000, 65000, 70000]
}
df = pd.DataFrame(data)
df

X = df[['YearsExperience']]  # Features (2D array)
y = df['Salary']  # Target

model = LinearRegression()
model.fit(X, y)

print("Coefficient (Slope):", model.coef_[0])
print("Intercept:", model.intercept_)

# Make predictions
y_pred = model.predict(X)

# Plot data points and regression line
plt.scatter(X, y, color='blue', label='Actual data')
plt.plot(X, y_pred, color='red', label='Regression line')
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.title("Linear Regression Model")
plt.legend()
plt.show()

Link copied!

Comments

Add Your Comment

Comment Added!