Ⅰ 如何處理不平衡數據(一)——欠采樣
一、重采樣
1、欠采樣
欠采樣就是一個隨機刪除一部分多數類(數量多的類型)數據的過程
# Shuffle the Dataset. 進行一個數據集打亂的操作
shuffled_df = credit_df.sample(frac=1,random_state=4)
# Put all the fraud class in a separate dataset. 欺詐類 就是數量少的類
fraud_df = shuffled_df.loc[shuffled_df['Class'] == 1]
#Randomly select 492 observations from the non-fraud (majority class) 選取過多的類進行一個抽取
non_fraud_df=shuffled_df.loc[shuffled_df['Class']== 0].sample(n=492,random_state=42)
# Concatenate both dataframes again 生成一個均衡類
normalized_df = pd.concat([fraud_df, non_fraud_df])
#plot the dataset after the undersampling 下面是畫圖操作
plt.figure(figsize=(8, 8))
sns.countplot('Class', data=normalized_df)
plt.title('Balanced Classes')
plt.show()