����λ�ã���ҳ > �����̳� > �̳� > ���ɭ��R����Ԥ�⹤��

���ɭ��R����Ԥ�⹤��

��Դ������������|��ʱ�䣺2024-07-01 11:56:46 |���Ķ���145��|�� ��ǩ�� ɭ�� �� |����������

������ϸ������R���Խ���Ԥ��Ĵ���ʾ�����Լ����ɭ��R���Ե�Ӧ��ʵ����ͬʱ��ϸ���������ɭ�ֵ�Ӧ��ʵ������������ϸ�Ĵ���ʾ�����������⣬�ɻ�������

���ɭ�֣�Random Forest����һ�ֻ��ھ������ļ���ѧϰ��������ͨ������������������������ǵ�Ԥ���������Ԥ���׼ȷ�ԡ���R�����У����ǿ���ʹ�� randomForest ����������ѵ�����ɭ��ģ�͡������Ƕ����ɭ�ֵ���ϸ�����Լ�ʹ��R���Խ���Ԥ��Ĵ���ʾ����

1. R���Խ���Ԥ��Ĵ���ʾ��

1.1 ���ɭ�ּ��

���ɭ��ͨ�����²�����й�����

��1�� ������������Bootstrap Sampling�� ����ԭʼ���ݼ����зŻص������ȡ���������������ѵ����þ�������

��2�� �������ѡ�� ����ѵ��ÿ�þ�����ʱ�����������������ѡ��һ�����������нڵ���ѡ�

��3�� ���������� �����������������õ��������������ѡ�����������������þ�������

��4�� ����Ԥ�� �����ڷ������⣬ͨ��ͶƱ��������ͶƱ���������о�������Ԥ���������ڻع����⣬ͨ��ȡƽ��ֵ�������о�������Ԥ������

���ɭ�ֵ��ŵ������

  • ���Դ�����ά���ݣ������������ѡ��
  • �ܹ�ѧϰ����֮����໥Ӱ�죬�Ҳ����׹���ϡ�
  • ���ڲ�ƽ������ݼ�������ƽ����
  • ��ȵ�һ�����������и��ߵ�Ԥ��׼ȷ�ԡ�

1.2 R���Դ���ʾ��

������һ��ʹ��R�����е� randomForest ���������ɭ��Ԥ��Ĵ���ʾ����

# ��װrandomForest���������δ��װ��  
install.packages("randomForest")  
  
# ����randomForest��  
library(randomForest)  
  
# �������ݼ���������iris���ݼ�Ϊ����  
data(iris)  
  
# ����ѵ�����Ͳ��Լ�  
set.seed(123) # ������������Ա�֤����Ŀ��ظ���  
train_index <- sample(1:nrow(iris), nrow(iris)*0.7) # ���ѡ��70%��������Ϊѵ����  
train_data <- iris[train_index,]  
test_data <- iris[-train_index,]  
  
# ʹ��randomForest����ѵ�����ɭ��ģ��  
# ntreeָ����������������mtryָ��ÿ�η���ʱ���ѡ�����������  
model <- randomForest(Species ~ ., data=train_data, ntree=500, mtry=2)  
  
# ʹ��ѵ���õ�ģ�ͶԲ��Լ�����Ԥ��  
predictions <- predict(model, newdata=test_data)  
  
# ���������  
# ���ڷ������⣬���Լ���׼ȷ�ʡ����������ָ��  
confusionMatrix <- table(predictions, test_data$Species)  
accuracy <- sum(diag(confusionMatrix)) / sum(confusionMatrix)  
print(paste("Accuracy:", accuracy))  
  
# �����Ҫ�������Ի���������Ҫ��ͼ  
# importance(model) # ����������Ҫ�Ծ���  
# plot(importance(model)) # ����������Ҫ��ͼ

1.3 ʵ��Ӧ������

