SamuelGalaxys commited on
Commit
0a58a6f
1 Parent(s): 675b346

Upload 8 files

Browse files
DYProfessor/.DS_Store ADDED
Binary file (6.15 kB). View file
 
DYProfessor/.Rhistory ADDED
File without changes
DYProfessor/RF_lab.ipynb ADDED
@@ -0,0 +1 @@
 
 
1
+ {"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"LI8PnFZ9CY8D"},"outputs":[],"source":["import pandas as pd\n","from pandas import Series, DataFrame\n","import numpy as np\n","import matplotlib.pyplot as plt\n","from sklearn.ensemble import RandomForestClassifier\n","\n","\n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"QC0uRmQSCsQq"},"outputs":[],"source":["train = pd.read_excel(\"input/washer_분석용 데이터.xls\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"YAKgHScREYiq"},"outputs":[],"source":["train = pd.read_excel(\"input/washer_분석용 데이터.xls\", sheet_name=1)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"D9XGKYmRCsJC"},"outputs":[],"source":["train = train.iloc[:, :-3]\n","\n","train"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"S8Vamo80Ezg5"},"outputs":[],"source":["X_train = train.drop(\"BrandSwitching\",axis=1)\n","Y_train = train[\"BrandSwitching\"]\n","\n","rf_model = RandomForestClassifier(n_estimators=100, random_state=42)\n","rf_model.fit(X_train, Y_train)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"6nG25KUcGPhU"},"outputs":[],"source":["Y_pred = rf_model.predict(X_train)\n","Y_pro = rf_model.predict_proba(X_train)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"WscFuv3mHFay"},"outputs":[],"source":["Y_pred"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"FNUoUdQIHHxE"},"outputs":[],"source":["Y_pro"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"j3RMG-rOHI-g"},"outputs":[],"source":["rf_model.score(X_train, Y_train)"]},{"cell_type":"markdown","metadata":{"id":"7efD-9JFyI3l"},"source":["------------------------------"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"IWfkVklVq51d"},"outputs":[],"source":["train_half = train.iloc[40:80]\n","test_half = train"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"0gOTWYblrGXV"},"outputs":[],"source":["X_train2 = train_half.drop(\"BrandSwitching\",axis=1)\n","Y_train2 = train_half[\"BrandSwitching\"]\n","X_test2 = test_half.drop(\"BrandSwitching\",axis=1)\n","Y_test2 = test_half[\"BrandSwitching\"]\n","\n","rf_model = RandomForestClassifier(n_estimators=100, random_state=42)\n","rf_model.fit(X_train2, Y_train2)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"bpZmkSFruY4C"},"outputs":[],"source":["Y_pred2 = rf_model.predict(X_test2)\n","Y_pro2 = rf_model.predict_proba(X_test2)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"HQLpw4KAui14"},"outputs":[],"source":["a_1 = 0\n","for i in range(0,len(Y_pred2)):\n"," if Y_pred2[i] != Y_test2[i]:\n"," a_1+=1\n","print('Discord', a_1)\n","\n","print(\"discord rate:\",round(a_1/len(Y_pred2)*100, 2),\"%\")"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"NI2oy_xYvTtC"},"outputs":[],"source":["Y_pred2"]}],"metadata":{"colab":{"authorship_tag":"ABX9TyNJYIKxXolmheRpHQROsFoF","private_outputs":true,"provenance":[]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
DYProfessor/Rlab1.R ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"private_outputs":true,"provenance":[],"authorship_tag":"ABX9TyMkS2xKZMMHJ3eViJZCIDEX"},"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/washer_분석용 데이터.xls\")\n","\n","washer <- washer[, -c(17, 18, 19)] #필요없는 끝에 열 삭제\n","# 종속 변수를 팩터로 변환\n","washer$BrandSwitching <- as.factor(washer$BrandSwitching)\n","washer"],"metadata":{"id":"yy_NjClAdwj5"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["nrow(washer)"],"metadata":{"id":"Uxm91rgLglBZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ggplot(washer, aes(x = Age_Group)) +\n"," geom_histogram(aes(y = ..density..), binwidth = 1)+\n"," geom_density(color = \"red\", size = 1)"],"metadata":{"id":"Uv2Sbyqmdwqo"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ggplot(washer, aes(x = FamilyLifeCycle)) +\n"," geom_histogram(aes(y = ..density..), binwidth = 1)+\n"," geom_density(color = \"red\", size = 1)"],"metadata":{"id":"lWiW-v4AdwtK"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ggplot(washer, aes(x = Purchase_Experience_Recency)) +\n"," geom_histogram(aes(y = ..density..), binwidth = 1)+\n"," geom_density(color = \"red\", size = 1)"],"metadata":{"id":"RrYr77Op_24P"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ggplot(washer, aes(x = Age_Group, fill = factor(BrandSwitching))) +\n"," geom_bar() +\n"," geom_text(aes(label = ..count..), stat = \"count\", position = position_stack(0.5))"],"metadata":{"id":"HinJDORu_6Gv"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ggplot(washer, aes(x = Sex, fill = factor(BrandSwitching))) +\n"," geom_bar() +\n"," geom_text(aes(label = ..count..), stat = \"count\", position = position_stack(0.5))"],"metadata":{"id":"VirKEm2y_8Sl"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["washer$Overall_RFM_Score2 <- cut(washer$Overall_RFM_Score, breaks = seq(0, 600, 20), right = F)"],"metadata":{"id":"6ViQM3Ss_-AD"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ggplot(washer, aes(Overall_RFM_Score, fill = BrandSwitching)) +\n"," geom_histogram()"],"metadata":{"id":"31XyAv-___KT"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["table(washer$Overall_RFM_Score2, washer$BrandSwitching)\n","prop.table(table(washer$Overall_RFM_Score2, washer$BrandSwitching), 1)"],"metadata":{"id":"GyOOgs37AAkN"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#-----분류 및 예측-----#\n","train.DF <- washer[30:90, ]\n","test.DF <- washer[-c(30:90), ]"],"metadata":{"id":"2ApDcUG0AC-_"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#train 데이터셋을 분할하여 검증(validation) 데이터셋을 만듭니다.\n","set.seed(1)\n","train.index <- createDataPartition(train.DF$BrandSwitching, p = 0.9, list = FALSE)\n","train.0.9.DF <- train.DF[train.index, ]\n","valid.DF <- train.DF[-train.index, ]"],"metadata":{"id":"suFCbMKZAEcD"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 종속 변수를 팩터로 변환\n","washer$BrandSwitching <- as.factor(washer$BrandSwitching)\n"],"metadata":{"id":"d1cN9LoSgy5f"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["set.seed(1234)\n","rf.model <- randomForest(BrandSwitching ~ Sex + Age_Group + Marriage + FamilyLifeCycle + Purchase_Experience_Recency + LX_Curve_Pattern + Overall_RFM_Score +\n"," Peformance_Experience + Quality_Experience + Utility_Experience + SAT + BrandLove + CCB + Loyalty,\n"," data = train.0.9.DF, importance = T)\n","\n","rf.model"],"metadata":{"id":"t4D0TM--AG2Z"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["valid.predict.class <- predict(rf.model, newdata = valid.DF, type = \"class\")\n","valid.predict.class"],"metadata":{"id":"bwNh3e9BAIAW"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 랜덤 포레스트 모델을 이미 생성한 경우, 다음과 같이 예측을 수��합니다.\n","\n","# 예측 수행 (loyalty 변수를 중심으로 예측)\n","rf.predictions_loyalty <- predict(rf.model, newdata = washer)\n","\n","# 예측 결과와 실제 레이블 비교\n","actual_labels <- washer$BrandSwitching\n","\n","# Confusion Matrix 생성\n","confusion_matrix_loyalty <- table(Actual = actual_labels, Predicted = rf.predictions_loyalty)\n","\n","# Classification table 출력\n","print(confusion_matrix_loyalty)\n","\n","# 또는 Classification table을 보다 읽기 쉽게 출력하려면 아래와 같이 사용 가능\n","library(caret)\n","confusionMatrix(confusion_matrix_loyalty)\n"],"metadata":{"id":"WNLCX1PlcYNJ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["varImpPlot(rf.model, pch = 19, main = \"\")\n","\n","round(importance(rf.model), 2)"],"metadata":{"id":"unv0o_8RAK5q"},"execution_count":null,"outputs":[]}]}
DYProfessor/Rlab2.R ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"private_outputs":true,"provenance":[],"authorship_tag":"ABX9TyO7rr88hFtQjd1gKkwwoxb2"},"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:16)] #필요없는 끝에 열 삭제\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":["str(washer)"],"metadata":{"id":"Uxm91rgLglBZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["nrow(washer)"],"metadata":{"id":"zKwvHScycLL8"},"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":["#랜덤 포레스트 모형 생성\n","set.seed(1234)\n","rf.model <- randomForest(Actual_Purchase_Behavior ~ Sex + Age_Group + MaritalStatus + 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","rf.model"],"metadata":{"id":"6ViQM3Ss_-AD"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# RandomForest 함수 매개변수 설정을 변경하여 분류 모델로 만들기\n","rf.model <- randomForest(Actual_Purchase_Behavior ~ Sex + Age_Group + MaritalStatus + 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":["#모형 성능 평가\n","#이상함....\n","valid.predict.class <- predict(rf.model, newdata = valid_washer, type = \"class\")\n","valid.predict.class"],"metadata":{"id":"31XyAv-___KT"},"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":["valid.predict.prob <- predict(rf.model, newdata = valid_washer, type = \"prob\")\n","\n","confusionMatrix(as.factor(valid.predict.class), valid_washer$Actual_Purchase_Behavior, positive = \"1\")"],"metadata":{"id":"XvnPpshQZEVg"},"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":["#제출용\n","prediction <- predict(rf.model2, test_washer)\n","submission <- data.frame(PassengerID = test_washer$ID_Number, Actual_Purchase_Behavior = prediction)\n","write.csv(submission, file = \"lg_rf_mod_Solution.csv\", row.names = F)"],"metadata":{"id":"mBXLWpFwS3ps"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# valid.predict.class와 valid_washer$Actual_Purchase_Behavior을 factor로 변환하고 levels를 지정\n","valid.predict.class <- factor(valid.predict.class, levels = c(\"0\", \"1\"))\n","valid_washer$Actual_Purchase_Behavior <- factor(valid_washer$Actual_Purchase_Behavior, levels = c(\"0\", \"1\"))"],"metadata":{"id":"d1cN9LoSgy5f"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# 다시 한 번 factor levels를 확인\n","levels(valid.predict.class)\n","levels(valid_washer$Actual_Purchase_Behavior)"],"metadata":{"id":"t4D0TM--AG2Z"},"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":"code","source":["# ROC 곡선 그리기\n","roc(valid_washer$Actual_Purchase_Behavior, valid.predict.class_numeric, ci = TRUE) %>%\n"," plot.roc(col = \"red\", print.thres = TRUE, print.auc = TRUE,\n"," auc.polygon = TRUE, auc.polygon.col = \"#D1F2EB\", max.auc.polygon = TRUE)"],"metadata":{"id":"bwNh3e9BAIAW"},"execution_count":null,"outputs":[]}]}
DYProfessor/Rlab3.R ADDED
@@ -0,0 +1 @@
 
 
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":[]}]}
DYProfessor/ZeroRlab.R ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"private_outputs":true,"provenance":[],"authorship_tag":"ABX9TyMuiqnUdpXJr+DoITFro6h6"},"kernelspec":{"name":"ir","display_name":"R"},"language_info":{"name":"R"}},"cells":[{"cell_type":"code","source":["install.packages(\"randomForest\")\n","library(randomForest)"],"metadata":{"id":"X8gj3gvugQhX"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["data(iris)\n","iris.rf <- randomForest(iris[,-5], iris[,5], prox=TRUE)\n","iris.p <- classCenter(iris[,-5], iris[,5], iris.rf$prox)\n","plot(iris[,3], iris[,4], pch=21, xlab=names(iris)[3], ylab=names(iris)[4],\n","bg=c(\"red\", \"blue\", \"green\")[as.numeric(factor(iris$Species))],\n","main=\"Iris Data with Prototypes\")\n","points(iris.p[,3], iris.p[,4], pch=21, cex=2, bg=c(\"red\", \"blue\", \"green\"))"],"metadata":{"id":"yy_NjClAdwj5"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["iris"],"metadata":{"id":"Uxm91rgLglBZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["data(iris)\n","rf1 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)\n","#열을 예측할 타겟(목표) 변수로 설정하고, 나머지 열들을 입력 변수로 사용합니다(~ .는 모든 열을 의미).\n","rf2 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)\n","rf3 <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)\n","rf.all <- combine(rf1, rf2, rf3)\n","print(rf.all)"],"metadata":{"id":"Uv2Sbyqmdwqo"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["data(iris)\n","iris.rf <- randomForest(Species ~ ., iris, ntree=50, norm.votes=FALSE)\n","iris.rf <- grow(iris.rf, 50)\n","print(iris.rf)\n"],"metadata":{"id":"lWiW-v4AdwtK"},"execution_count":null,"outputs":[]}]}
DYProfessor/rwa실습.R ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"private_outputs":true,"provenance":[],"authorship_tag":"ABX9TyOGXZs33URbCd8MFVDOeVHs"},"kernelspec":{"name":"ir","display_name":"R"},"language_info":{"name":"R"}},"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"yu1qMJoWwbaO"},"outputs":[],"source":["install.packages(\"devtools\")\n","devtools::install_github(\"martinctc/rwa\")"]},{"cell_type":"code","source":["library(rwa)\n","library(tidyverse)"],"metadata":{"id":"Lm7-xh11w9fE"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["rsquare: the rsquare value of the regression model.\n","\n","result: the final output of the importance metrics.\n","\n","The Rescaled.RelWeight column sums up to 100.\n","\n","The Sign column indicates whether a predictor is positively or negatively correlated with the outcome.\n","\n","n: indicates the number of observations used in the analysis.\n","\n","lambda:\n","\n","RXX: Correlation matrix of all the predictor variables against each other.\n","\n","RXY: Correlation values of the predictor variables against the outcome variable"],"metadata":{"id":"tFWx4b6k0lT4"}},{"cell_type":"code","source":["mtcars %>%\n"," rwa(outcome = \"mpg\",\n"," predictors = c(\"cyl\", \"disp\", \"hp\", \"gear\"),\n"," applysigns = TRUE)"],"metadata":{"id":"DzjpS6TTxCq7"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["library(ggplot2)\n","rwa(diamonds,\"price\",c(\"depth\",\"carat\"))"],"metadata":{"id":"B__8tp9XyJoo"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["library(dplyr)\n","data_train <- read.csv(\"https://raw.githubusercontent.com/guru99-edu/R-Programming/master/train.csv\")\n","glimpse(data_train)\n","data_test <- read.csv(\"https://raw.githubusercontent.com/guru99-edu/R-Programming/master/test.csv\")\n","glimpse(data_test)"],"metadata":{"id":"lwQsSTZJYd_n"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["install.packages(\"randomForest\")\n","library(randomForest)"],"metadata":{"id":"mXqBprSbbCyG"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["RandomForest(formula, ntree=n, mtry=FALSE, maxnodes = NULL)"],"metadata":{"id":"_8Uc6OMHv5OA"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["library(caret)\n","library(e1071)"],"metadata":{"id":"5qSMgL78b0DB"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["trControl <- trainControl(method = \"cv\",\n"," number = 10,\n"," search = \"grid\")"],"metadata":{"id":"LH9fLIBxY2QQ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":[],"metadata":{"id":"kZ25clb3b_2M"},"execution_count":null,"outputs":[]}]}