bagging python
时间: 2023-07-14 14:01:42 浏览: 52
Bagging, short for Bootstrap Aggregating, is a machine learning ensemble technique that combines multiple models to improve prediction accuracy. In Python, you can implement bagging using various libraries such as scikit-learn.
Here's an example of how to use bagging in Python with scikit-learn:
```python
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# Generate some example data
X, y = make_classification(n_samples=1000)
# 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)
# Create a base classifier
base_classifier = DecisionTreeClassifier()
# Create a bagging classifier
bagging_classifier = BaggingClassifier(base_classifier, n_estimators=10)
# Train the bagging classifier
bagging_classifier.fit(X_train, y_train)
# Evaluate the bagging classifier
accuracy = bagging_classifier.score(X_test, y_test)
print("Accuracy:", accuracy)
```
In this example, we first generate some example data using `make_classification`. Then, we split the data into training and testing sets using `train_test_split`. Next, we create a base classifier, which in this case is a decision tree classifier. Finally, we create a bagging classifier using `BaggingClassifier` and train it on the training data. We evaluate the accuracy of the bagging classifier on the testing data using the `score` method.
Note that this is just a basic example, and there are many other parameters and options you can explore when using bagging in scikit-learn.