我試圖弄清楚如何繪制決策邊界線,只選擇幾個中間值而不是整個分隔線,以便它大致跨越觀測值跨越的 y 范圍。
目前,我手動反復選擇不同的邊界并進行視覺評估,直到出現“好看的分隔符”。
MWE:
from collections import Counter
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
import numpy as np
from sklearn.svm import SVC
# sample data
X, y = make_classification(n_samples=100, n_features=2, n_redundant=0,
n_clusters_per_class=1, weights=[0.9], flip_y=0, random_state=1)
# fit svm model
svc_model = SVC(kernel='linear', random_state=32)
svc_model.fit(X, y)
# Constructing a hyperplane using a formula.
w = svc_model.coef_[0]
b = svc_model.intercept_[0]
x_points = np.linspace(-1, 1)
y_points = -(w[0] / w[1]) * x_points - b / w[1]
圖1:
決策邊界線跨度更大的范圍,導致觀察結果在視覺上看起來幾乎像一條線時被“壓扁”
plt.figure(figsize=(10, 8))
# Plotting our two-features-space
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, s=50)
# Plotting a red hyperplane
plt.plot(x_points, y_points, c='r')

圖 2
手動使用點來確定視覺上的合適度(x_points[19:-29], y_points[19:-29]):
plt.figure(figsize=(10, 8))
# Plotting our two-features-space
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, s=50)
# Plotting a red hyperplane
plt.plot(x_points[19:-29], y_points[19:-29], c='r')

如何自動化“良好擬合”的值范圍?例如,這適用于n_samples=100資料點,但不適用于n_samples=1000.
uj5u.com熱心網友回復:
x_points您可以反轉線性方程并直接指定您想要的界限,而不是從 -1 到 1 y_points:
y_points = np.linspace(X[:, 1].min(), X[:, 1].max())
x_points = -(w[1] * y_points b) / w[0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473872.html
標籤:Python 麻木的 matplotlib
