Question
Simple Linear Regression — Predicting Salary from Experience
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
- Slope (m): Shows how much the salary changes for each additional year of experience.
- Intercept (c): The base salary when experience is 0 years (theoretical starting point).
- y_pred: The model’s predicted salaries for the given experiences.
- 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
Click here to download practice questions on
Linear Regression