sklearn怎么写随机森林算法
时间: 2024-04-21 19:05:46 浏览: 43
随机森林算法
好的,关于你的问题,以下是使用Scikit-learn库编写随机森林算法的基本步骤:
1.导入所需模块和数据集
```
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
import pandas as pd
# Load data
df = pd.read_csv('data.csv')
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
```
2.拆分训练和测试集
```
from sklearn.model_selection import train_test_split
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
3.创建并拟合模型
```
# Create the model
forest = RandomForestClassifier(n_estimators=100, random_state=0)
# Fit the model
forest.fit(X_train, y_train)
```
4.预测测试数据
```
# Predict the test data
y_pred = forest.predict(X_test)
```
5.评估模型性能
```
from sklearn.metrics import accuracy_score
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
以上就是Scikit-learn库中随机森林分类器的基本使用方法。希望可以帮到你!
阅读全文