# 1. استدعاء المكتبات [cite: 126, 130, 131, 132, 134]
import pandas as pd
import numpy as np
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
# Hide the interactive navigation toolbar (home/pan/zoom/save) in the plot window.
mpl.rcParams["toolbar"] = "None"
# Ensure Arabic prints don't crash on Windows consoles using legacy codepages.
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
def _hide_toolbar(fig) -> None:
mgr = getattr(fig.canvas, "manager", None)
tb = getattr(mgr, "toolbar", None)
if tb is None:
return
# Qt: setVisible/hide. Tk: pack_forget. (Other backends: best-effort.)
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
# 2. قراءة البيانات (تأكد من تعديل المسار ليطابق مسار الملف في حاسوبك)
path = "C:\\Users\\pc\\OneDrive\\Desktop\\Intro Ai ii.xlsx"
file = pd.read_excel(path, "Sheet3")
X = file.iloc[:, :-1].values # [cite: 128]
Y = file.iloc[:, -1].values # [cite: 129]
# 3. فصل البيانات إلى بيانات تدريب وبيانات اختبار [cite: 130]
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
# 4. ضبط مقياس الميزات (Feature Scaling) [cite: 131]
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# 5. إنشاء وتدريب المصنف (الخطي) [cite: 132]
# يمكنك تغيير 'linear' إلى 'rbf' إذا أردت تصنيفاً غير خطي كما في الشريحة 26 [cite: 135]
classifier = SVC(kernel='linear', random_state=0)
classifier.fit(X_train, y_train)
# 6. اختبار المصنف وطباعة النتائج [cite: 133]
Y_predict = classifier.predict(X_test)
print("مقارنة التنبؤات بالنتائج الحقيقية:")
print(np.concatenate((Y_predict.reshape(len(Y_predict), 1), y_test.reshape(len(y_test), 1)), 1))
# 7. التمثيل المرئي لنتائج التدريب [cite: 134]
# PLOT_TOOLBAR_HIDDEN
X_set, y_set = sc.inverse_transform(X_train), y_train
X1, X2 = np.meshgrid(
np.arange(start=X_set[:, 0].min() - 3, stop=X_set[:, 0].max() + 3, step=0.25),
np.arange(start=X_set[:, 1].min() - 3, stop=X_set[:, 1].max() + 3, step=0.25),
)
plt.contourf(
X1,
X2,
classifier.predict(sc.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape),
alpha=0.75,
cmap=ListedColormap(('salmon', 'dodgerblue')),
)
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(
X_set[y_set == j, 0],
X_set[y_set == j, 1],
c=ListedColormap(('salmon', 'dodgerblue'))(i),
label=j,
)
plt.title('SVM (Training set)')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
_hide_toolbar(plt.gcf())
plt.show()