import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 读取CSV文件
data = pd.read_csv('your_file.csv')
# 假设最后一列是目标变量
X = data.iloc[:, :-1] # 特征数据
y = data.iloc[:, -1] # 目标变量
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 初始化随机森林分类器
rf = RandomForestClassifier(n_estimators=100, random_state=42) # n_estimators是树的数量
# 训练模型
rf.fit(X_train, y_train)
# 进行预测
y_pred = rf.predict(X_test)
# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')
06-12
1432
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)