Keras

영화평에 대한 binary classification

이부일 2019. 3. 4. 22:04

# 패키지 설치하기와 로딩하기
devtools::install_github("rstudio/keras")
library(keras)
install_keras()


# 예제 데이터 불러오기
imdb <- keras::dataset_imdb(num_words = 10000)


# train, test 데이터 구분하기
c(c(train_data, train_labels), c(test_data, test_labels)) %<-% imdb


# 데이터 변형하기 함수
vectorize_sequences <- function(sequences, dimension = 10000){
    results <- matrix(0, nrow = length(sequences), ncol = dimension)
    for(i in 1:length(sequences)){
        results[i, sequences[[i]]] <- 1
    }

results

}


# 데이터 변형하기
x_train <- vectorize_sequences(train_data)
x_test <- vectorize_sequences(test_data)
y_train <- as.numeric(train_labels)
y_test <- as.numeric(test_labels)


# 모형 만들기
model <- keras::keras_model_sequential() %>% 
    keras::layer_dense(units = 16, activation = "relu", input_shape = 10000) %>% 
    keras::layer_dense(units = 16, activation = "relu") %>% 
    keras::layer_dense(units = 1, activation = "sigmoid")


# 모형의 컴파일
model %>%
    keras::compile(optimizer = "rmsprop",
    loss = "binary_crossentropy",
    metrics = "accuracy")


# 학습하기
history <- model %>% 
    keras::fit(x_train,
    y_train,
    epochs = 100,
    batch_size = 512)
plot(history)


# 평가하기
results <- model %>% 
    keras::evaluate(x_test, y_test)

results


[출처] Deep Learning with R, 프랑소와 숄레, J.J. 알래어 지음, 박진수 옮김, 제이펍, p64~88