# R编程中的随机森林法详细指南

2021年3月10日15:54:35 发表评论 732 次浏览

#### 理论

• 绘制一个大小随机的引导样本ñ(随机选择ñ训练数据样本)。
• 从引导程序样本中增长决策树。在树的每个节点上, 随机选择d特征。
• 使用根据目标函数提供最佳拆分的特征(变量)拆分节点。例如, 通过最大化信息增益。
• 重复步骤1到步骤2, ķ次(k是要使用样本子集创建的树的数量)。
• 汇总每棵树对新数据点的预测, 以多数表决方式分配类别标签, 即选择最多树数选择的组, 然后为该组分配新数据点。

#### 数据集

``````# Loading data
data(iris)

# Structure
str (iris)``````

#### 对数据集执行随机森林

``````# Installing package
install.packages( "caTools" )       # For sampling the dataset
install.packages( "randomForest" )  # For implementing random forest algorithm

library(caTools)
library(randomForest)

# Splitting data in train and test data
split < - sample.split(iris, SplitRatio = 0.7 )
split

train < - subset(iris, split = = "TRUE" )
test < - subset(iris, split = = "FALSE" )

# Fitting Random Forest to the train dataset
set .seed( 120 )  # Setting seed
classifier_RF = randomForest(x = train[ - 5 ], y = train\$Species, ntree = 500 )

classifier_RF

# Predicting the Test set results
y_pred = predict(classifier_RF, newdata = test[ - 5 ])

# Confusion Matrix
confusion_mtx = table(test[, 5 ], y_pred)
confusion_mtx

# Plotting model
plot(classifier_RF)

# Importance plot
importance(classifier_RF)

# Variable importance plot
varImpPlot(classifier_RF)``````
{"ft_lang_label":"__label__zh","ft_lang_prob":0.73311424,"math_prob":0.92064464,"size":2128,"snap":"2023-14-2023-23","text_gpt3_token_len":1435,"char_repetition_ratio":0.09039548,"word_repetition_ratio":0.019417476,"special_character_ratio":0.22979324,"punctuation_ratio":0.21352313,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9860697,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-31T18:24:36Z\",\"WARC-Record-ID\":\"<urn:uuid:a8ae182e-b46d-4011-ae11-48d9aa624e4c>\",\"Content-Length\":\"73979\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e349635d-1b3c-41c4-8ed1-ef21bd72b4d7>\",\"WARC-Concurrent-To\":\"<urn:uuid:46415231-6235-4f69-ac84-6103446c3cd9>\",\"WARC-IP-Address\":\"8.210.201.97\",\"WARC-Target-URI\":\"https://www.lsbin.com/610.html\",\"WARC-Payload-Digest\":\"sha1:MLA5ZU2C2UVGWIZSFXTSCAKYSTEGDNRK\",\"WARC-Block-Digest\":\"sha1:J2VXHFWJHGZ5AEZ54EKFWDKKKGYOKK5H\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296949678.39_warc_CC-MAIN-20230331175950-20230331205950-00551.warc.gz\"}"}