if (!require("shiny")) install.packages("shiny")
if (!require("naivebayes")) install.packages("naivebayes")
if (!require("e1071")) install.packages("e1071")
if (!require("caret")) install.packages("caret")
library(shiny)
library(naivebayes)
library(e1071)
library(caret)
# 데이터 불러오기
movie <- read.csv("c:\\data\\movie2.csv", stringsAsFactors=TRUE, fileEncoding = "euc-kr")
# 결측치 확인
colSums(is.na(movie))
# 훈련 데이터와 테스트 데이터로 분리
set.seed(1)
k <- createDataPartition(movie$장르, p=0.8, list=F)
train_data <- movie[k, ]
test_data <- movie[-k, ]
# 나이브 베이즈 모델 생성
new_model <- naive_bayes(장르 ~ ., data=train_data)
ui <- fluidPage(
titlePanel("영화 장르 예측기"),
# 전체 앱에 대한 사용자 정의 CSS 적용
tags$head(
tags$style(HTML("
body {
background-color: black; /* 배경색을 검정색으로 설정 */
color: orange; /* 글자색을 주황색으로 설정 */
font-size: 14px; /* 글꼴 크기 조정 */
}
"))
),
sidebarLayout(
sidebarPanel(
selectInput("age", "나이", choices = unique(movie$나이)),
selectInput("gender", "성별", choices = unique(movie$성별)),
selectInput("job", "직업", choices = unique(movie$직업)),
selectInput("married", "결혼여부", choices = unique(movie$결혼여부)),
selectInput("relationship", "이성친구 여부", choices = unique(movie$이성친구)),
actionButton("predict", "예측하기")
),
mainPanel(
textOutput("selected_inputs"), # 선택된 입력 조건 출력
verbatimTextOutput("predictions") # 예측 결과 출력
)
)
)
# 서버 로직 정의
server <- function(input, output, session) {
# 예측 결과를 저장할 reactiveValues 객체 생성
predictions <- reactiveValues(results = NULL, inputs = NULL)
observeEvent(input$predict, {
test_data <- data.frame(
나이 = input$age,
성별 = input$gender,
직업 = input$job,
결혼여부 = input$married,
이성친구 = input$relationship
)
# 저장된 입력 조건 업데이트
predictions$inputs <- test_data
# 새로운 예측 결과 계산
result <- predict(new_model, test_data, type = "class")
prob_result <- predict(new_model, test_data, type = "prob")
# 이전 결과에 새 결과를 추가
if (is.null(predictions$results)) {
predictions$results <- data.frame(예측 = result, 확률 = prob_result[, result])
} else {
new_result <- data.frame(예측 = result, 확률 = prob_result[, result])
predictions$results <- rbind(predictions$results, new_result)
}
})
# 선택된 입력 조건 출력
output$selected_inputs <- renderText({
req(predictions$inputs)
paste("선택된 조건:",
paste(names(predictions$inputs), "=", unlist(predictions$inputs), collapse = ", "))
})
# 예측 결과 출력
output$predictions <- renderPrint({
req(predictions$results) # predictions$results가 NULL이 아닌 경우에만 출력
predictions$results
})
}
# Shiny 앱 실행
shinyApp(ui = ui, server = server)