getwd()
## [1] "C:/Users/x230t/Desktop"
setwd('c:/data')
getwd()
## [1] "c:/data"
library(dplyr)
## 
## 다음의 패키지를 부착합니다: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(caret)
## 필요한 패키지를 로딩중입니다: ggplot2
## 필요한 패키지를 로딩중입니다: lattice
rm(list=ls())
ls()
## character(0)
set.seed(1)
data(iris)
idx<-createDataPartition(iris$Species,p=0.8,list=FALSE)
#idx$Resample1

#table(iris[idx$Resample1,"Species"])
#table(iris[-idx$Resample1,"Species"])

train<-iris[idx,]
test<-iris[-idx,]
nrow(train)
## [1] 120
nrow(test)
## [1] 30
set.seed(2)
data(iris)
idx<-createDataPartition(iris$Species,p=0.6,list=FALSE)
train<-iris[idx,]
valid_test<-iris[-idx,]

idx2<-createDataPartition(valid_test$Species,p=0.5,list=FALSE)
valid<-valid_test[idx2,]
test<-valid_test[-idx2,]

nrow(train)/nrow(iris)
## [1] 0.6
nrow(valid)/nrow(iris)
## [1] 0.2
nrow(test)/nrow(iris)
## [1] 0.2
data(iris)
zs_iris<-preProcess(iris,method=c("center","scale"))
zs_iris
## Created from 150 samples and 5 variables
## 
## Pre-processing:
##   - centered (4)
##   - ignored (1)
##   - scaled (4)
zs_iris_p<-predict(zs_iris,iris)

#install.packages("psych")
library(psych)
## 
## 다음의 패키지를 부착합니다: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
describe(zs_iris_p[,1:4])
##              vars   n mean sd median trimmed  mad   min  max range  skew
## Sepal.Length    1 150    0  1  -0.05   -0.04 1.25 -1.86 2.48  4.35  0.31
## Sepal.Width     2 150    0  1  -0.13   -0.03 1.02 -2.43 3.08  5.51  0.31
## Petal.Length    3 150    0  1   0.34    0.00 1.05 -1.56 1.78  3.34 -0.27
## Petal.Width     4 150    0  1   0.13   -0.02 1.36 -1.44 1.71  3.15 -0.10
##              kurtosis   se
## Sepal.Length    -0.61 0.08
## Sepal.Width      0.14 0.08
## Petal.Length    -1.42 0.08
## Petal.Width     -1.36 0.08
sca_iris<-preProcess(iris,method = "range")
sca_iris
## Created from 150 samples and 5 variables
## 
## Pre-processing:
##   - ignored (1)
##   - re-scaling to [0, 1] (4)
sca_iris_p<-predict(sca_iris,iris)
head(sca_iris_p)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1   0.22222222   0.6250000   0.06779661  0.04166667  setosa
## 2   0.16666667   0.4166667   0.06779661  0.04166667  setosa
## 3   0.11111111   0.5000000   0.05084746  0.04166667  setosa
## 4   0.08333333   0.4583333   0.08474576  0.04166667  setosa
## 5   0.19444444   0.6666667   0.06779661  0.04166667  setosa
## 6   0.30555556   0.7916667   0.11864407  0.12500000  setosa
library(psych)
describe(sca_iris_p)
##              vars   n mean   sd median trimmed  mad min max range  skew
## Sepal.Length    1 150 0.43 0.23   0.42    0.42 0.29   0   1     1  0.31
## Sepal.Width     2 150 0.44 0.18   0.42    0.43 0.19   0   1     1  0.31
## Petal.Length    3 150 0.47 0.30   0.57    0.47 0.31   0   1     1 -0.27
## Petal.Width     4 150 0.46 0.32   0.50    0.45 0.43   0   1     1 -0.10
## Species*        5 150 2.00 0.82   2.00    2.00 1.48   1   3     2  0.00
##              kurtosis   se
## Sepal.Length    -0.61 0.02
## Sepal.Width      0.14 0.01
## Petal.Length    -1.42 0.02
## Petal.Width     -1.36 0.03
## Species*        -1.52 0.07
bc_iris=preProcess(iris,method = "BoxCox")
bc_iris
## Created from 150 samples and 5 variables
## 
## Pre-processing:
##   - Box-Cox transformation (4)
##   - ignored (1)
## 
## Lambda estimates for Box-Cox transformation:
## -0.1, 0.3, 0.9, 0.6
bc_iris_t=predict(bc_iris,iris)
head(bc_iris_t)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1     1.629241    1.520660          1.4  -1.0321154  setosa
## 2     1.589235    1.301297          1.4  -1.0321154  setosa
## 3     1.547563    1.391905          1.3  -1.0321154  setosa
## 4     1.526056    1.347113          1.5  -1.0321154  setosa
## 5     1.609438    1.561856          1.4  -1.0321154  setosa
## 6     1.686399    1.680826          1.7  -0.7048667  setosa
par(mfrow=c(1,2))
plot(density(x=iris$Sepal.Width))
plot(density(x=bc_iris_t$Sepal.Width))

