-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearRegression.py
More file actions
79 lines (66 loc) · 2.95 KB
/
Copy pathLinearRegression.py
File metadata and controls
79 lines (66 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# Load the CSV file
data = pd.read_csv('TeleCom.csv')
df = pd.DataFrame(data)
# Show the Last few rows
print("Bottom Data Samples for testing:")
print(data.tail())
# Show the first few rows for model training consistency
'''print("Top Data Samples for testing:")
print(data.tail())'''
# Extract relevant columns
X = data[['Salary']] # Independent variable
y = data['TaxDeduction'] # Dependent variable
# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create and train the linear regression model
model = LinearRegression()
model.fit(X_train, y_train)
# Predict using the model
y_pred = model.predict(X_test)
# Evaluate some aspects of the model
print(f"R² score: {r2_score(y_test, y_pred):.4f}")
print(f"Mean Squared Error: {mean_squared_error(y_test, y_pred):.2f}")
print(f"Regression Coefficient: {model.coef_[0]:.2f}")
print(f"Intercept: {model.intercept_:.2f}")
#Perform data analysis
print("\nData Analysis:")
print(f"Total number of employees: {len(data)}")
print(f"Number of employees in training set: {len(X_train)}")
print(f"Number of employee in test set: {len(X_test)}")
print(f"Max salary : {df['Salary'].max():.2f}")
print(f"Min salary : {df['Salary'].min():.2f}")
#Mean, max, and min values for Salary and Tax Deduction in the training set
print("\nSalary Training Set Statistics:")
print(f"Mean Salary in training set: {X_train['Salary'].mean():.2f}")
print(f"Max Salary in training set: {X_train['Salary'].max():.2f}")
print(f"Average Salary in training set: {X_train['Salary'].mean():.2f}")
print(f"Min Salary in training set: {X_train['Salary'].min():.2f}")
# Mean, max, and min values for Tax Deduction in the training set
print("\ntex Deduction Training Set Statistics:")
print(f"Mean Tax Deduction in training set: {y_train.mean():.2f}")
print(f"Max Tax Deduction in training set: {y_train.max():.2f}")
print(f"Average Tax Deduction in training set: {y_train.mean():.2f}")
print(f"Min Tax Deduction in training set: {y_train.min():.2f}")
#I display the first 5 predictions
print(f"Predicted values: {y_pred[:5]}")
# I used a simple if statement to determine if the predicted tax deductions are increasing or decreasing based on the sample test data
if sorted(y_pred)[-1] > sorted(y_pred)[0]:
print("Predicted tax deductions are increasing.")
else:
print("Predicted tax deductions are decreasing.")
# Visualize the regression line
plt.figure(figsize=(8, 6))
plt.scatter(X_test, y_test, color='blue', label='Actual Salary')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Predicted Salary (Regression Line)')
plt.title('Linear Regression: Tax Deduction vs Salary')
plt.xlabel('Salary')
plt.ylabel('Tax Deduction')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()