���ɭ����ʵ��Ӧ���о��й㷺�����壬�ر����ڴ����������ݼ��ͽ���Ԥ�����ʱ�����磬��������Ϣѧ��ҽѧ��ϡ�����Ԥ����������ɭ�ֿ������ڷ��ࡢ�ع顢����ѡ������⡣ͨ�����ɶ�þ�������Ԥ���������ɭ�ֿ������Ԥ���׼ȷ�ԣ������͹���ϵķ��ա����⣬���ɭ�ֻ������ṩ������Ҫ������������������������Щ������Ԥ����������ҪӰ�졣

2. ���ɭ��R����Ӧ��ʵ��

��̸�����ɭ�ֵ�Ӧ��ʵ��ʱ��������һЩ����ij����Լ����ʹ��R�����е� randomForest ����ʵ����Щʵ������ϸ����ʾ����

2.1 ������ϣ������ٰ����Ϊ����

2.1.1 ���ݼ������ٰ����ݼ��� breastCancer ��

����������һ�����ٰ����ݼ������а���һЩ�방֢��ص�������һ�������������Ƿ�Ϊ���ԣ������ǵ�Ŀ����ѵ��һ�����ɭ��ģ����Ԥ���µIJ����Ƿ�Ϊ���ԡ�

2.1.2 ����ʾ��

# ���ر�Ҫ�İ�  
library(randomForest)  
  
# �������ݼ���������������Ѿ�����breastCancer���ݼ���  
# �����Ҫ�����Դ��ⲿ����Դ���أ���read.csv  
data(breastCancer, package = "mlbench") # ����breastCancer��mlbench����  
  
# ����ѵ�����Ͳ��Լ�  
set.seed(123) # Ϊ�˽���Ŀɸ�����  
trainIndex <- sample(1:nrow(breastCancer), nrow(breastCancer)*0.7)  
trainData <- breastCancer[trainIndex, ]  
testData <- breastCancer[-trainIndex, ]  
  
# ʹ�����ɭ��ģ�ͽ���ѵ��  
rfModel <- randomForest(Class ~ ., data = trainData, ntree = 500, importance = TRUE)  
  
# �ڲ��Լ��Ͻ���Ԥ��  
predictions <- predict(rfModel, newdata = testData)  
  
# �鿴���������׼ȷ��  
confusionMatrix <- table(predictions, testData$Class)  
accuracy <- sum(diag(confusionMatrix)) / sum(confusionMatrix)  
print(paste("Accuracy:", accuracy))  
  
# �鿴������Ҫ��  
importance(rfModel)  
  
# ����������Ҫ��ͼ  
plot(rfModel, main="Feature Importance")

2.2 ����Ԥ��

2.2.1 ���ݼ����������ݼ�������Ϊ housingData ��

����������һ���������ݼ������а������ݵĸ�������������������������ضεȣ��ͷ��ݵļ۸����ǵ�Ŀ����Ԥ���·��ݵļ۸�

2.2.2 ����ʾ��

# ���ر�Ҫ�İ�  
library(randomForest)  
  
# ����housingData�Ѿ����ص�R������  
# �����Ҫ�����Դ��ⲿ����Դ���أ���read.csv  
  
# ����������Ŀ�����  
features <- housingData[, -ncol(housingData)] # �������һ���Ǽ۸�  
prices <- housingData[, ncol(housingData)]  
  
# ����ѵ�����Ͳ��Լ�  
set.seed(123)  
trainIndex <- sample(1:nrow(housingData), nrow(housingData)*0.7)  
trainFeatures <- features[trainIndex, ]  
trainPrices <- prices[trainIndex]  
testFeatures <- features[-trainIndex, ]  
testPrices <- prices[-trainIndex]  
  
# ʹ�����ɭ��ģ�ͽ���ѵ��  
rfModel <- randomForest(trainPrices ~ ., data = data.frame(trainPrices, trainFeatures), ntree = 500, importance = TRUE)  
  
# �ڲ��Լ��Ͻ���Ԥ��  
predictedPrices <- predict(rfModel, newdata = data.frame(testPrices = rep(NA, nrow(testFeatures)), testFeatures))  
  
# ����Ԥ���������磬ʹ�þ�����  
mse <- mean((predictedPrices - testPrices)^2)  
print(paste("Mean Squared Error:", mse))  
  