pca_iris<-preProcess(iris,method = "pca")
pca_iris
## Created from 150 samples and 5 variables
## 
## Pre-processing:
##   - centered (4)
##   - ignored (1)
##   - principal component signal extraction (4)
##   - scaled (4)
## 
## PCA needed 2 components to capture 95 percent of the variance
pca_iris_p<-predict(pca_iris,iris)
head(pca_iris_p)
##   Species       PC1        PC2
## 1  setosa -2.257141 -0.4784238
## 2  setosa -2.074013  0.6718827
## 3  setosa -2.356335  0.3407664
## 4  setosa -2.291707  0.5953999
## 5  setosa -2.381863 -0.6446757
## 6  setosa -2.068701 -1.4842053
#install.packages("earth")
library(earth)
## 필요한 패키지를 로딩중입니다: Formula
## 필요한 패키지를 로딩중입니다: plotmo
## 필요한 패키지를 로딩중입니다: plotrix
## 
## 다음의 패키지를 부착합니다: 'plotrix'
## The following object is masked from 'package:psych':
## 
##     rescale
## 필요한 패키지를 로딩중입니다: TeachingDemos
data(etitanic)
glimpse(etitanic)
## Rows: 1,046
## Columns: 6
## $ pclass   <fct> 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1st, 1…
## $ survived <int> 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1…
## $ sex      <fct> female, male, female, male, female, male, female, male, femal…
## $ age      <dbl> 29.0000, 0.9167, 2.0000, 30.0000, 25.0000, 48.0000, 63.0000, …
## $ sibsp    <int> 0, 1, 1, 1, 1, 0, 1, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1…
## $ parch    <int> 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1…
dummies<-dummyVars(survived~.,data = etitanic)
head(predict(dummies, newdata = etitanic))
##   pclass.1st pclass.2nd pclass.3rd sex.female sex.male     age sibsp parch
## 1          1          0          0          1        0 29.0000     0     0
## 2          1          0          0          0        1  0.9167     1     2
## 3          1          0          0          1        0  2.0000     1     2
## 4          1          0          0          0        1 30.0000     1     2
## 5          1          0          0          1        0 25.0000     1     2
## 6          1          0          0          0        1 48.0000     0     0
data(airquality)
colSums(is.na(airquality))
##   Ozone Solar.R    Wind    Temp   Month     Day 
##      37       7       0       0       0       0
#install.packages("RANN")
library(RANN)
head(airquality)
##   Ozone Solar.R Wind Temp Month Day
## 1    41     190  7.4   67     5   1
## 2    36     118  8.0   72     5   2
## 3    12     149 12.6   74     5   3
## 4    18     313 11.5   62     5   4
## 5    NA      NA 14.3   56     5   5
## 6    28      NA 14.9   66     5   6
knn_im<-preProcess(airquality[1:4],method = "knnImpute")
head(predict(knn_im,airquality))
##         Ozone     Solar.R       Wind       Temp Month Day
## 1 -0.03423409  0.04517615 -0.7259482 -1.1497140     5   1
## 2 -0.18580489 -0.75430487 -0.5556388 -0.6214670     5   2
## 3 -0.91334473 -0.41008388  0.7500660 -0.4101682     5   3
## 4 -0.73145977  1.41095624  0.4378323 -1.6779609     5   4
## 5 -0.69508278 -0.92308420  1.2326091 -2.3118573     5   5
## 6 -0.42831817 -0.28349938  1.4029185 -1.2553634     5   6
knn_im_p<-predict(knn_im,airquality)
colSums(is.na(knn_im_p))
##   Ozone Solar.R    Wind    Temp   Month     Day 
##       0       0       0       0       0       0
describe(knn_im_p)
##         vars   n  mean   sd median trimmed   mad   min   max range  skew
## Ozone      1 153 -0.04 0.92  -0.31   -0.16  0.72 -1.25  3.82  5.06  1.30
## Solar.R    2 153 -0.01 0.99   0.17    0.03  1.05 -1.99  1.64  3.63 -0.39
## Wind       3 153  0.00 1.00  -0.07   -0.02  0.97 -2.34  3.05  5.39  0.34
## Temp       4 153  0.00 1.00   0.12    0.04  0.94 -2.31  2.02  4.33 -0.37
## Month      5 153  6.99 1.42   7.00    6.99  1.48  5.00  9.00  4.00  0.00
## Day        6 153 15.80 8.86  16.00   15.80 11.86  1.00 31.00 30.00  0.00
##         kurtosis   se
## Ozone       1.62 0.07
## Solar.R    -0.99 0.08
## Wind        0.03 0.08
## Temp       -0.46 0.08
## Month      -1.32 0.11
## Day        -1.22 0.72
median_im<-preProcess(airquality[1:4],method = "medianImpute")
head(predict(median_im,airquality))
##   Ozone Solar.R Wind Temp Month Day
## 1  41.0     190  7.4   67     5   1
## 2  36.0     118  8.0   72     5   2
## 3  12.0     149 12.6   74     5   3
## 4  18.0     313 11.5   62     5   4
## 5  31.5     205 14.3   56     5   5
## 6  28.0     205 14.9   66     5   6
library(mlbench)
data("BostonHousing")
x=BostonHousing[,c("age","lstat","tax")]
y=BostonHousing$medv
featurePlot(x,
            y=BostonHousing$medv,
            plot = "scatter",
            layout=c(3,1))

