import numpy as np
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
# 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
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
# 1. تجهيز البيانات (مثال: Voltage و Temperature)
# في المحاضرة يتم استيرادها من ملف، هنا نضع مثالاً توضيحياً
X = np.array([[0.1], [0.2], [0.3], [0.4], [0.5], [0.6], [0.7], [0.8], [0.9]])
y = np.array([15, 18, 25, 35, 45, 60, 80, 95, 110])
# 2. تحجيم البيانات (ضروري جداً في SVR)
sc_X = StandardScaler()
sc_y = StandardScaler()
X_scaled = sc_X.fit_transform(X)
y_scaled = sc_y.fit_transform(y.reshape(-1, 1))
# 3. بناء وتدريب موديل SVR بنواة rbf
regressor = SVR(kernel = 'rbf')
regressor.fit(X_scaled, y_scaled.ravel())
# 4. التنبؤ بقيمة جديدة (مثلاً عند فولت 0.75)
prediction_scaled = regressor.predict(sc_X.transform([[0.75]]))
# إعادة القيمة لأصلها (قبل التحجيم) لقراءتها كدرجة حرارة
prediction = sc_y.inverse_transform(prediction_scaled.reshape(-1, 1))
print(f"التنبؤ بدرجة الحرارة عند 0.75 فولت هو: {prediction[0][0]}")
# 5. الرسم البياني للنتائج
# PLOT_TOOLBAR_HIDDEN
plt.scatter(X, y, color='red', label='the points')
plt.plot(
X,
sc_y.inverse_transform(regressor.predict(X_scaled).reshape(-1, 1)),
color='blue',
label='the Regression',
)
plt.title('Temperature Calibration (SVR)')
plt.xlabel('Voltage (V)')
plt.ylabel('Temperature (deg C)')
plt.legend()
_hide_toolbar(plt.gcf())
plt.show()