# �鿴������Ҫ��  
importance(rfModel)  
  
# ����������Ҫ��ͼ  
plot(rfModel, main="Feature Importance")

��ע�⣬��������ʾ���е����ݼ��� breastCancer �� housingData ���Ǽ���ģ����ҿ�����Ҫ���ⲿ����Դ���ء����⣬���ڷ���Ԥ�⣬���Ǽ���۸��������ݼ������һ�У�������ʵ��Ӧ���п�����Ҫ��һ��������Ԥ�������������̡�ͬ�������ɭ�ֵIJ������� ntree ��Ҳ���Ը��ݾ���������е�����

��R�����У����ǿ���ʹ�ö��ְ�������Ԥ�⣬���� randomForest �� caret �� e1071 ������SVM���� glmnet �����ڵ�������ع飩�ȡ������ҽ���������ʹ��R���Խ���Ԥ��Ĵ���ʾ����

2.3 ʹ�����ɭ�ֽ���Ԥ��

���ȣ�������Ҫ��װ������ randomForest ���������δ��װ����

# ��װrandomForest���������δ��װ��  
install.packages("randomForest")  
  
# ����randomForest��  
library(randomForest)  
  
# ���ػ򴴽�����  
# ��������ʹ��iris���ݼ���Ϊʾ��  
data(iris)  
  
# �����ݼ�����Ϊѵ�����Ͳ��Լ�  
set.seed(123) # Ϊ�˽���Ŀ��ظ���  
train_index <- sample(1:nrow(iris), 0.8 * nrow(iris))  
train_data <- iris[train_index, ]  
test_data <- iris[-train_index, ]  
  
# ʹ��ѵ����ѵ�����ɭ��ģ��  
rf_model <- randomForest(Species ~ ., data = train_data, ntree = 500)  
  
# ʹ�ò��Լ�����Ԥ��  
rf_predictions <- predict(rf_model, newdata = test_data)  
  
# �鿴Ԥ����  
print(table(test_data$Species, rf_predictions))  
  
# ����Ԥ��׼ȷ��  
accuracy <- sum(test_data$Species == rf_predictions) / nrow(test_data)  
print(paste("Accuracy:", accuracy))

2.4 ʹ���߼��ع����Ԥ�⣨���������⣩

# ����MASS���������δ��װ��  
# MASS�������������߼��ع�Ķ�����ݼ�  
install.packages("MASS")  
library(MASS)  
  
# ʹ��MASS���е�Pima Indians Diabetes���ݼ�  
data(PimaIndiansDiabetes)  
  
# �����ݼ�����Ϊѵ�����Ͳ��Լ�  
set.seed(123)  
train_index <- sample(1:nrow(PimaIndiansDiabetes), 0.8 * nrow(PimaIndiansDiabetes))  
train_data <- PimaIndiansDiabetes[train_index, ]  
test_data <- PimaIndiansDiabetes[-train_index, ]  
  
# ʹ��ѵ����ѵ���߼��ع�ģ��  
glm_model <- glm(diabetes ~ ., data = train_data, family = binomial)  
  
# ʹ�ò��Լ�����Ԥ�⣨ע�⣺�߼��ع�Ԥ����Ǹ��ʣ���Ҫת��Ϊ���  
glm_probabilities <- predict(glm_model, newdata = test_data, type = "response")  
glm_predictions <- ifelse(glm_probabilities > 0.5, "pos", "neg")  
  
# �鿴Ԥ����  
print(table(test_data$diabetes, glm_predictions))  
  
# ����Ԥ��׼ȷ�ʣ�����'pos'�������࣬'neg'�������ࣩ  
accuracy <- sum(test_data$diabetes == (glm_predictions == "pos")) / nrow(test_data)  
print(paste("Accuracy:", accuracy))

2.5 ʹ��֧����������SVM������Ԥ��

# ��װe1071���������δ��װ��  
install.packages("e1071")  
library(e1071)  
  
# ʹ��iris���ݼ�  
data(iris)  
  