data("PimaIndiansDiabetes")
PimaIndiansDiabetes %>% count(diabetes)
##   diabetes   n
## 1      neg 500
## 2      pos 268
glimpse(PimaIndiansDiabetes)
## Rows: 768
## Columns: 9
## $ pregnant <dbl> 6, 1, 8, 1, 0, 5, 3, 10, 2, 8, 4, 10, 10, 1, 5, 7, 0, 7, 1, 1…
## $ glucose  <dbl> 148, 85, 183, 89, 137, 116, 78, 115, 197, 125, 110, 168, 139,…
## $ pressure <dbl> 72, 66, 64, 66, 40, 74, 50, 0, 70, 96, 92, 74, 80, 60, 72, 0,…
## $ triceps  <dbl> 35, 29, 0, 23, 35, 0, 32, 0, 45, 0, 0, 0, 0, 23, 19, 0, 47, 0…
## $ insulin  <dbl> 0, 0, 0, 94, 168, 0, 88, 0, 543, 0, 0, 0, 0, 846, 175, 0, 230…
## $ mass     <dbl> 33.6, 26.6, 23.3, 28.1, 43.1, 25.6, 31.0, 35.3, 30.5, 0.0, 37…
## $ pedigree <dbl> 0.627, 0.351, 0.672, 0.167, 2.288, 0.201, 0.248, 0.134, 0.158…
## $ age      <dbl> 50, 31, 32, 21, 33, 30, 26, 29, 53, 54, 30, 34, 57, 59, 51, 3…
## $ diabetes <fct> pos, neg, pos, neg, pos, neg, pos, neg, pos, pos, neg, pos, n…
#install.packages("randomForest")
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## 다음의 패키지를 부착합니다: 'randomForest'
## The following object is masked from 'package:psych':
## 
##     outlier
## The following object is masked from 'package:ggplot2':
## 
##     margin
## The following object is masked from 'package:dplyr':
## 
##     combine
control<-trainControl(method = "repeatedcv",number=5)
model<-train(diabetes~.,data=PimaIndiansDiabetes,method="rf",
             preProcess=c("center","scale"),trControl=control)
model
## Random Forest 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## Pre-processing: centered (8), scaled (8) 
## Resampling: Cross-Validated (5 fold, repeated 1 times) 
## Summary of sample sizes: 615, 614, 614, 615, 614 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##   2     0.7694848  0.4809709
##   5     0.7577710  0.4552707
##   8     0.7538664  0.4471454
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
importance<-varImp(model,scale = FALSE)
plot(importance)

