随机森林预测python代码
时间: 2023-10-03 22:09:32 浏览: 45
Sure, here's a Python code snippet to train and predict using a Random Forest model:
```python
# Import libraries
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Prepare the data
# Assuming you have X as the feature matrix and y as the target variable
# 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=42)
# Create a Random Forest classifier
rf_classifier = RandomForestClassifier()
# Train the model
rf_classifier.fit(X_train, y_train)
# Make predictions on the test set
y_pred = rf_classifier.predict(X_test)
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
Make sure you have the scikit-learn library installed (`pip install scikit-learn`) before running this code. Replace `X` with your feature matrix and `y` with your target variable. Feel free to modify the code according to your specific requirements.