偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

機(jī)器學(xué)習(xí)中處理不平衡數(shù)據(jù)集的五種方法

人工智能 機(jī)器學(xué)習(xí)
不平衡數(shù)據(jù)集是指在分類(lèi)任務(wù)中,不同類(lèi)別的樣本數(shù)量差異顯著的數(shù)據(jù)集,通常表現(xiàn)為少數(shù)類(lèi)樣本遠(yuǎn)少于多數(shù)類(lèi)樣本。這樣的數(shù)據(jù)集在現(xiàn)實(shí)生活中很常見(jiàn),比如欺詐檢測(cè)、醫(yī)療診斷、故障預(yù)測(cè)等場(chǎng)景。

大家好,我是小寒

今天給大家分享處理不平衡數(shù)據(jù)集的常用方法。

在開(kāi)始之前,我們先來(lái)了解一下什么是不平衡的數(shù)據(jù)集。

不平衡數(shù)據(jù)集是指在分類(lèi)任務(wù)中,不同類(lèi)別的樣本數(shù)量差異顯著的數(shù)據(jù)集,通常表現(xiàn)為少數(shù)類(lèi)樣本遠(yuǎn)少于多數(shù)類(lèi)樣本。這樣的數(shù)據(jù)集在現(xiàn)實(shí)生活中很常見(jiàn),比如欺詐檢測(cè)、醫(yī)療診斷、故障預(yù)測(cè)等場(chǎng)景。

例如,在一個(gè)包含 10,000 個(gè)實(shí)例的數(shù)據(jù)集中,95% 屬于一個(gè)類(lèi)(類(lèi) 0),只有 5% 屬于另一個(gè)類(lèi)(類(lèi) 1),很明顯,模型可能會(huì)高度關(guān)注多數(shù)類(lèi),而經(jīng)常完全忽略少數(shù)類(lèi)。

不平衡數(shù)據(jù)的問(wèn)題

在不平衡的數(shù)據(jù)集中,多數(shù)類(lèi)別主導(dǎo)著模型的預(yù)測(cè),導(dǎo)致少數(shù)類(lèi)別的預(yù)測(cè)性能較差。

例如,如果 95% 的數(shù)據(jù)被標(biāo)記為 0 類(lèi),則將所有實(shí)例預(yù)測(cè)為 0 類(lèi)可獲得 95% 的準(zhǔn)確率,即使 1 類(lèi)預(yù)測(cè)完全不正確。

示例:

考慮一個(gè)欺詐檢測(cè)系統(tǒng),其中 99% 的交易是合法的,只有 1% 是欺詐的。預(yù)測(cè)所有交易均為合法的模型將達(dá)到 99% 的準(zhǔn)確率,但無(wú)法檢測(cè)到任何欺詐行為,使其無(wú)法達(dá)到預(yù)期目的。

讓我們通過(guò)一個(gè)例子來(lái)可視化不平衡數(shù)據(jù)

import numpy as np
import pandas as pd
import plotly.express as px
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
import plotly.figure_factory as ff

# Generate imbalanced data
n_samples = 10000
class_0_ratio = 0.95
n_class_0 = int(n_samples * class_0_ratio)
n_class_1 = n_samples - n_class_0

X_class_0 = np.random.randn(n_class_0, 2)
X_class_1 = np.random.randn(n_class_1, 2) + 2  # Shift class 1 data

y_class_0 = np.zeros(n_class_0)
y_class_1 = np.ones(n_class_1)

X = np.concatenate((X_class_0, X_class_1), axis=0)
y = np.concatenate((y_class_0, y_class_1), axis=0)

# Create a Pandas DataFrame for easier handling
df = pd.DataFrame(X, columns=['Feature 1', 'Feature 2'])
df['Target'] = y

# Visualize class distribution
fig = px.histogram(df, x='Target', title='Class Distribution', width=800, height=600)
fig.update_layout(title_x=0.5)
fig.update_xaxes(tickvals=[0, 1], ticktext=['Class 0', 'Class 1'])
fig.show()

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train a Logistic Regression model
model = LogisticRegression()
model.fit(X_train, y_train)

# Make predictions on the test set
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)

print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1-score: {f1:.4f}")

# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
fig = ff.create_annotated_heatmap(cm, x=['Predicted 0', 'Predicted 1'], y=['True 0', 'True 1'])
fig.update_layout(title_text='Confusion Matrix', width=800, height=600, title_x=0.5)
fig.show()

此代碼生成一個(gè)不平衡的數(shù)據(jù)集,其中 95% 的實(shí)例被標(biāo)記為類(lèi) 0,只有 5% 被標(biāo)記為類(lèi) 1。

