我一直在想這個,但不知道該怎么做。我有一個二進制不平衡資料,并想svm用來選擇最接近的多數資料點的子集support vector。此后,我可以在這個“平衡”資料上擬合一個二元分類器。
為了說明我的意思,MWE:
# packages import
from collections import Counter
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
import numpy as np
from sklearn.svm import SVC
import seaborn as sns
# 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)
# class distribution summary
print(Counter(y))
Counter({0: 91, 1: 9})
# fit svm model
svc_model = SVC(kernel='linear', random_state=32)
svc_model.fit(X, y)
plt.figure(figsize=(10, 8))
# Plotting our two-features-space
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, s=50)
# Constructing a hyperplane using a formula.
w = svc_model.coef_[0] # w consists of 2 elements
b = svc_model.intercept_[0] # b consists of 1 element
x_points = np.linspace(-1, 1) # generating x-points from -1 to 1
y_points = -(w[0] / w[1]) * x_points - b / w[1] # getting corresponding y-points
# Plotting a red hyperplane
plt.plot(x_points, y_points, c='r')

這兩個類被超平面很好地分開。我們可以看到support vectors兩個類的 (甚至更好class 1)。
由于少數人class 0有9-data-points,我想class 0通過選擇它support vectors的 和8最接近它的其他資料點來進行下采樣。這樣類分布就會{0: 9, 1: 9}忽略 的所有其他資料點0。然后我將使用它來擬合像LR(甚至SVC)這樣的二元分類器。
我的問題是如何選擇class 0最接近班級的那些資料點support vector,同時考慮到一種與少數資料點取得平衡的方法class 1。
uj5u.com熱心網友回復:
這可以如下實作:獲取類 0 的支持向量 ( sv0),遍歷類 0 ( X[y == 0]) 中的所有資料點,計算到支持向量表示的點的距離 ( d),對它們進行排序,取 9 與最小值,并將它們與類 1 的點連接以創建下采樣資料 ( X_ds, y_ds)。
sv0 = svc_model.support_vectors_[0]
distances = []
for i, x in enumerate(X[y == 0]):
d = np.linalg.norm(sv0 - x)
distances.append((i, d))
distances.sort(key=lambda tup: tup[1])
index = [i for i, d in distances][:9]
X_ds = np.concatenate((X[y == 0][index], X[y == 1]))
y_ds = np.concatenate((y[y == 0][index], y[y == 1]))
plt.plot(x_points[19:-29], y_points[19:-29], c='r')
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, s=50)
plt.scatter(X_ds[y_ds == 0][:,0], X_ds[y_ds == 0][:,1], color='yellow', alpha=0.4)

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/462414.html
