MLteach / visualizer.py
TrakyaliAi's picture
Update visualizer.py
2e37eb6 verified
Raw History Blame Contribute Delete
7.43 kB
# visualizer.py
import numpy as np
import plotly.graph_objects as go
from sklearn.datasets import make_classification, make_regression, make_blobs
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge, Lasso
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, IsolationForest
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.cluster import KMeans, AgglomerativeClustering
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.neural_network import MLPClassifier
def _get_classifier(algo_adi, param):
p = max(1, int(param))
if "Lojistik" in algo_adi:
return LogisticRegression(C=float(param) * 0.5)
elif "Karar Ağacı" in algo_adi:
return DecisionTreeClassifier(max_depth=p, random_state=42)
elif "Rastgele Orman" in algo_adi:
return RandomForestClassifier(n_estimators=30, max_depth=p, random_state=42)
elif "SVM" in algo_adi:
return SVC(kernel='rbf', C=float(param) * 0.5, probability=True, random_state=42)
elif "KNN" in algo_adi:
return KNeighborsClassifier(n_neighbors=p)
elif "Naive Bayes" in algo_adi:
return GaussianNB(var_smoothing=10**(-p))
elif "Sinir Ağları" in algo_adi:
return MLPClassifier(hidden_layer_sizes=(p * 8, p * 4), max_iter=200, random_state=42)
else:
return GradientBoostingClassifier(max_depth=min(6, p), n_estimators=40, random_state=42)
def generate_ml_plot(detay, algo_adi, n_samples, noise, param):
fig = go.Figure()
n_samples = int(n_samples)
noise = float(noise)
param = float(param)
if detay["tip"] == "Regresyon":
X, y = make_regression(n_samples=n_samples, n_features=1, noise=noise * 25.0, random_state=42)
x_raw = X.flatten()
if "Ridge" in algo_adi:
model = Ridge(alpha=param * 5.0)
elif "Lasso" in algo_adi:
model = Lasso(alpha=param * 2.0)
else:
deg = max(1, min(5, int(param)))
model = make_pipeline(PolynomialFeatures(degree=deg), LinearRegression())
model.fit(X, y)
x_sorted = np.linspace(x_raw.min(), x_raw.max(), 100).reshape(-1, 1)
y_sorted = model.predict(x_sorted)
fig.add_trace(go.Scatter(
x=x_raw.tolist(), y=y.tolist(), mode='markers', name='Veri Noktaları',
marker=dict(color='#818cf8', size=8, opacity=0.8)
))
fig.add_trace(go.Scatter(
x=x_sorted.flatten().tolist(), y=y_sorted.tolist(), mode='lines', name='Model Tahmini',
line=dict(color='#ef4444', width=3)
))
fig.update_layout(
title=f"{algo_adi} Tahmin Eğrisi",
xaxis=dict(title="Özellik (X)", autorange=True),
yaxis=dict(title="Hedef (y)", autorange=True)
)
elif detay["tip"] == "Kümeleme":
k_val = max(2, int(param))
X, _ = make_blobs(n_samples=n_samples, centers=4, cluster_std=noise * 2 + 0.5, random_state=42)
model = KMeans(n_clusters=k_val, random_state=42) if "K-Means" in algo_adi else AgglomerativeClustering(n_clusters=k_val)
preds = model.fit_predict(X)
fig.add_trace(go.Scatter(
x=X[:, 0].tolist(), y=X[:, 1].tolist(), mode='markers',
marker=dict(color=preds.tolist(), colorscale='Viridis', size=9, line=dict(width=1, color='white')),
name="Kümeler"
))
if "K-Means" in algo_adi:
centers = model.cluster_centers_
fig.add_trace(go.Scatter(
x=centers[:, 0].tolist(), y=centers[:, 1].tolist(), mode='markers',
marker=dict(color='#ef4444', size=14, symbol='x'),
name="Küme Merkezleri"
))
fig.update_layout(title=f"{algo_adi} (K={k_val}) Kümeleme Sonucu")
elif detay["tip"] == "Boyut İndirgeme":
n_feat = max(4, int(param) + 3)
X, y = make_classification(n_samples=n_samples, n_features=n_feat, n_informative=3, random_state=42)
if "PCA" in algo_adi:
X_2d = PCA(n_components=2).fit_transform(X)
else:
perp = min(40, max(5, int(param) * 4))
X_2d = TSNE(n_components=2, perplexity=min(perp, n_samples - 1), random_state=42).fit_transform(X)
fig.add_trace(go.Scatter(
x=X_2d[:, 0].tolist(), y=X_2d[:, 1].tolist(), mode='markers',
marker=dict(color=y.tolist(), colorscale='Plasma', size=8),
name="2D İzdüşüm"
))
fig.update_layout(title=f"{algo_adi} 2 Boyutlu İzdüşümü", xaxis_title="Bileşen 1", yaxis_title="Bileşen 2")
elif detay["tip"] == "Anomali Tespiti":
contam = max(0.02, min(0.35, param / 25.0))
X, _ = make_blobs(n_samples=n_samples, centers=1, cluster_std=noise + 0.5, random_state=42)
model = IsolationForest(contamination=contam, random_state=42)
preds = model.fit_predict(X)
colors = ['#ef4444' if p == -1 else '#818cf8' for p in preds]
fig.add_trace(go.Scatter(
x=X[:, 0].tolist(), y=X[:, 1].tolist(), mode='markers',
marker=dict(color=colors, size=8),
name="Veri Noktaları"
))
fig.update_layout(title=f"Isolation Forest Anomali Tespiti (Oran: %{int(contam*100)})")
else:
X, y = make_classification(
n_samples=n_samples, n_features=2, n_redundant=0,
n_informative=2, n_clusters_per_class=1, flip_y=noise * 0.35, random_state=42
)
clf = _get_classifier(algo_adi, param)
clf.fit(X, y)
acc = clf.score(X, y)
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 40), np.linspace(y_min, y_max, 40))
if hasattr(clf, "predict_proba"):
Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
else:
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig.add_trace(go.Contour(
x=np.linspace(x_min, x_max, 40).tolist(),
y=np.linspace(y_min, y_max, 40).tolist(),
z=Z.tolist(),
colorscale=[[0, 'rgba(99, 102, 241, 0.25)'], [1, 'rgba(52, 211, 153, 0.25)']],
showscale=False,
contours=dict(coloring='fill', showlines=True),
name="Karar Sınırı"
))
colors = ['#6366f1' if label == 0 else '#10b981' for label in y]
fig.add_trace(go.Scatter(
x=X[:, 0].tolist(), y=X[:, 1].tolist(), mode='markers',
marker=dict(color=colors, size=8, line=dict(width=1, color='#1e1e2e')),
name="Sınıflar"
))
fig.update_layout(
title=f"{algo_adi} Karar Sınırı (Doğruluk: %{acc*100:.1f})",
xaxis_title="Özellik 1", yaxis_title="Özellik 2"
)
fig.update_layout(
template="plotly_dark",
margin=dict(l=20, r=20, t=45, b=20),
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)
return fig