import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# Hide the interactive navigation toolbar (home/pan/zoom/save) in the plot window.
mpl.rcParams["toolbar"] = "None"
def _hide_toolbar(fig) -> None:
mgr = getattr(fig.canvas, "manager", None)
tb = getattr(mgr, "toolbar", None)
if tb is None:
return
for m in ("setVisible", "hide", "pack_forget"):
fn = getattr(tb, m, None)
if callable(fn):
try:
fn(False) if m == "setVisible" else fn()
except Exception:
pass
# ================== قراءة البيانات ==================
# The sheet has its real headers starting on the 2nd row and in columns D-F.
dataset = pd.read_excel(
"C:\\Users\\pc\\OneDrive\\Desktop\\Antro Ai ii.xlsx",
header=2,
usecols="D:F",
).dropna(how="all")
# Coerce to numeric to avoid mixed string/number columns from Excel causing matplotlib's
# categorical converter to crash (e.g., "6.5" as text in some rows).
x_col = pd.to_numeric(dataset["Level"], errors='coerce') # Level
y_col = pd.to_numeric(dataset["Salary"], errors='coerce') # Salary
mask = x_col.notna() & y_col.notna()
X = x_col[mask].to_numpy().reshape(-1, 1)
y = y_col[mask].to_numpy()
# PLOT_ORIGINAL_TOOLBAR_HIDDEN
plt.scatter(X, y)
plt.title('Salaries Vs Position')
plt.xlabel('Position Level')
plt.ylabel('Salary')
_hide_toolbar(plt.gcf())
plt.show()
# ================== رسم البيانات الأصلية ==================
# ================== Linear Regression ==================
lin_reg = LinearRegression()
lin_reg.fit(X, y)
# PLOT_LINEAR_TOOLBAR_HIDDEN
plt.scatter(X, y)
plt.plot(X, lin_reg.predict(X))
plt.title('Linear Regression')
plt.xlabel('Position Level')
plt.ylabel('Salary')
_hide_toolbar(plt.gcf())
plt.show()
linear_prediction = lin_reg.predict([[6.5]])
print("Linear Regression Prediction at level 6.5:", linear_prediction)
# ================== Polynomial Regression ==================
poly_reg = PolynomialFeatures(degree=4)
X_poly = poly_reg.fit_transform(X)
lin_reg2 = LinearRegression()
lin_reg2.fit(X_poly, y)
# PLOT_POLY_TOOLBAR_HIDDEN
X_grid = np.arange(X.min(), X.max(), 0.1).reshape(-1, 1)
plt.scatter(X, y)
plt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)))
plt.title('Polynomial Regression')
plt.xlabel('Position Level')
plt.ylabel('Salary')
_hide_toolbar(plt.gcf())
plt.show()
# رسم Polynomial بدقة عالية
poly_prediction = lin_reg2.predict(poly_reg.fit_transform([[6.5]]))
print("Polynomial Regression Prediction at level 6.5:", poly_prediction)