if (!require("shiny")) {install.packages("shiny"); library(shiny) } else {library(shiny)} if (!require("naivebayes")) {install.packages("naivebayes"); library(naivebayes) } else {library(naivebayes)} if (!require("e1071")) {install.packages("e1071"); library(e1071) } else {library(e1071)} if (!require("caret")) {install.packages("caret"); library(caret) } else {library(caret)} if (!require("ggplot2")) {install.packages("ggplot2"); library(ggplot2) } else {library(ggplot2)}
# 데이터 불러오기 movie <- read.csv("c:\\data\\movie2.csv", stringsAsFactors = TRUE, fileEncoding = "euc-kr")
# 결측치 확인 colSums(is.na(movie))
# 훈련 데이터와 테스트 데이터로 분리 set.seed(9) k <- createDataPartition(movie$장르, p = 0.8, list = F) train_data <- movie[k, ] test_data <- movie[-k, ]
# 나이브 베이즈 모델 생성 new_model <- naive_bayes(장르 ~ ., data = train_data)
# UI 정의 ui <- fluidPage(titlePanel("영화 장르 예측기"), 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(verbatimTextOutput("prediction"), plotOutput("prob_plot")) )) # 서버 로직 정의 server <- function(input, output) { observeEvent(input$predict, { test_data <- data.frame( 나이 = input$age, 성별 = input$gender, 직업 = input$job, 결혼여부 = input$married, 이성친구 = input$relationship ) result <- predict(new_model, test_data, type = "prob") predicted_genre <- colnames(result)[which.max(result)] output$prediction <- renderPrint({ paste("예측 장르: ", predicted_genre) }) output$prob_plot <- renderPlot({ prob_data <- as.data.frame(t(result)) prob_data$장르 <- rownames(prob_data) prob_data$확률 <- prob_data$V1 * 100 ggplot(prob_data, aes(x = 장르, y = V1)) + geom_bar(stat = "identity", fill = "pink", width = 0.5) + geom_text(aes(label = sprintf("%.2f%%", 확률)), vjust = -0.5, size = 4) + labs(title = "장르별 확률", x = "장르", y = "확률") + theme_minimal() }) }) }
# Shiny 앱 실행 shinyApp(ui = ui, server = server) |