File size: 9,271 Bytes
0a58a6f |
1 |
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"private_outputs":true,"provenance":[],"authorship_tag":"ABX9TyMw9KD5n9ZwBbRHi/tmy8/D"},"kernelspec":{"name":"ir","display_name":"R"},"language_info":{"name":"R"}},"cells":[{"cell_type":"code","source":["install.packages(\"caret\")\n","install.packages(\"naniar\")\n","install.packages(\"randomForest\")\n","install.packages(\"tidyverse\")\n","install.packages(\"psych\")\n","install.packages(\"mice\")\n","install.packages(\"pROC\")\n","install.packages(\"readxl\")\n","install.packages(\"openxlsx\")\n","install.packages(\"ggplot2\")"],"metadata":{"id":"_z67-XXqBMNn"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["library(caret)\n","library(tidyverse)\n","library(psych) #데이터 탐색\n","library(naniar) #결측치 처리 패키지\n","library(mice) #결측치 처리 패키지\n","library(pROC)\n","library(randomForest)\n","\n","library(readxl)\n","library(openxlsx)\n","library(ggplot2)"],"metadata":{"id":"X8gj3gvugQhX"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["washer <- read_excel(\"input/분석결과_세탁기.xlsx\")\n","\n","washer <- washer[, c(1:15)] #필요없는 끝에 열 삭제\n","washer$Actual_Purchase_Behavior <- ifelse(washer$Actual_Purchase_Behavior == -1, 0, 1)\n","# 종속 변수를 팩터로 변환\n","washer$Actual_Purchase_Behavior <- as.factor(washer$Actual_Purchase_Behavior)\n","washer"],"metadata":{"id":"yy_NjClAdwj5"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["refor <- read_excel(\"input/분석결과_냉장고.xls\")\n","refor <- refor[, c(1:15)] #필요없는 끝에 열 삭제\n","refor$Actual_Purchase_Behavior <- ifelse(refor$Actual_Purchase_Behavior == -1, 0, 1)\n","# 종속 변수를 팩터로 변환\n","refor$Actual_Purchase_Behavior <- as.factor(refor$Actual_Purchase_Behavior)\n","refor"],"metadata":{"id":"CyvOmVT9DpBU"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["aircon <- read_excel(\"input/분석결과_에어컨.xls\")\n","aircon <- aircon[, c(1:15)] #필요없는 끝에 열 삭제\n","aircon$Actual_Purchase_Behavior <- ifelse(aircon$Actual_Purchase_Behavior == -1, 0, 1)\n","# 종속 변수를 팩터로 변환\n","aircon$Actual_Purchase_Behavior <- as.factor(aircon$Actual_Purchase_Behavior)\n","aircon"],"metadata":{"id":"as0AvV3uECr6"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 예제 데이터 생성 (실제 데이터 대신 사용)\n","set.seed(42) # 시드를 설정하여 재현성을 보장합니다.\n","num_rows <- nrow(washer)"],"metadata":{"id":"Uv2Sbyqmdwqo"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 랜덤으로 열을 선택하기\n","selected_rows <- sample(1:num_rows, num_rows/2)"],"metadata":{"id":"lWiW-v4AdwtK"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 선택된 열 추출\n","train_washer <- washer[selected_rows,]\n","test_washer <- washer[-c(selected_rows),]"],"metadata":{"id":"RrYr77Op_24P"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 결과 확인\n","train_washer\n","test_washer"],"metadata":{"id":"HinJDORu_6Gv"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#검증 데이터셋 생성\n","set.seed(1)\n","train.index <- createDataPartition(train_washer$Actual_Purchase_Behavior, p = 0.9, list = FALSE)\n","train.0.9.DF <- train_washer[train.index, ]\n","valid_washer <- train_washer[-train.index, ]"],"metadata":{"id":"VirKEm2y_8Sl"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# RandomForest 함수 매개변수 설정을 변경하여 분류 모델로 만들기\n","rf.model <- randomForest(Actual_Purchase_Behavior ~ Sex + Age_Group + Marriage + FamilyLifeCycle +\n"," Purchase_Experience_Recency + Overall_RFM_Score + Peformance_Experience +\n"," Quality_Experience + Utility_Experience + SAT + BrandLove + CCB + Loyalty,\n"," data = train.0.9.DF, importance = TRUE, ntree = 500, nodesize = 1, mtry = sqrt(ncol(train.0.9.DF) - 1))\n"],"metadata":{"id":"IYYSbdijRIiZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["rf.predictions <- predict(rf.model, newdata = washer)\n","\n","# 예측 결과 출력\n","print(rf.predictions)"],"metadata":{"id":"ztgYPoPXbW8f"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#2)ROC Curve / AUC\n","#이상함...\n","roc(valid_washer$Actual_Purchase_Behavior, valid.predict.class, ci = T) %>%\n"," plot.roc(., col = \"red\", print.thres = T,\n"," print.auc = T, auc.polygon=TRUE, auc.polygon.col=\"#D1F2EB\",\n"," max.auc.polygon = T)"],"metadata":{"id":"GyOOgs37AAkN"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#개별 중요도\n","varImpPlot(rf.model, pch = 19, main = \"\")\n","round(importance(rf.model), 2)"],"metadata":{"id":"2ApDcUG0AC-_"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#수정한 랜덤 포레스트 모형\n","set.seed(1)\n","rf.model2 <- randomForest(Actual_Purchase_Behavior ~ Sex +\tAge_Group +\tMaritalStatus +\tMarriage\t+\n"," Overall_RFM_Score\t+ Quality_Experience +\tUtility_Experience\t+ SAT +\tBrandLove +\tCCB +\tLoyalty,\n"," data = train.0.9.DF, importance = T)\n","rf.model2"],"metadata":{"id":"suFCbMKZAEcD"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["rf.predictions_loyalty <- predict(rf.model, newdata = washer)\n","\n","# 예측 결과와 실제 레이블 비교\n","actual_labels <- washer$Actual_Purchase_Behavior\n","\n","# Confusion Matrix 생성\n","confusion_matrix_loyalty <- table(Actual = actual_labels, Predicted = rf.predictions_loyalty)\n","\n","# Classification table 출력\n","confusionMatrix(confusion_matrix_loyalty)"],"metadata":{"id":"7B5mXsPkTCJu"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["냉장고 레스고"],"metadata":{"id":"H0HU6HQhxBLd"}},{"cell_type":"code","source":["num_rows <- nrow(refor)\n","selected_rows <- sample(1:num_rows, num_rows/2)\n","train_refor <- refor[selected_rows,]\n","test_refor <- refor[-c(selected_rows),]\n","set.seed(1)\n","train.index <- createDataPartition(train_refor$Actual_Purchase_Behavior, p = 0.9, list = FALSE)\n","train.0.9.DF <- train_refor[train.index, ]\n","valid_refor <- train_refor[-train.index, ]\n","rf.model <- randomForest(Actual_Purchase_Behavior ~ Sex + Age_Group + Marriage + FamilyLifeCycle +\n"," Purchase_Experience_Recency + Overall_RFM_Score + Performance_Experience +\n"," Quality_Experience + Purchase_Behavior + SAT + BrandLove + CCB + Loyalty,\n"," data = train.0.9.DF, importance = TRUE, ntree = 500, nodesize = 1, mtry = sqrt(ncol(train.0.9.DF) - 1))\n","\n","rf.predictions <- predict(rf.model, newdata = refor)\n","\n","# 예측 결과 출력\n","print(rf.predictions)"],"metadata":{"id":"qXbNKdvCwlfV"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["rf.predictions_loyalty <- predict(rf.model, newdata = refor)\n","\n","# 예측 결과와 실제 레이블 비교\n","actual_labels <- refor$Actual_Purchase_Behavior\n","\n","# Confusion Matrix 생성\n","confusion_matrix_loyalty <- table(Actual = actual_labels, Predicted = rf.predictions_loyalty)\n","\n","# Classification table 출력\n","confusionMatrix(confusion_matrix_loyalty)"],"metadata":{"id":"98_5Ov9Pwyu_"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["에어컨 레스고"],"metadata":{"id":"U5E5njRS0cOf"}},{"cell_type":"code","source":["num_rows <- nrow(aircon)\n","selected_rows <- sample(1:num_rows, num_rows/2)\n","train_aircon <- aircon[selected_rows,]\n","test_aircon <- aircon[-c(selected_rows),]\n","set.seed(1)\n","train.index <- createDataPartition(train_aircon$Actual_Purchase_Behavior, p = 0.9, list = FALSE)\n","train.0.9.DF <- train_aircon[train.index, ]\n","valid_aircon <- train_aircon[-train.index, ]\n","rf.model <- randomForest(Actual_Purchase_Behavior ~ Sex + Age_Group + Marriage + FamilyLifeCycle +\n"," Purchase_Experience_Recency + Overall_RFM_Score + Performance_Experience +\n"," Quality_Experience + Utility_Experience + SAT + BrandLove + CCB + Loyalty,\n"," data = train.0.9.DF, importance = TRUE, ntree = 500, nodesize = 1, mtry = sqrt(ncol(train.0.9.DF) - 1))\n","\n","rf.predictions <- predict(rf.model, newdata = aircon)\n","\n","# 예측 결과 출력\n","print(rf.predictions)"],"metadata":{"id":"j7VF_b310eC3"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["rf.predictions_loyalty <- predict(rf.model, newdata = aircon)\n","\n","# 예측 결과와 실제 레이블 비교\n","actual_labels <- aircon$Actual_Purchase_Behavior\n","\n","# Confusion Matrix 생성\n","confusion_matrix_loyalty <- table(Actual = actual_labels, Predicted = rf.predictions_loyalty)\n","\n","# Classification table 출력\n","confusionMatrix(confusion_matrix_loyalty)"],"metadata":{"id":"7F9IjrGL0gB6"},"execution_count":null,"outputs":[]}]} |