當(dāng)我們可視化類(lèi)別分布時(shí),我們會(huì)看到兩個(gè)類(lèi)別之間的明顯不平衡。

圖片圖片

Accuracy: 0.9815
Precision: 0.8451
Recall: 0.6977
F1-score: 0.7643

混淆矩陣顯示,雖然準(zhǔn)確率很高,但少數(shù)類(lèi)(類(lèi)1)的準(zhǔn)確率和召回率要低得多。該模型偏向多數(shù)類(lèi)。

圖片圖片

import plotly.express as px

df["Target"] = df["Target"].astype(str)
fig = px.scatter(df, x='Feature 1', y='Feature 2', color='Target', title='Original Dataset')
fig.update_layout(title_x=0.5, width=800, height=600)
fig.show()

圖片圖片

處理不平衡數(shù)據(jù)的技術(shù)

1.隨機(jī)欠采樣

隨機(jī)欠采樣是一種通過(guò)減少多數(shù)類(lèi)樣本的數(shù)量來(lái)平衡類(lèi)分布的方法。

具體做法是隨機(jī)選擇部分多數(shù)類(lèi)樣本并將其移除,使得多數(shù)類(lèi)和少數(shù)類(lèi)的樣本數(shù)量接近平衡。

優(yōu)點(diǎn)

  • 簡(jiǎn)單易行,不需要復(fù)雜的算法。
  • 減少了數(shù)據(jù)集的規(guī)模,降低了計(jì)算成本。

缺點(diǎn)

  • 可能丟失重要的多數(shù)類(lèi)信息,導(dǎo)致模型性能下降。
  • 縮小的數(shù)據(jù)集可能導(dǎo)致模型對(duì)多數(shù)類(lèi)的泛化能力變差。
from imblearn.under_sampling import RandomUnderSampler
from collections import Counter

# Use RandomUnderSampler to balance the dataset
undersampler = RandomUnderSampler(sampling_strategy='auto', random_state=42)
X_resampled, y_resampled = undersampler.fit_resample(X, y)

# Check the original class distribution
print("Original class distribution:", Counter(y))
# Check the new class distribution after undersampling
print("New class distribution after undersampling:", Counter(y_resampled))

X_train, X_test, y_train, y_test = train_test_split(X_resampled, y_resampled, test_size=0.2, random_state=42)

# Train a simple logistic regression model
model = LogisticRegression(solver='liblinear')
model.fit(X_train, y_train)

# Make predictions
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy: {accuracy:.4f}")

# Distribution of undersampled data
df_resampled = pd.DataFrame(X_resampled, columns=['Feature 1', 'Feature 2'])
df_resampled['Target'] = y_resampled

df_resampled["Target"] = df_resampled["Target"].astype(str)
fig = px.scatter(df_resampled, x='Feature 1', y='Feature 2', color='Target', title='Undersampled Dataset')
fig.update_layout(title_x=0.5, width=800, height=600)
fig.show()

圖片圖片

2.隨機(jī)過(guò)采樣

隨機(jī)過(guò)采樣通過(guò)增加少數(shù)類(lèi)樣本的數(shù)量來(lái)平衡類(lèi)分布。

常見(jiàn)的做法是隨機(jī)復(fù)制少數(shù)類(lèi)的樣本,直到少數(shù)類(lèi)樣本的數(shù)量與多數(shù)類(lèi)樣本的數(shù)量相等。

優(yōu)點(diǎn)

  • 不會(huì)丟失數(shù)據(jù),不像欠采樣那樣丟失多數(shù)類(lèi)的樣本。
  • 在數(shù)據(jù)較少時(shí),可以通過(guò)增加樣本數(shù)量提高模型的學(xué)習(xí)效果。

缺點(diǎn)

  • 由于重復(fù)樣本的存在,可能導(dǎo)致模型過(guò)擬合少數(shù)類(lèi)樣本。
from imblearn.over_sampling import RandomOverSampler

# Check the original class distribution
original_class_distribution = Counter(y)
print("Original class distribution:", original_class_distribution)

# Initialize RandomOverSampler
oversampler = RandomOverSampler(sampling_strategy='auto', random_state=42)

# Apply random oversampling to balance the dataset
X_oversampled, y_oversampled = oversampler.fit_resample(X, y)

# Check the new class distribution after oversampling
new_class_distribution = Counter(y_oversampled)
print("New class distribution after oversampling:", new_class_distribution)

X_train, X_test, y_train, y_test = train_test_split(X_oversampled, y_oversampled, test_size=0.2, random_state=42)

# Train a simple logistic regression model
model = LogisticRegression(solver='liblinear')
model.fit(X_train, y_train)

