🌲 Python随机森林:一群决策树开的民主大会
随机森林就像让一群决策树"投票"做决定——每棵树可能有点偏见,但大家投票结果往往很准确。下面我们用Python实现这个"集体智慧"算法。
随机森林基础实现代码
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
import numpy as np# 创建模拟数据 - 判断是否批准贷款(年龄、收入、信用分)
X, y = make_classification(n_samples=100, n_features=3, n_informative=3, n_redundant=0, random_state=42)
# 给特征取有意义的名字
X = np.abs(X) * np.array([[50, 100000, 200]]) # 年龄(20-70岁), 收入(0-100k), 信用分(0-200)
y = np.where(y == 0, '拒绝', '批准') # 转换标签# 创建随机森林(10棵树)
forest = RandomForestClassifier(n_estimators=10, random_state=42)
forest.fit(X, y)# 预测新申请人
new_applicant = np.array([[35, 60000, 150]]) # 35岁,6万收入,150信用分
prediction = forest.predict(new_applicant)
probabilities = forest.predict_proba(new_applicant)[0]print("贷款审批预测结果:"