library(randomForest)

data("Sonar")
set.seed(998)
inTraining<-createDataPartition(y=Sonar$Class,p=.65,list=FALSE)
training<-Sonar[ inTraining,]
testing<-Sonar[-inTraining,]

set.seed(825)
#library(randomForest)
rffit<-train(Class~.,data=training,method="rf",preProc=c("center", "scale"))
rffit
## Random Forest 
## 
## 137 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## Pre-processing: centered (60), scaled (60) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 137, 137, 137, 137, 137, 137, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##    2    0.7728421  0.5369022
##   31    0.7554612  0.4988887
##   60    0.7607071  0.5100324
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
caret::trainControl
## function (method = "boot", number = ifelse(grepl("cv", method), 
##     10, 25), repeats = ifelse(grepl("[d_]cv$", method), 1, NA), 
##     p = 0.75, search = "grid", initialWindow = NULL, horizon = 1, 
##     fixedWindow = TRUE, skip = 0, verboseIter = FALSE, returnData = TRUE, 
##     returnResamp = "final", savePredictions = FALSE, classProbs = FALSE, 
##     summaryFunction = defaultSummary, selectionFunction = "best", 
##     preProcOptions = list(thresh = 0.95, ICAcomp = 3, k = 5, 
##         freqCut = 95/5, uniqueCut = 10, cutoff = 0.9), sampling = NULL, 
##     index = NULL, indexOut = NULL, indexFinal = NULL, timingSamps = 0, 
##     predictionBounds = rep(FALSE, 2), seeds = NA, adaptive = list(min = 5, 
##         alpha = 0.05, method = "gls", complete = TRUE), trim = FALSE, 
##     allowParallel = TRUE) 
## {
##     if (is.null(selectionFunction)) 
##         stop("null selectionFunction values not allowed")
##     if (!(returnResamp %in% c("all", "final", "none"))) 
##         stop("incorrect value of returnResamp")
##     if (length(predictionBounds) > 0 && length(predictionBounds) != 
##         2) 
##         stop("'predictionBounds' should be a logical or numeric vector of length 2")
##     if (any(names(preProcOptions) == "method")) 
##         stop("'method' cannot be specified here")
##     if (any(names(preProcOptions) == "x")) 
##         stop("'x' cannot be specified here")
##     if (!is.na(repeats) & !(method %in% c("repeatedcv", "adaptive_cv"))) 
##         warning("`repeats` has no meaning for this resampling method.", 
##             call. = FALSE)
##     if (!(adaptive$method %in% c("gls", "BT"))) 
##         stop("incorrect value of adaptive$method")
##     if (adaptive$alpha < 1e-07 | adaptive$alpha > 1) 
##         stop("incorrect value of adaptive$alpha")
##     if (grepl("adapt", method)) {
##         num <- if (method == "adaptive_cv") 
##             number * repeats
##         else number
##         if (adaptive$min >= num) 
##             stop(paste("adaptive$min should be less than", num))
##         if (adaptive$min <= 1) 
##             stop("adaptive$min should be greater than 1")
##     }
##     if (!(search %in% c("grid", "random"))) 
##         stop("`search` should be either 'grid' or 'random'")
##     if (method == "oob" & any(names(match.call()) == "summaryFunction")) {
##         warning("Custom summary measures cannot be computed for out-of-bag resampling. ", 
##             "This value of `summaryFunction` will be ignored.", 
##             call. = FALSE)
##     }
##     list(method = method, number = number, repeats = repeats, 
##         search = search, p = p, initialWindow = initialWindow, 
##         horizon = horizon, fixedWindow = fixedWindow, skip = skip, 
##         verboseIter = verboseIter, returnData = returnData, returnResamp = returnResamp, 
##         savePredictions = savePredictions, classProbs = classProbs, 
##         summaryFunction = summaryFunction, selectionFunction = selectionFunction, 
##         preProcOptions = preProcOptions, sampling = sampling, 
##         index = index, indexOut = indexOut, indexFinal = indexFinal, 
##         timingSamps = timingSamps, predictionBounds = predictionBounds, 
##         seeds = seeds, adaptive = adaptive, trim = trim, allowParallel = allowParallel)
## }
## <bytecode: 0x000001d394854d18>
## <environment: namespace:caret>
fitControl <- trainControl(method = "repeatedcv",
                           number = 10,
                           repeats = 10,
                           ## Estimate class probabilities
                           classProbs = TRUE,
                           ## Evaluate performance using
                           ## the following function
                           summaryFunction = twoClassSummary)