# Make predictions
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy: {accuracy:.4f}")

df_resampled = pd.DataFrame(X_oversampled, columns=['Feature 1', 'Feature 2'])
df_resampled['Target'] = y_oversampled

df_resampled["Target"] = df_resampled["Target"].astype(str)
fig = px.scatter(df_resampled, x='Feature 1', y='Feature 2', color='Target', title='Oversampled Dataset')
fig.update_layout(title_x=0.5, width=800, height=600)
fig.show()

圖片圖片

3.SMOTE

SMOTE 是一種合成過(guò)采樣方法,通過(guò)生成新的少數(shù)類(lèi)樣本來(lái)平衡數(shù)據(jù)集。

它不是簡(jiǎn)單地復(fù)制現(xiàn)有的少數(shù)類(lèi)樣本,而是通過(guò)對(duì)現(xiàn)有少數(shù)類(lèi)樣本的特征進(jìn)行插值,創(chuàng)建新樣本。

具體來(lái)說(shuō),SMOTE 從少數(shù)類(lèi)樣本中選取一個(gè)樣本和其最近鄰樣本,在它們之間生成新的合成樣本。

優(yōu)點(diǎn)

  • 通過(guò)生成新樣本代替簡(jiǎn)單復(fù)制,緩解了過(guò)擬合的問(wèn)題。
  • 利用插值方法生成多樣化的少數(shù)類(lèi)樣本,擴(kuò)展了少數(shù)類(lèi)樣本的分布。

缺點(diǎn)

  • 生成的合成樣本可能落在錯(cuò)誤的決策邊界上,尤其是在樣本分布不清晰時(shí)。
  • 對(duì)高維數(shù)據(jù)的效果不佳,因?yàn)楦呔S數(shù)據(jù)中的樣本通常稀疏,插值生成的樣本可能不具有代表性。
from imblearn.over_sampling import SMOTE

# Check the original class distribution
original_class_distribution = Counter(y)
print("Original class distribution:", original_class_distribution)

# Initialize SMOTE
smote = SMOTE(sampling_strategy='auto', random_state=42)

# Apply SMOTE to balance the dataset
X_smote, y_smote = smote.fit_resample(X, y)

# Check the new class distribution after SMOTE
new_class_distribution = Counter(y_smote)
print("New class distribution after SMOTE:", new_class_distribution)

X_train, X_test, y_train, y_test = train_test_split(X_smote, y_smote, test_size=0.2, random_state=42)

# Train a simple logistic regression model
model = LogisticRegression(solver='liblinear')
model.fit(X_train, y_train)

# Make predictions
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy: {accuracy:.4f}")

df_resampled = pd.DataFrame(X_smote, columns=['Feature 1', 'Feature 2'])
df_resampled['Target'] = y_smote

df_resampled["Target"] = df_resampled["Target"].astype(str)
fig = px.scatter(df_resampled, x='Feature 1', y='Feature 2', color='Target', title='SMOTE Dataset')
fig.update_layout(title_x=0.5, width=800, height=600)
fig.show()
df_resampled["Target"].value_counts()

圖片圖片

4.成本敏感型學(xué)習(xí)

成本敏感型學(xué)習(xí)通過(guò)為分類(lèi)錯(cuò)誤分配不同的成本來(lái)解決數(shù)據(jù)不平衡問(wèn)題。

在不平衡數(shù)據(jù)集中,錯(cuò)分少數(shù)類(lèi)的代價(jià)通常比多數(shù)類(lèi)更高。成本敏感型學(xué)習(xí)通過(guò)在損失函數(shù)中引入成本矩陣來(lái)調(diào)整模型,使得少數(shù)類(lèi)的錯(cuò)分類(lèi)損失更大,從而引導(dǎo)模型更加關(guān)注少數(shù)類(lèi)。

優(yōu)點(diǎn)

  • 不需要對(duì)數(shù)據(jù)進(jìn)行重采樣,可以直接在模型訓(xùn)練中融入不平衡問(wèn)題。
  • 可以靈活調(diào)整不同錯(cuò)誤分類(lèi)的成本,適應(yīng)不同場(chǎng)景的需求。

缺點(diǎn):

  • 成本矩陣的設(shè)置需要根據(jù)實(shí)際問(wèn)題調(diào)整,具有一定的挑戰(zhàn)性。
  • 在處理嚴(yán)重不平衡的數(shù)據(jù)時(shí),仍可能遇到少數(shù)類(lèi)樣本過(guò)少的問(wèn)題。
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
from imblearn.under_sampling import RandomUnderSampler
from collections import Counter
from sklearn.datasets import make_classification

