juooo1117

Self-Organizing Maps (SOM) Model - Practice 본문

Deep Learning Study/Udemy Deep Learning A-Z

Self-Organizing Maps (SOM) Model - Practice

Hyo__ni 2023. 11. 12. 12:03

Finding Frauds using Credit card applications dataset

 

Data Load & Preprocessing 

credit card applications dataset 을 이용해서 누가 사기꾼인지 알아내는 task 를 수행해 보자. 

dataset 을 확인해보니, 690명의 고객(row)과 특징 A1~A14(column)이 존재하고, 마지막 'class' column에는 이 고객이 승인되었는지 아닌지의 여부가 '0'(not approved), '1'(approved) 로 기재되어 있다. 

# importing the dataset
dataset = pd.read_csv('/content/MyDrive/MyDrive/Credit_Card_Applications.csv')

# Class column
## 0: application is not approved, 1: application is approved
dataset

Credit Card Application.csv dataset

 

'class' column만 떼어내기 위해서 x, y 2개의 subset을 만들어준다. 

'y'에는 승인여부를 나타내는 '1' 또는 '0'의 값만 존재하게 되고, 'x'에는 class column을 제외한 나머지 값들이 담긴다. 

# make two subset
x = dataset.iloc[:,:-1].values     # except class column => :-1입력!
y = dataset.iloc[:,-1].values

 

feature scaling 을 통해서 SOMs mapping에 사용될 모든 값들이(x) 0~1 사이의 값이 되도록 normalize 한다. 

# feature scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range=(0,1))
x = sc.fit_transform(x) # normalized version of 'x'

 

 

Training the SOM

minisom 을 import 하고 (10x10) size의 grid map을 만들어준다. 

input feature(x)가 총 15개 이므로, input_len=15 로 설정하고, weights로 initialize 해준 뒤에, 100번 학습시켜 준다. 

!pip3 install minisom
from minisom import MiniSom

# create 10*10 grid
som = MiniSom(x=10, y=10, input_len=15, sigma=1.0, learning_rate=0.5)
# initialize the weights
som.random_weights_init(x)
# to train the self-organizing maps on X
som.train_random(data=x, num_iteration=100)

 

Visualizing the results

start building the self organizing map

bone()을 이용해서 initializing map을 띄우고, marker의 종류는 'o' → circle, 's' → square 로 지정, marker 의 color는 'r' → red, 'g' → green으로 지정해 준다.

 

loop를 돌려서 모든 고객들을 SOM에 배치시킨다. (i: all the index of the customers, x: all the vectors of the customers)

winning node의 좌표 → (winning_node[0], winning_node[1])

marker는 winning node 중심에 위치시켜야 하므로, 각 좌표에 0.5씩을 더해준다. 

  • 고객이 승인되면(y[i]=0) → red circle
  • 고객이 승인되지 않으면(y[i]=1) → green square
from pylab import bone, pcolor, colorbar, plot, show

bone()                         # initializing map
pcolor(som.distance_map().T)   # 모든 노드의 거리가 반영됨
colorbar()                     # legend
markers = ['o','s']            # y[i]=0일때는 'o(circle)', y[i]=1일때는 's(square)'
colors = ['r','g']             # y[i]=0일때는 'r(red)', y[i]=1일때는 'g(green)'

# i: all the index of all customers, x: all the vectors of the customers
for i, x in enumerate(x):
  winning_node = som.winner(x)                         # winning node를 가져옴 (winning node의 좌표)
  # winning node의 좌표: (winning_node[0], winning_node[1])
  plot(winning_node[0] + 0.5, winning_node[1] + 0.5,   # marker를 winning node의 중심에 놓아야함 (0.5를 더해줌!)
       markers[y[i]],                                  # 고객이 승인되면 y[i]=0, 승인안되면 y[i]=1
       markeredgecolor = colors[y[i]],                 # 고객이 승인되면 y[i]=0, 승인안되면 y[i]=1
       markerfacecolor = 'None',
       markersize = 10,
       markeredgewidth = 2)

show()

1에 가까워질수록(하얀색 칸) → outlier winning node

 

Finding the frauds

SOMs 에 winning node 가 mapping 된 정보를 가져온다. → winning node의 좌표를 사용해서 customer list를 만들자

이후에 concatenate로 두 개의 outlier winning node(frauds: outlier winning node 이기 때문에)를 mapping 시켜준 다음, normalize 했던 값을(feature scaling) 다시 원래대로 되돌려 준다. 

mappings = som.win_map(x)                # SOMs의 winning node mapping 정보를 가져옴
frauds = np.concatenate((mappings[(6,5)], mappings[(6,8)]), axis = 0)  # 두 개의 mapping 을 묶어줌
frauds = sc.inverse_transform(frauds)    # inverse mapping

 

결과(frauds)를 확인해 보면, SOMs을 이용해서 frauds라고 판단한 고객의 list가 출력된다. 

 

 

[Practice github]

https://github.com/juooo1117/practice_AI_Learning/blob/main/SOMs/Self_Organizing_Maps.ipynb