set.seed(825)
rmfit1 <- train(Class ~ ., data = training,
                 method = "rf",
                 trControl = fitControl,
                 verbose = FALSE,
                 ## Specify which metric to optimize
                 metric = "ROC")
rmfit1
## Random Forest 
## 
## 137 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 10 times) 
## Summary of sample sizes: 124, 124, 123, 123, 124, 123, ... 
## Resampling results across tuning parameters:
## 
##   mtry  ROC        Sens       Spec     
##    2    0.9277742  0.8853571  0.6483333
##   31    0.9105676  0.8676786  0.6800000
##   60    0.8999192  0.8633929  0.6916667
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
set.seed(825)
customGrid <- expand.grid(mtry = 1:10)
rffit2 <- train(Class ~ ., data = training, method = "rf", trControl =
                   fitControl,tuneGrid = customGrid, metric = "ROC")
rffit2
## Random Forest 
## 
## 137 samples
##  60 predictor
##   2 classes: 'M', 'R' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 10 times) 
## Summary of sample sizes: 124, 124, 123, 123, 124, 123, ... 
## Resampling results across tuning parameters:
## 
##   mtry  ROC        Sens       Spec     
##    1    0.9224235  0.8933929  0.6654762
##    2    0.9334354  0.8889286  0.6559524
##    3    0.9265391  0.8850000  0.6538095
##    4    0.9265476  0.8923214  0.6438095
##    5    0.9246769  0.8812500  0.6490476
##    6    0.9227041  0.8775000  0.6509524
##    7    0.9235587  0.8798214  0.6464286
##    8    0.9261437  0.8775000  0.6721429
##    9    0.9189796  0.8732143  0.6578571
##   10    0.9184694  0.8769643  0.6530952
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
predict(rmfit1,newdata=head(testing))
## [1] R R M M R R
## Levels: M R
predict(rmfit1,newdata=head(testing),type='prob')
##        M     R
## 4  0.412 0.588
## 6  0.484 0.516
## 7  0.574 0.426
## 8  0.632 0.368
## 10 0.262 0.738
## 11 0.106 0.894
predict(rmfit1,newdata=testing) %>% confusionMatrix(testing$Class)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  M  R
##          M 32  7
##          R  6 26
##                                           
##                Accuracy : 0.8169          
##                  95% CI : (0.7073, 0.8987)
##     No Information Rate : 0.5352          
##     P-Value [Acc > NIR] : 6.544e-07       
##                                           
##                   Kappa : 0.6312          
##                                           
##  Mcnemar's Test P-Value : 1               
##                                           
##             Sensitivity : 0.8421          
##             Specificity : 0.7879          
##          Pos Pred Value : 0.8205          
##          Neg Pred Value : 0.8125          
##              Prevalence : 0.5352          
##          Detection Rate : 0.4507          
##    Detection Prevalence : 0.5493          
##       Balanced Accuracy : 0.8150          
##                                           
##        'Positive' Class : M               
## 
#install.packages("caTools")
library(caTools)