# Create a mock imbalanced dataset
X, y = make_classification(n_classes=2, weights=[0.99, 0.01], n_samples=1000, random_state=42)
print('Original class distribution:', Counter(y))

# Train a cost-sensitive decision tree
model = DecisionTreeClassifier(class_weight={0: 1, 1: 10}, random_state=42)
model.fit(X, y)

# Evaluate the model
y_pred = model.predict(X)
print(classification_report(y, y_pred))

5.平衡隨機(jī)森林

平衡隨機(jī)森林是在隨機(jī)森林的基礎(chǔ)上改進(jìn)的一種方法,針對(duì)不平衡數(shù)據(jù)集做了優(yōu)化。

它通過(guò)在構(gòu)建每棵決策樹(shù)時(shí),對(duì)多數(shù)類(lèi)進(jìn)行隨機(jī)欠采樣,確保每棵樹(shù)的訓(xùn)練集都是平衡的。同時(shí),它結(jié)合了隨機(jī)森林的特性,通過(guò)多個(gè)弱分類(lèi)器的集成來(lái)提高整體的預(yù)測(cè)能力。

優(yōu)點(diǎn)

  • 保留了隨機(jī)森林的優(yōu)勢(shì),如高準(zhǔn)確性和魯棒性。
  • 對(duì)多數(shù)類(lèi)進(jìn)行欠采樣,能夠減少模型對(duì)多數(shù)類(lèi)的偏向,提高對(duì)少數(shù)類(lèi)的預(yù)測(cè)能力。
  • 集成多個(gè)決策樹(shù),具有較強(qiáng)的泛化能力,減少了單一模型的偏差。

缺點(diǎn):

  • 相比于傳統(tǒng)隨機(jī)森林,平衡隨機(jī)森林的計(jì)算成本更高,因?yàn)樾枰獙?duì)多數(shù)類(lèi)進(jìn)行多次欠采樣。
  • 欠采樣過(guò)程中可能丟失多數(shù)類(lèi)的重要信息,影響模型的整體表現(xiàn)。
from imblearn.ensemble import BalancedRandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Train a Balanced Random Forest model
brf = BalancedRandomForestClassifier(random_state=42)
brf.fit(X_train, y_train)

# Evaluate
y_pred = brf.predict(X_test)
print('Balanced Random Forest Accuracy:', accuracy_score(y_test, y_pred))


責(zé)任編輯:武曉燕 來(lái)源: 程序員學(xué)長(zhǎng)
相關(guān)推薦

2019-02-25 08:35:22

機(jī)器學(xué)習(xí)數(shù)據(jù)模型

2019-03-27 08:51:38

機(jī)器學(xué)習(xí)類(lèi)失衡算法

2021-01-04 10:40:37

Python不平衡數(shù)據(jù)機(jī)器學(xué)習(xí)

2016-12-13 11:48:05

數(shù)據(jù)處理不平衡數(shù)據(jù)

2020-09-21 09:02:56

AI機(jī)器學(xué)習(xí)類(lèi)不平衡

2017-03-28 09:40:23

機(jī)器學(xué)習(xí)數(shù)據(jù)不平衡

2017-06-16 22:14:45

機(jī)器學(xué)習(xí)數(shù)據(jù)不平衡

2022-05-06 09:48:56

機(jī)器學(xué)習(xí)樣本不平衡

2025-01-20 09:00:00

2018-04-20 11:33:22

不平衡數(shù)據(jù)數(shù)據(jù)集模型

2017-03-20 09:25:10

機(jī)器學(xué)習(xí)采樣數(shù)據(jù)合成

2016-09-07 13:26:25

R語(yǔ)言不平衡數(shù)據(jù)

2023-09-29 22:51:22

數(shù)據(jù)不平衡Python機(jī)器學(xué)習(xí)

2023-12-26 15:32:25

不平衡數(shù)據(jù)過(guò)采樣機(jī)器學(xué)習(xí)

2018-09-11 13:47:35

數(shù)據(jù)不平衡數(shù)據(jù)分布數(shù)據(jù)集

2020-10-31 17:16:31

機(jī)器學(xué)習(xí)數(shù)據(jù)缺失數(shù)據(jù)科學(xué)

2020-11-02 10:54:18

機(jī)器學(xué)習(xí)技術(shù)人工智能

2020-10-06 10:44:16

機(jī)器學(xué)習(xí)不平衡數(shù)據(jù)算法

2021-06-06 22:41:30

人才技術(shù)預(yù)測(cè)不平衡

2018-06-11 16:20:22

數(shù)據(jù)不平衡數(shù)據(jù)集算法
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)