# �����ݼ�����Ϊѵ�����Ͳ��Լ�  
set.seed(123)  
train_index <- sample(1:nrow(iris), 0.8 * nrow(iris))  
train_data <- iris[train_index, ]  
test_data <- iris[-train_index, ]  
  
# ��Speciesת��Ϊ�������ͣ������δ�ǣ�  
train_data$Species <- as.factor(train_data$Species)  
test_data$Species <- as.factor(test_data$Species)  
  
# ʹ��ѵ����ѵ��SVMģ��  
svm_model <- svm(Species ~ ., data = train_data, kernel = "radial", cost = 10, gamma = 0.1)  
  
# ʹ�ò��Լ�����Ԥ��  
svm_predictions <- predict(svm_model, newdata = test_data)  
  
# �鿴Ԥ����  
print(table(test_data$Species, svm_predictions))  
  
# ����Ԥ��׼ȷ��  
accuracy <- sum(test_data$Species == svm_predictions) / nrow(test_data)  
print(paste("Accuracy:", accuracy))

���ϴ���ʾ��չʾ�������R������ʹ�����ɭ�֡��߼��ع��֧������������Ԥ�⣬��������Ԥ��׼ȷ�ʡ���ע�⣬��Щʾ��ʹ�������õ����ݼ�

3. ���ɭ�ֵ�Ӧ��ʵ��

3.1 �β�����ݼ����ࣨIris Dataset Classification��

�β�����ݼ���һ�����õķ������ݼ�������150��������ÿ���������ĸ����������೤�ȡ�������ȡ����곤�ȡ�������ȣ������ڷ��������β����

from sklearn.datasets import load_iris  
from sklearn.model_selection import train_test_split  
from sklearn.ensemble import RandomForestClassifier  
from sklearn.metrics import accuracy_score  
  
# �����β�����ݼ�  
iris = load_iris()  
X = iris.data  
y = iris.target  
  
# ����ѵ�����Ͳ��Լ�  
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)  
  
# �������ɭ�ַ�����  
clf = RandomForestClassifier(n_estimators=100, random_state=42)  
  
# ѵ��ģ��  
clf.fit(X_train, y_train)  
  
# Ԥ����Լ�  
y_pred = clf.predict(X_test)  
  
# ����׼ȷ��  
accuracy = accuracy_score(y_test, y_pred)  
print(f"Accuracy: {accuracy}")

3.2 ����Ԥ�⣨Housing Price Prediction��

����������һ���������ݼ����������ݵ����������������������¥�����ȣ��Ͷ�Ӧ�ķ��ۡ�

import pandas as pd  
from sklearn.model_selection import train_test_split  
from sklearn.ensemble import RandomForestRegressor  
from sklearn.metrics import mean_squared_error  
  
# �������ݣ��������������һ��CSV�ļ���  
data = pd.read_csv('housing_data.csv')  
X = data.drop('price', axis=1)  # ����  
y = data['price']  # Ŀ�����  
  
# ����ѵ�����Ͳ��Լ�  
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)  
  
# �������ɭ�ֻع���  
rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)  
  
# ѵ��ģ��  
rf_regressor.fit(X_train, y_train)  
  
# Ԥ����Լ�  
y_pred = rf_regressor.predict(X_test)  
  
# ����������  
mse = mean_squared_error(y_test, y_pred)  
print(f"Mean Squared Error: {mse}")

3.3 ��Ӱ������з�����Sentiment Analysis of Movie Reviews��

����������һ����Ӱ�������ݼ������������ı��Ͷ�Ӧ����б�ǩ��������棩��

from sklearn.datasets import fetch_20newsgroups  
from sklearn.feature_extraction.text import CountVectorizer  
from sklearn.model_selection import train_test_split  
from sklearn.ensemble import RandomForestClassifier  
from sklearn.metrics import classification_report  
  
# �������ݼ�������ʹ��20 Newsgroups���ݼ���һ���Ӽ���Ϊʾ����  
categories = ['alt.atheism', 'soc.religion.christian']  
newsgroups_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)  
X_train, y_train = newsgroups_train.data, newsgroups_train.target  
  