df<-read.csv("diagnosis.csv")
glimpse(df)
## Rows: 569
## Columns: 32
## $ id                      <int> 842302, 842517, 84300903, 84348301, 84358402, …
## $ diagnosis               <chr> "M", "M", "M", "M", "M", "M", "M", "M", "M", "…
## $ radius_mean             <dbl> 17.990, 20.570, 19.690, 11.420, 20.290, 12.450…
## $ texture_mean            <dbl> 10.38, 17.77, 21.25, 20.38, 14.34, 15.70, 19.9…
## $ perimeter_mean          <dbl> 122.80, 132.90, 130.00, 77.58, 135.10, 82.57, …
## $ area_mean               <dbl> 1001.0, 1326.0, 1203.0, 386.1, 1297.0, 477.1, …
## $ smoothness_mean         <dbl> 0.11840, 0.08474, 0.10960, 0.14250, 0.10030, 0…
## $ compactness_mean        <dbl> 0.27760, 0.07864, 0.15990, 0.28390, 0.13280, 0…
## $ concavity_mean          <dbl> 0.30010, 0.08690, 0.19740, 0.24140, 0.19800, 0…
## $ concave.points_mean     <dbl> 0.14710, 0.07017, 0.12790, 0.10520, 0.10430, 0…
## $ symmetry_mean           <dbl> 0.2419, 0.1812, 0.2069, 0.2597, 0.1809, 0.2087…
## $ fractal_dimension_mean  <dbl> 0.07871, 0.05667, 0.05999, 0.09744, 0.05883, 0…
## $ radius_se               <dbl> 1.0950, 0.5435, 0.7456, 0.4956, 0.7572, 0.3345…
## $ texture_se              <dbl> 0.9053, 0.7339, 0.7869, 1.1560, 0.7813, 0.8902…
## $ perimeter_se            <dbl> 8.589, 3.398, 4.585, 3.445, 5.438, 2.217, 3.18…
## $ area_se                 <dbl> 153.40, 74.08, 94.03, 27.23, 94.44, 27.19, 53.…
## $ smoothness_se           <dbl> 0.006399, 0.005225, 0.006150, 0.009110, 0.0114…
## $ compactness_se          <dbl> 0.049040, 0.013080, 0.040060, 0.074580, 0.0246…
## $ concavity_se            <dbl> 0.05373, 0.01860, 0.03832, 0.05661, 0.05688, 0…
## $ concave.points_se       <dbl> 0.015870, 0.013400, 0.020580, 0.018670, 0.0188…
## $ symmetry_se             <dbl> 0.03003, 0.01389, 0.02250, 0.05963, 0.01756, 0…
## $ fractal_dimension_se    <dbl> 0.006193, 0.003532, 0.004571, 0.009208, 0.0051…
## $ radius_worst            <dbl> 25.38, 24.99, 23.57, 14.91, 22.54, 15.47, 22.8…
## $ texture_worst           <dbl> 17.33, 23.41, 25.53, 26.50, 16.67, 23.75, 27.6…
## $ perimeter_worst         <dbl> 184.60, 158.80, 152.50, 98.87, 152.20, 103.40,…
## $ area_worst              <dbl> 2019.0, 1956.0, 1709.0, 567.7, 1575.0, 741.6, …
## $ smoothness_worst        <dbl> 0.1622, 0.1238, 0.1444, 0.2098, 0.1374, 0.1791…
## $ compactness_worst       <dbl> 0.6656, 0.1866, 0.4245, 0.8663, 0.2050, 0.5249…
## $ concavity_worst         <dbl> 0.71190, 0.24160, 0.45040, 0.68690, 0.40000, 0…
## $ concave.points_worst    <dbl> 0.26540, 0.18600, 0.24300, 0.25750, 0.16250, 0…
## $ symmetry_worst          <dbl> 0.4601, 0.2750, 0.3613, 0.6638, 0.2364, 0.3985…
## $ fractal_dimension_worst <dbl> 0.11890, 0.08902, 0.08758, 0.17300, 0.07678, 0…
df<-df %>% select(-id)
df$diagnosis<-as.factor(df$diagnosis)
prop.table(table(df$diagnosis))
## 
##         B         M 
## 0.6274165 0.3725835
any(is.na(df))
## [1] FALSE
set.seed(3)
inTraining<-createDataPartition(y=df$diagnosis,p=.75,list=FALSE)
training<-df[ inTraining,]
testing<-df[-inTraining,]

my_trainControl<-trainControl(method = "cv",
                              number=5,
                              classProbs = TRUE,
                              summaryFunction = twoClassSummary)

library(glmnet)
## 필요한 패키지를 로딩중입니다: Matrix
## Loaded glmnet 4.1-8
glmnetfit<-train(diagnosis~.,data=training,
                 method="glmnet",
                 trControl=fitControl,
                 verbose=FALSE,
                 metric="ROC")

my_trainControl<-trainControl(method = "cv",
                              number=5,
                              classProbs = TRUE,
                              summaryFunction = twoClassSummary)

rffit<-train(diagnosis~.,data=training,
             method="rf",
             trControl=fitControl,
             verbose=FALSE,
             metric="ROC")

