處理非平衡資料集——SMOTE演算法
阿新 • • 發佈:2018-11-06
SMOTE全稱是Synthetic Minority Oversampling Technique即合成少數類過取樣技術,它是基於隨機過取樣演算法的一種改進方案,由於隨機過取樣採取簡單複製樣本的策略來增加少數類樣本,這樣容易產生模型過擬合的問題,即使得模型學習到的資訊過於特別(Specific)而不夠泛化(General),SMOTE演算法的基本思想是對少數類樣本進行分析並根據少數類樣本人工合成新樣本新增到資料集中,具體如圖2所示,演算法流程如下。
- 對於少數類中每一個樣本xx,以歐氏距離為標準計算它到少數類樣本集SminSmin中所有樣本的距離,得到其k近鄰。
- 根據樣本不平衡比例設定一個取樣比例以確定取樣倍率N,對於每一個少數類樣本xx,從其k近鄰中隨機選擇若干個樣本,假設選擇的近鄰為xnxn。
- 對於每一個隨機選出的近鄰xnxn,分別與原樣本按照如下的公式構建新的樣本
xnew=x+rand(0,1)∗|x−xn|xnew=x+rand(0,1)∗|x−xn|
#SMOTE演算法及其python實現 import random from sklearn.neighbors import NearestNeighbors import numpy as np class Smote: def __init__(self,samples,N=10,k=5): self.n_samples,self.n_attrs=samples.shape self.N=N self.k=k self.samples=samples self.newindex=0 # self.synthetic=np.zeros((self.n_samples*N,self.n_attrs)) def over_sampling(self): N=int(self.N/100) self.synthetic = np.zeros((self.n_samples * N, self.n_attrs)) neighbors=NearestNeighbors(n_neighbors=self.k).fit(self.samples) print ('neighbors',neighbors) for i in range(len(self.samples)): print('samples',self.samples[i]) nnarray=neighbors.kneighbors(self.samples[i].reshape((1,-1)),return_distance=False)[0] #Finds the K-neighbors of a point. print ('nna',nnarray) self._populate(N,i,nnarray) return self.synthetic # for each minority class sample i ,choose N of the k nearest neighbors and generate N synthetic samples. def _populate(self,N,i,nnarray): for j in range(N): print('j',j) nn=random.randint(0,self.k-1) #包括end dif=self.samples[nnarray[nn]]-self.samples[i] gap=random.random() self.synthetic[self.newindex]=self.samples[i]+gap*dif self.newindex+=1 print(self.newindex) a=np.array([[1,2,3],[4,5,6],[2,3,1],[2,1,2],[2,3,4],[2,3,4]]) s=Smote(a,N=1000) s.over_sampling()