# 데이터 불러오기 및 모델 생성 (여기서부터 시작) 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 정의 ui <- fluidPage( titlePanel("영화 장르 예측기"), sidebarLayout( sidebarPanel( tags$div( style = "text-align: center;", 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("prediction_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") output$prediction <- renderPrint({ result }) output$prediction_plot <- renderPlot({ if (!is.null(result)) { # 결과에 100을 곱하여 확률을 백분율로 변환 result_percent <- result * 100 # 소수점 첫 번째 자리에서 올림 result_percent_ceil <- ceiling(result_percent * 10) / 10 barplot(as.matrix(result_percent_ceil), beside = TRUE, col = 'lightsalmon', main = "장르 예측 결과", ylab = "확률 (%)", xlab = "장르", ylim = c(0, 100)) # 확률 값 표시 text( x = barplot(as.matrix(result_percent_ceil), beside = TRUE, plot = FALSE) + 0.2, y = as.matrix(result_percent_ceil) + 2, labels = format(as.matrix(result_percent_ceil), nsmall = 1), pos = 3, col = "black" ) } else { plot(NULL, xlim = c(0, 1), ylim = c(0, 100), type = "n", xlab = "장르", ylab = "확률 (%)", main = "장르 예측 결과") text(0.5, 50, "예측 결과가 없습니다.", cex = 1.5) } }) }) }
# Shiny 앱 실행 shinyApp(ui = ui, server = server) |