#install.packages("lubridate")
library(lubridate)
## 
## 다음의 패키지를 부착합니다: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
#install.packages("nycflights13")
library(nycflights13)
data("flights")
glimpse(flights)
## Rows: 336,776
## Columns: 19
## $ year           <int> 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2…
## $ month          <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ day            <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ dep_time       <int> 517, 533, 542, 544, 554, 554, 555, 557, 557, 558, 558, …
## $ sched_dep_time <int> 515, 529, 540, 545, 600, 558, 600, 600, 600, 600, 600, …
## $ dep_delay      <dbl> 2, 4, 2, -1, -6, -4, -5, -3, -3, -2, -2, -2, -2, -2, -1…
## $ arr_time       <int> 830, 850, 923, 1004, 812, 740, 913, 709, 838, 753, 849,…
## $ sched_arr_time <int> 819, 830, 850, 1022, 837, 728, 854, 723, 846, 745, 851,…
## $ arr_delay      <dbl> 11, 20, 33, -18, -25, 12, 19, -14, -8, 8, -2, -3, 7, -1…
## $ carrier        <chr> "UA", "UA", "AA", "B6", "DL", "UA", "B6", "EV", "B6", "…
## $ flight         <int> 1545, 1714, 1141, 725, 461, 1696, 507, 5708, 79, 301, 4…
## $ tailnum        <chr> "N14228", "N24211", "N619AA", "N804JB", "N668DN", "N394…
## $ origin         <chr> "EWR", "LGA", "JFK", "JFK", "LGA", "EWR", "EWR", "LGA",…
## $ dest           <chr> "IAH", "IAH", "MIA", "BQN", "ATL", "ORD", "FLL", "IAD",…
## $ air_time       <dbl> 227, 227, 160, 183, 116, 150, 158, 53, 140, 138, 149, 1…
## $ distance       <dbl> 1400, 1416, 1089, 1576, 762, 719, 1065, 229, 944, 733, …
## $ hour           <dbl> 5, 5, 5, 5, 6, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 6, 6, 6…
## $ minute         <dbl> 15, 29, 40, 45, 0, 58, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 0…
## $ time_hour      <dttm> 2013-01-01 05:00:00, 2013-01-01 05:00:00, 2013-01-01 0…
#view(flights)

