[데이터 전처리] 데이터 불균형
Y
Yerim
- ML
- DataAnalysis
n0 = 200; n1 = 20
rv1 = sp.stats.multivariate_normal([-1, 0], [[1, 0], [0, 1]])
rv2 = sp.stats.multivariate_normal([+1, 0], [[1, 0], [0, 1]])
X0 = rv1.rvs(n0, random_state=0)
X1 = rv2.rvs(n1, random_state=0)
X_imb = np.vstack([X0, X1])
y_imb = np.hstack([np.zeros(n0), np.ones(n1)])
x1min = -4; x1max = 4
x2min = -2; x2max = 2
xx1 = np.linspace(x1min, x1max, 1000)
xx2 = np.linspace(x2min, x2max, 1000)
X1, X2 = np.meshgrid(xx1, xx2)
def classification_result2(X, y, title=""):
plt.contour(X1, X2, rv1.pdf(np.dstack([X1, X2])), levels=[0.05], linestyles="dashed")
plt.contour(X1, X2, rv2.pdf(np.dstack([X1, X2])), levels=[0.05], linestyles="dashed")
model = SVC(kernel="linear", C=1e4, random_state=0).fit(X, y)
Y = np.reshape(model.predict(np.array([X1.ravel(), X2.ravel()]).T), X1.shape)
plt.scatter(X[y == 0, 0], X[y == 0, 1], marker='x', label="0 클래스")
plt.scatter(X[y == 1, 0], X[y == 1, 1], marker='o', label="1 클래스")
plt.contour(X1, X2, Y, colors='k', levels=[0.5])
y_pred = model.predict(X)
plt.xlim(-4, 4)
plt.ylim(-3, 3)
plt.xlabel("x1")
plt.ylabel("x2")
plt.title(title)
return modelfrom imblearn.under_sampling import RandomUnderSampler
import matplotlib.pyplot as plt
from sklearn.svm import SVC
X_samp, y_samp = RandomUnderSampler(random_state=0).fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.under_sampling import TomekLinks
import matplotlib.pyplot as plt
tl = TomekLinks()
X_samp, y_samp = tl.fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.under_sampling import CondensedNearestNeighbour
import matplotlib.pyplot as plt
cnn = CondensedNearestNeighbour(random_state=0)
X_samp, y_samp = cnn.fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.under_sampling import OneSidedSelection
import matplotlib.pyplot as plt
oss = OneSidedSelection(random_state=0)
X_samp, y_samp = oss.fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.under_sampling import EditedNearestNeighbours
import matplotlib.pyplot as plt
enn = EditedNearestNeighbours(kind_sel="all", n_neighbors=5)
X_samp, y_samp = enn.fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.under_sampling import NeighbourhoodCleaningRule
import matplotlib.pyplot as plt
ncr = NeighbourhoodCleaningRule(kind_sel="all", n_neighbors=5)
X_samp, y_samp = ncr.fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.over_sampling import RandomOverSampler
import matplotlib.pyplot as plt
X_samp, y_samp = RandomOverSampler(random_state=0).fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.over_sampling import ADASYN
import matplotlib.pyplot as plt
X_samp, y_samp = ADASYN(random_state=0).fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.over_sampling import SMOTE
import matplotlib.pyplot as plt
X_samp, y_samp = SMOTE(random_state=0).fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.combine import SMOTEENN
import matplotlib.pyplot as plt
X_samp, y_samp = SMOTEENN(random_state=0).fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)from imblearn.combine import SMOTETomek
import matplotlib.pyplot as plt
X_samp, y_samp = SMOTETomek(random_state=0).fit_resample(X_imb, y_imb)
plt.subplot(121)
classification_result2(X_imb, y_imb)
plt.subplot(122)
model_samp = classification_result2(X_samp, y_samp)import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from sklearn.svm import SVC
n0 = 200; n1 = 20
rv1 = sp.stats.multivariate_normal([-1, 0], [[1, 0], [0, 1]])
rv2 = sp.stats.multivariate_normal([+1, 0], [[1, 0], [0, 1]])
X0 = rv1.rvs(n0, random_state=0)
X1 = rv2.rvs(n1, random_state=0)
X_imb = np.vstack([X0, X1])
y_imb = np.hstack([np.zeros(n0), np.ones(n1)])
x1min = -4; x1max = 4
x2min = -2; x2max = 2
xx1 = np.linspace(x1min, x1max, 1000)
xx2 = np.linspace(x2min, x2max, 1000)
X1, X2 = np.meshgrid(xx1, xx2)
def classification_result2(X, y, title=""):
plt.contour(X1, X2, rv1.pdf(np.dstack([X1, X2])), levels=[0.05], linestyles="dashed")
plt.contour(X1, X2, rv2.pdf(np.dstack([X1, X2])), levels=[0.05], linestyles="dashed")
model = SVC(kernel="linear", C=1e4, random_state=0).fit(X, y)
Y = np.reshape(model.predict(np.array([X1.ravel(), X2.ravel()]).T), X1.shape)
plt.scatter(X[y == 0, 0], X[y == 0, 1], marker='x', label="0 클래스")
plt.scatter(X[y == 1, 0], X[y == 1, 1], marker='o', label="1 클래스")
plt.contour(X1, X2, Y, colors='k', levels=[0.5])
y_pred = model.predict(X)
plt.xlim(-4, 4)
plt.ylim(-3, 3)
plt.xlabel("x1")
plt.ylabel("x2")
plt.title(title)
return model# data/label, 학습/평가 데이터로 구분
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_imb, y_imb)
print("X_train.shape: {}".format(X_train.shape))
print("X_test.shape: {}".format(X_test.shape))
print("y_train.shape: {}".format(y_train.shape))
print("y_test.shape: {}".format(y_test.shape))
# 불균형 테스트
from sklearn.neighbors import KNeighborsClassifier as KNN
from sklearn.metrics import *
# Assuming you have X_train, y_train, X_test, and y_test defined
kNN_model = KNN(n_neighbors=11).fit(X_train, y_train)
pred_Y = kNN_model.predict(X_test)
print('recall_score: ', recall_score(y_test, pred_Y))
print('accuracy_score: ', accuracy_score(y_test, pred_Y))
# 비용 민감 모델 적용
from sklearn.linear_model import LogisticRegression
# 인스턴스화
model = LogisticRegression(max_iter=100000).fit(X_train, y_train)
y_pred = model.predict(X_test)
print('recall_score: ', recall_score(y_test, y_pred))
print('accuracy_score: ', accuracy_score(y_test, y_pred))
# cut off value 조정
probs = model.predict_proba(X_test)
probs = pd.DataFrame(probs, columns=model.classes_)
cut_off_value = 0.3
pred_y = 2 * (probs.iloc[:, -1] >= cut_off_value) - 1
print('recall_score: ', recall_score(y_test, y_pred))
print('accuracy_score: ', accuracy_score(y_test, y_pred))def cost_sensitive_model(model, cut_off_value, X_test, y_test):
probs = model.predict_proba(X_test)
probs = pd.DataFrame(probs, columns=model.classes_)
y_pred = 2 * (probs.iloc[:, -1] >= cut_off_value) - 1
recall = recall_score(y_test, y_pred, average='weighted')
accuracy = accuracy_score(y_test, y_pred)
return recall, accuracy
from matplotlib import pyplot as plt
import numpy as np
%matplotlib inline
model = LogisticRegression(max_iter=100000).fit(X_train, y_train)
cut_off_value_list = np.linspace(0, 1, 101)
recall_list = []
accuracy_list = []
for c in cut_off_value_list:
recall, accuracy = cost_sensitive_model(model, c, X_test, y_test)
recall_list.append(recall)
accuracy_list.append(accuracy)
plt.figure(figsize=(12, 8))
plt.plot(cut_off_value_list, recall_list, label = 'recall')
plt.plot(cut_off_value_list, accuracy_list, label='accuracy')
plt.legend()
plt.show()import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from sklearn.svm import SVC
n0 = 200; n1 = 20
rv1 = sp.stats.multivariate_normal([-1, 0], [[1, 0], [0, 1]])
rv2 = sp.stats.multivariate_normal([+1, 0], [[1, 0], [0, 1]])
X0 = rv1.rvs(n0, random_state=0)
X1 = rv2.rvs(n1, random_state=0)
X_imb = np.vstack([X0, X1])
y_imb = np.hstack([np.zeros(n0), np.ones(n1)])
x1min = -4; x1max = 4
x2min = -2; x2max = 2
xx1 = np.linspace(x1min, x1max, 1000)
xx2 = np.linspace(x2min, x2max, 1000)
X1, X2 = np.meshgrid(xx1, xx2)
def classification_result2(X, y, title=""):
plt.contour(X1, X2, rv1.pdf(np.dstack([X1, X2])), levels=[0.05], linestyles="dashed")
plt.contour(X1, X2, rv2.pdf(np.dstack([X1, X2])), levels=[0.05], linestyles="dashed")
model = SVC(kernel="linear", C=1e4, random_state=0).fit(X, y)
Y = np.reshape(model.predict(np.array([X1.ravel(), X2.ravel()]).T), X1.shape)
plt.scatter(X[y == 0, 0], X[y == 0, 1], marker='x', label="0 클래스")
plt.scatter(X[y == 1, 0], X[y == 1, 1], marker='o', label="1 클래스")
plt.contour(X1, X2, Y, colors='k', levels=[0.5])
y_pred = model.predict(X)
plt.xlim(-4, 4)
plt.ylim(-3, 3)
plt.xlabel("x1")
plt.ylabel("x2")
plt.title(title)
return model# data/label, 학습/평가 데이터로 구분
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_imb, y_imb)
# 불균형 테스트
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import *
KNN_model = KNeighborsClassifier(n_neighbors=11).fit(X_train, y_train)
y_pred = KNN_model.predict(X_test)
print('recall_score: ', recall_score(y_test, y_pred))
print('accuracy_score: ', accuracy_score(y_test, y_pred))
# 비용 민감 모델
from sklearn.svm import SVC
model = SVC().fit(X_train, y_train)
y_pred = model.predict(X_test)
print('recall_score: ', recall_score(y_test, y_pred))
print('accuracy_score: ', accuracy_score(y_test, y_pred))
# 조정
model = SVC(class_weight={1: 8, 0: 1}).fit(X_train, y_train)
y_pred = model.predict(X_test)
print('recall_score: ', recall_score(y_test, y_pred))
print('accuracy_score: ', accuracy_score(y_test, y_pred))ensemble.BalancedRandomForestClassifier(n_estimators=100, *, criterion='gini',
max_depth=None, min_samples_split=2, min_samples_leaf=1,
min_weight_fraction_leaf=0.0, max_features='sqrt',
max_leaf_nodes=None, min_impurity_decrease=0.0, bootstrap='warn',
oob_score=False, sampling_strategy='warn', replacement='warn',
n_jobs=None, random_state=None, verbose=0, warm_start=False,
class_weight=None, ccp_alpha=0.0, max_samples=None, monotonic_cst=None)from imblearn.ensemble import BalancedRandomForestClassifier
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000, n_classes=3,
n_informative=4, weights=[0.2, 0.3, 0.5],
random_state=0)
clf = BalancedRandomForestClassifier(
sampling_strategy='all', replacement=True, max_depth=2, random_state=0,
bootstrap=False
)
# Fit the classifier on your data
clf.fit(X, y)
# Now you can access the feature importances
print(clf.feature_importances_)
# Make a prediction (Note: This is just to demonstrate; you may need actual test data)
print(clf.predict([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]))imblearn.ensemble.EasyEnsembleClassifier(n_estimators=10, estimator=None, *,
warm_start=False, sampling_strategy='auto', replacement=False,
n_jobs=None, random_state=None, verbose=0)from collections import Counter
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from imblearn.ensemble import EasyEnsembleClassifier
X, y = make_classification(n_classes=2, class_sep=2,
n_features=20, n_clusters_per_class=1,
n_samples=1000, random_state=10)
print('Original dataset shape %s' %Counter(y))
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Instantiate the EasyEnsembleClassifier
eec = EasyEnsembleClassifier()
# Fit the classifier on your training data
eec.fit(X_train, y_train)
# Now you can use it for predictions
y_pred = eec.predict(X_test)
print(confusion_matrix(y_test, y_pred))