# �ı�������ȡ������ʹ�ô�Ƶ����������  
vectorizer = CountVectorizer()  
X_train_counts = vectorizer.fit_transform(X_train)  
  
# ����ѵ�����Ͳ��Լ�������Ϊ�˼򻯣�ֱ�Ӵ�ѵ�����л��֣�  
X_train_counts, X_test_counts, y_train, y_test = train_test_split(X_train_counts, y_train, test_size=0.2, random_state=42)  
  
# �������ɭ�ַ�����  
clf = RandomForestClassifier(n_estimators=100, random_state=42)  
  
# ѵ��ģ��  
clf.fit(X_train_counts, y_train)  
  
# Ԥ����Լ�  
y_pred = clf.predict(X_test_counts)  
  
# �����  
print(classification_report(y_test, y_pred

3.4 ͼ����ࣨImage Classification��

��Ȼ���ɭ��ͨ����ֱ������ԭʼ���ؼ����ͼ����ࣨ��Ϊ���ַ����ڴ�����ά����ʱ���ܲ�����Ч���������ǿ���ʹ�����ɭ��������ͼ����������HOG��SIFT��SURF�������������ߴ�Ԥѵ�������ѧϰģ������ȡ��������

������һ���򻯵����ӣ����������Ѿ�����һ������ͼ�������Ͷ�Ӧ��ǩ�����ݼ���

from sklearn.model_selection import train_test_split  
from sklearn.ensemble import RandomForestClassifier  
from sklearn.metrics import classification_report  
import numpy as np  
  
# ���������Ѿ�����һ����������X�����磬��ͼ������ȡ���������ͱ�ǩy  
# X = ... (��״Ϊ (n_samples, n_features) ��NumPy����)  
# y = ... (��״Ϊ (n_samples,) ��NumPy����)  
  
# Ϊ����ʾ�������������һЩģ������  
n_samples = 1000  
n_features = 64  # ����ÿ��ͼ�񱻱�ʾΪһ��64ά����������  
X = np.random.rand(n_samples, n_features)  
y = np.random.randint(0, 2, n_samples)  # ����������  
  
# ����ѵ�����Ͳ��Լ�  
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)  
  
# �������ɭ�ַ�����  
clf = RandomForestClassifier(n_estimators=100, random_state=42)  
  
# ѵ��ģ��  
clf.fit(X_train, y_train)  
  
# Ԥ����Լ�  
y_pred = clf.predict(X_test)  
  
# �����  
print(classification_report(y_test, y_pred))

3.5 ������Ҫ��������Feature Importance Evaluation��

���ɭ�ֲ����������ڷ���ͻع����񣬻���������������������Ҫ�ԡ����������ѡ��ͽ���ģ�ͽ���dz����á�

# ʹ��֮ǰ���β�����ݼ�ʾ��  
# ...���������ݡ�����ѵ�����Ͳ��Լ���ѵ��ģ�͵Ĵ��룩  
  
# ��ȡ������Ҫ��  
importances = clf.feature_importances_  
std = np.std([tree.feature_importances_ for tree in clf.estimators_], axis=0)  
indices = np.argsort(importances)[::-1]  
  
# ��ӡ��������  
print("Feature ranking:")  
  
for f in range(X.shape[1]):  
    print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))  
  
# ���ǿ���ʹ����Щ������Ҫ������������ͼ�����߸�����Ҫ��ѡ����ų�ijЩ����

���ϴ���ʾ��չʾ�����ɭ���ڲ�ͬ�����µ�Ӧ�ã��������ࡢ�ع顢������Ҫ�������ȡ�ע�⣬��Щʾ���е����ݺ���������ģ��Ļ�򻯵ģ�ʵ��Ӧ����������Ҫ�����Լ������ݼ����������������롣

3.6 �쳣��⣨Outlier Detection��

���ɭ��Ҳ���������쳣������Ⱥ���⡣ͨ���������ɭ��ģ�Ͳ�����ÿ����������Ҷ�ڵ��ƽ�����루���磬ʹ�ù���ɭ�� Isolation Forest�������ǿ���ʶ���������������ͬ���쳣�㡣