today()
## [1] "2024-01-31"
now()
## [1] "2024-01-31 16:48:22 KST"
ymd("2023-01-31")
## [1] "2023-01-31"
mdy("january 1st, 2023")
## [1] "2023-01-01"
dmy("31-jan-2023")
## [1] "2023-01-31"
ymd(20230131)
## [1] "2023-01-31"
#install.packages("plyr")
library(plyr)
## ------------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## ------------------------------------------------------------------------------
## 
## 다음의 패키지를 부착합니다: 'plyr'
## The following objects are masked from 'package:dplyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
df<-read.csv("Data1.csv")
df$Gender<-as.factor(df$Gender)
df$Gender<-revalue(df$Gender,replace=c("0"="female","1"="male"))
glimpse(df)
## Rows: 1,925
## Columns: 27
## $ X         <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1…
## $ Q1        <int> 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, …
## $ Q2        <int> 4, 4, 4, 4, 4, 4, 2, 2, 4, 4, 4, 4, 4, 2, 4, 4, 2, 4, 2, 2, …
## $ Q3        <int> 2, 4, 4, 4, 4, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 4, 4, 3, 2, 3, …
## $ Q4        <int> 3, 4, 4, 4, 4, 4, 4, 4, 4, 2, 4, 4, 4, 2, 4, 4, 4, 2, 2, 4, …
## $ Q5        <int> 4, 4, 2, 4, 4, 4, 4, 4, 2, 4, 4, 2, 4, 4, 4, 4, 4, 3, 1, 2, …
## $ Q6        <int> 2, 3, 4, 4, 4, 4, 4, 4, 1, 2, 2, 2, 4, 4, 3, 5, 2, 2, 1, 4, …
## $ Q7        <int> 2, 2, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 5, 4, 4, 5, 4, 3, 4, 4, …
## $ Q8        <int> 4, 4, 4, 4, 4, 4, 5, 5, 2, 2, 4, 4, 4, 4, 3, 5, 4, 2, 4, 4, …
## $ Q9        <int> 4, 4, 4, 4, 2, 4, 5, 5, 3, 4, 4, 4, 2, 2, 4, 5, 2, 4, 2, 4, …
## $ Q10       <int> 4, 4, 2, 4, 4, 4, 5, 5, 2, 4, 2, 4, 4, 4, 3, 4, 4, 3, 2, 3, …
## $ Q11       <int> 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 3, 4, 4, 4, 4, 5, 4, 3, 3, …
## $ Q12       <int> 4, 4, 4, 4, 4, 4, 5, 5, 3, 4, 4, 3, 4, 3, 3, 4, 5, 4, 4, 2, …
## $ Q13       <int> 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 4, 4, 2, 4, 4, 4, 5, 4, 4, 4, …
## $ Q14       <int> 4, 4, 4, 4, 4, 4, 5, 5, 5, 4, 4, 4, 3, 4, 5, 4, 5, 4, 4, 4, …
## $ Q15       <int> 4, 4, 3, 4, 4, 4, 4, 2, 3, 4, 4, 3, 1, 4, 4, 4, 5, 4, 4, 4, …
## $ Q16       <int> 4, 4, 4, 4, 4, 4, 5, 2, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 4, 4, …
## $ Q17       <int> 4, 3, 4, 4, 4, 4, 2, 2, 4, 4, 4, 4, 3, 2, 4, 5, 4, 4, 3, 4, …
## $ Q18       <int> 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 2, 4, 4, 4, …
## $ Q19       <int> 4, 2, 4, 4, 4, 4, 4, 2, 4, 2, 4, 4, 1, 4, 4, 4, 5, 4, 2, 3, …
## $ Q20       <int> 4, 1, 3, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 2, 4, 5, 5, 4, 2, 4, …
## $ Gender    <fct> female, female, female, female, female, female, female, fema…
## $ EDU       <int> 1, 1, 2, 1, 2, 1, 1, 1, 4, 3, 2, 1, 1, 3, 3, 2, 1, 1, 1, 4, …
## $ BF        <dbl> 3.4, 4.0, 3.6, 4.2, 4.0, 4.0, 3.6, 3.6, 3.6, 3.2, 4.0, 3.2, …
## $ BM        <dbl> 3.2, 3.4, 3.6, 4.0, 3.6, 4.0, 4.6, 4.6, 2.2, 3.2, 3.2, 3.6, …
## $ Happiness <dbl> 4.0, 4.0, 3.8, 4.0, 4.0, 4.0, 4.8, 4.4, 3.8, 4.0, 4.0, 3.4, …
## $ Peace     <dbl> 4.0, 2.8, 3.8, 4.0, 4.0, 4.0, 3.8, 2.4, 4.0, 3.2, 4.0, 3.9, …
table(df$Gender)
## 
## female   male 
##   1136    789
colSums(is.na(df))
##         X        Q1        Q2        Q3        Q4        Q5        Q6        Q7 
##         0         0         0         0         0         0         0         0 
##        Q8        Q9       Q10       Q11       Q12       Q13       Q14       Q15 
##         0         0         0         0         0         0         0         0 
##       Q16       Q17       Q18       Q19       Q20    Gender       EDU        BF 
##         0         0         0         0         0         0         0         0 
##        BM Happiness     Peace 
##         0         0         0
zs_df<-preProcess(df,method = c("center","scale"))
zs_df
## Created from 1925 samples and 27 variables
## 
## Pre-processing:
##   - centered (26)
##   - ignored (1)
##   - scaled (26)
set.seed(700)
inTraining<-createDataPartition(y=df$Gender,p=.75,list=FALSE)
training<-df[ inTraining,]
testing<-df[-inTraining,]

set.seed(825)
rffit <- train(Gender ~ ., data = training, # target,predictor 변수
                method = "rf", # 모델 학습 알고리즘
                preProc = c("center", "scale")) # 중심화,척도화 수행
rffit
## Random Forest 
## 
## 1444 samples
##   26 predictor
##    2 classes: 'female', 'male' 
## 
## Pre-processing: centered (26), scaled (26) 
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 1444, 1444, 1444, 1444, 1444, 1444, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##    2    0.6118544  0.1512735
##   14    0.6018369  0.1471643
##   26    0.5976381  0.1404436
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
predict(rffit,newdata=head(testing))
## [1] female female female female female female
## Levels: female male
predict(rffit,newdata=head(testing),type='prob')
##    female  male
## 3   0.776 0.224
## 9   0.620 0.380
## 17  0.722 0.278
## 19  0.762 0.238
## 26  0.556 0.444
## 28  0.752 0.248