Question

Simple Linear Regression — Predicting Salary from Experience

Updated on August 15, 2025 | By Learnzy Admin | 👁️ Views: 118 students

Solution
✔ Verified
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

# Sample data
data = pd.DataFrame({
    'Experience': [1, 2, 3, 4, 5],
    'Salary': [30000, 35000, 40000, 45000, 50000]
})

# Features & target
X = data[['Experience']]  # Independent variable
y = data['Salary']        # Dependent variable

# Create and train model
model = LinearRegression()
model.fit(X, y)

# Predictions for training data
y_pred = model.predict(X)

# Output slope & intercept
print("Slope (m):", model.coef_[0])
print("Intercept (c):", model.intercept_)

# Error calculation
mae = mean_absolute_error(y, y_pred)
print("Mean Absolute Error (MAE):", mae)

# Predict for new experience value
print("Prediction for 6 years experience:", model.predict([[6]])[0])

Explanation

  1. Slope (m): Shows how much the salary changes for each additional year of experience.
  2. Intercept (c): The base salary when experience is 0 years (theoretical starting point).
  3. y_pred: The model’s predicted salaries for the given experiences.
  4. Mean Absolute Error (MAE): Average difference between actual salaries and predicted salaries.

Output:--

Slope (m): 5000.0
Intercept (c): 25000.0
Mean Absolute Error (MAE): 0.0
Prediction for 6 years experience: 55000.0
Was this solution helpful? 37
Click here to download practice questions on Linear Regression

More Questions on Linear Regression

Question 1

What is Multiple Linear Regression (MLR)


View solution
Question 2

How do you measure the accuracy of a linear regression model?


View solution
Question 3

What is the difference between simple and multiple linear regression?


View solution
Question 4

What is Linear Regression?


View solution