������һ��ʹ�� sklearn-extensions ���е� IsolationForest �����쳣����ʾ����ע�⣺ sklearn-extensions ������ scikit-learn �ٷ����һ���֣����ṩ�����Ƶ�ʵ�֣���

from sklearn_extensions.ensemble import IsolationForest  
import numpy as np  
  
# ���� X �����ǵ���������������������һЩģ������  
X = np.random.normal(size=(100, 2))  
# ����һ���쳣��  
X = np.r_[X + 2, np.array([[10, 10]])]  
  
# ���� IsolationForest ʵ��  
clf = IsolationForest(contamination=0.1)  # �������ݼ�����10%���쳣��  
  
# ����  
clf.fit(X)  
  
# Ԥ���쳣����������Խ�ͣ�Խ�������쳣�㣩  
y_pred = clf.predict(X)  
scores = clf.decision_function(X)  
  
# ��ӡ�쳣������Ԥ����  
for i, s in enumerate(scores):  
    print(f"Sample {i}: Score = {s}, Prediction = {y_pred[i]}")  
  
# ���ǿ�������һ����ֵ��ʶ���쳣��  
threshold = -0.5  # �����ֵ��Ҫ�������ǵ����ݺ�����������  
outliers = X[scores < threshold]  
print(f"Outliers: \n{outliers}")

��ע�⣬����� IsolationForest ����ܲ��� scikit-learn �ٷ����һ���֣������ǿ���ʹ�� scikit-learn �е� OneClassSVM �� LocalOutlierFactor ��ʵ�����ƵĹ��ܡ�

3.7 ���ǩ���ࣨMulti-label Classification��

���ɭ��Ҳ�������ڶ��ǩ�������񣬼�ÿ�������������ڶ�������ͨ��ͨ��ʹ�ö������������multi-output classifier����ʵ�֣��÷�����Ϊÿ����ǩѵ��һ�������ķ�������

from sklearn.datasets import make_multilabel_classification  
from sklearn.ensemble import RandomForestClassifier  
from sklearn.metrics import accuracy_score, precision_recall_fscore_support  
  
# ����һ�����ǩ�������ݼ�  
X, y = make_multilabel_classification(n_samples=1000, n_features=20, n_classes=5, n_labels=2, random_state=42)  
  
# ����ѵ�����Ͳ��Լ�  
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)  
  
# �������ɭ�ַ�������Ϊÿ����ǩѵ��һ��������  
clf = RandomForestClassifier(n_estimators=100, random_state=42)  
  
# ѵ��ģ��  
clf.fit(X_train, y_train)  
  
# Ԥ����Լ�  
y_pred = clf.predict(X_test)  
  
# ����ÿ����ǩ�ľ��ȡ��ٻ��ʺ�F1����  
precision, recall, fscore, support = precision_recall_fscore_support(y_test, y_pred, average=None)  
  
# ��ӡ���  
for i in range(y.shape[1]):  
    print(f"Label {i}: Precision = {precision[i]}, Recall = {recall[i]}, F1 Score = {fscore[i]}")  
  
# ע�⣺���ڶ��ǩ���࣬ͨ�������������׼ȷ�ʣ���Ϊ��ǩ֮������Ƕ�����

��Щʾ��չʾ�����ɭ���ڶ��ֲ�ͬ�����µ�Ӧ�ã������쳣��⡢���ǩ����ȡ���ʵ��Ӧ���У����ǿ�����Ҫ���ݾ�����������ݼ�����ģ�͵IJ��������á�

С���Ƽ��Ķ�

�������������Ľ�Ϊ������Ϣ����������������ͬ���޹۵��֤ʵ��������

�����Ƶ����

����

ͬ������

����

ɨ��ά�����������ֻ��汾��

ɨ��ά����������΢�Ź��ںţ�

��վ�������������������ϴ��������ַ���İ�Ȩ���뷢�ʼ�[email protected]

��ICP��2022002427��-10 �湫��������43070202000427��© 2013~2025 haote.com ������