오늘은 간략히 class weight를 주는 예제를 만들어 보고자 한다. python 예제는 충분한 것 같은데 R 예제가 없어서 기록을 남긴다.

자료 생성

손글씨 데이터를 불러오고 1인경우와 아닌경우로 자료의 불균형을 만들어 주었다.

library(tensorflow)
library(keras)
tf$test$is_gpu_available()
mnist=dataset_mnist()
train_images=mnist$train$x
train_labels=mnist$train$y
test_images=mnist$test$x
test_labels=mnist$test$y

train_images=array_reshape(train_images,c(nrow(train_images),28*28))
train_images=train_images/255
test_images=array_reshape(test_images,c(nrow(test_images),28*28))
test_images=test_images/255
train_labels=ifelse(train_labels==1,0,1)
test_labels=ifelse(test_labels==1,0,1)

모델 생성

기존 모델 구축

만들어 준 데이터의 가중치 없이 학습하는 코드는 아래와 같다.

set_random_seed(42)
network=keras_model_sequential()%>%
  layer_dense(units=512,activation ='relu', input_shape=c(28*28))%>%
  layer_dense(units=128, activation='relu')%>%
  layer_dense(units=1, activation='sigmoid')

network%>%compile(
  optimizer=optimizer_rmsprop(),
  loss=loss_binary_crossentropy(),
  metrics='acc'
)

network%>%fit(train_images,train_labels, epochs=5, batch_size=128)

가중치를 적용한 모델 구축

class_weight를 추가하면 적용이 된다.  

set_random_seed(42)
network=keras_model_sequential()%>%
  layer_dense(units=512,activation ='relu', input_shape=c(28*28))%>%
  layer_dense(units=128, activation='relu')%>%
  layer_dense(units=1, activation='sigmoid')

network%>%compile(
  optimizer=optimizer_rmsprop(),
  loss=loss_binary_crossentropy(),
  metrics='acc'
)

network%>%fit(train_images,train_labels, epochs=5, batch_size=128,
              class_weight =list("0"=9,"1"=1))