GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.w3schools.com — Python Machine Learning - Bootstrap Aggregation (Bagging)
❮
❯
Python TutorialPython HOME Python Intro Python Get Started Python Syntax Python Output Python Comments Python Variables
Python Variables
Variable Names
Assign Multiple Values
Output Variables
Global Variables
Variable Exercises
Code Challenge
Python Data Types
Python Numbers
Python Casting
Python Strings
Python Strings
Slicing Strings
Modify Strings
Concatenate Strings
Format Strings
Escape Characters
String Methods
String Exercises
Code Challenge
Python Booleans
Python Operators
Python Operators
Arithmetic Operators
Assignment Operators
Ternary Operator
Comparison Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators
Operator Precedence
Code Challenge
Python Lists
Python Lists
Access List Items
Change List Items
Add List Items
Remove List Items
Loop Lists
List Comprehension
Sort Lists
Copy Lists
Join Lists
List Methods
List Exercises
Code Challenge
Python Tuples
Python Tuples
Access Tuples
Update Tuples
Unpack Tuples
Loop Tuples
Join Tuples
Tuple Methods
Tuple Exercises
Code Challenge
Python Sets
Python Sets
Access Set Items
Add Set Items
Remove Set Items
Loop Sets
Join Sets
Frozenset
Set Methods
Set Exercises
Code Challenge
Python Dictionaries
Python Dictionaries
Access Items
Change Items
Add Items
Remove Items
Loop Dictionaries
Copy Dictionaries
Nested Dictionaries
Dictionary Methods
Dictionary Exercises
Code Challenge
Python If...Else
Python If
Python Elif
Python Else
Shorthand If
Logical Operators
Nested If
Pass Statement
Code Challenge
Python Match
Python While Loops
Python For Loops
Python Functions
Python Functions
Python Arguments
Python *args / **kwargs
Python Scope
Python Decorators
Python Lambda
Python Recursion
Python Generators
Code Challenge
Python Range
Python Arrays
Python Iterators
Python Modules
Python Dates
Python Math
Python JSON
Python RegEx
Python PIP
Python Try...Except
Python String Formatting
Python None
Python User Input
Python VirtualEnv
Python ClassesPython OOP Python Classes/Objects Python __init__ Method Python self Parameter Python Class Properties Python Class Methods Python Magic Methods Python Inheritance Python Polymorphism Python Encapsulation Python Inner ClassesFile HandlingPython File Handling Python Read Files Python Write/Create Files Python Delete FilesPython ModulesNumPy Tutorial Pandas Tutorial SciPy Tutorial Django TutorialPython MatplotlibMatplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie ChartsMachine LearningGetting Started Mean Median Mode Standard Deviation Percentile Data Distribution Normal Data Distribution Scatter Plot Linear Regression Polynomial Regression Multiple Regression Scale Train/Test Decision Tree Confusion Matrix Hierarchical Clustering Logistic Regression Grid Search Categorical Data K-means Bootstrap Aggregation Cross Validation AUC - ROC Curve K-nearest neighborsPython DSAPython DSA Lists and Arrays Stacks Queues Linked Lists Hash Tables Trees Binary Trees Binary Search Trees AVL Trees Graphs Linear Search Binary Search Bubble Sort Selection Sort Insertion Sort Quick Sort Counting Sort Radix Sort Merge SortPython MySQLMySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL JoinPython MongoDBMongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB LimitPython CertPython CertificatePython How ToRemove List Duplicates Reverse a String Add Two NumbersPython ExamplesPython Examples Python Videos Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python TrainingPython ReferencePython Overview Python Built-in Functions
abs()
all()
any()
ascii()
bin()
bool()
bytearray()
bytes()
callable()
chr()
compile()
complex()
delattr()
dict()
dir()
divmod()
enumerate()
eval()
exec()
filter()
float()
format()
frozenset()
getattr()
globals()
hasattr()
hex()
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals()
map()
max()
memoryview()
min()
next()
object()
oct()
open()
ord()
pow()
print()
range()
reversed()
round()
set()
setattr()
slice()
sorted()
str()
sum()
super()
tuple()
type()
vars()
zip()
Python String Methods
capitalize()
casefold()
center()
count()
encode()
endswith()
expandtabs()
find()
format()
format_map()
index()
isalnum()
isalpha()
isascii()
isdecimal()
isdigit()
isidentifier()
islower()
isnumeric()
isprintable()
isspace()
istitle()
isupper()
join()
ljust()
lower()
lstrip()
maketrans()
partition()
replace()
rfind()
rindex()
rjust()
rpartition()
rsplit()
rstrip()
split()
splitlines()
startswith()
strip()
swapcase()
title()
translate()
upper()
zfill()
Python List Methods
Python Dictionary Methods
Python Tuple Methods
Python Set Methods
add()
clear()
copy()
difference()
difference_update()
discard()
intersection()
intersection_update()
isdisjoint()
issubset()
<
issuperset()
>
pop()
remove()
symmetric_difference()
symmetric_difference_update()
union()
update()
Python File Methods
close()
fileno()
flush()
isatty()
read()
readable()
readline()
readlines()
seek()
seekable()
tell()
truncate()
writable()
write()
writelines()
Python Keywords
and
as
assert
async
await
break
case
class
continue
def
del
elif
else
except
False
finally
for
from
global
if
import
in
is
lambda
match
None
nonlocal
not
or
pass
raise
return
True
try
while
with
yield
Python Exceptions
ArithmeticError
AssertionError
AttributeError
Exception
EOFError
FloatingPointError
GeneratorExit
ImportError
IndentationError
IndexError
KeyError
KeyboardInterrupt
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
ReferenceError
RuntimeError
StopIteration
SyntaxError
TabError
SystemError
SystemExit
TypeError
UnboundLocalError
UnicodeError
UnicodeEncodeError
UnicodeDecodeError
UnicodeTranslateError
ValueError
ZeroDivisionError
Python Glossary
Module ReferenceBuilt-in Modules
abc
aifc
argparse
array
ast
asyncio
atexit
base64
bdb
binascii
bisect
builtins
bz2
calendar
cgi
cgitb
cmd
code
codecs
codeop
collections
colorsys
concurrent
configparser
contextlib
contextvars
copy
copyreg
csv
ctypes
curses
dataclasses
datetime
dbm
decimal
difflib
dis
doctest
email
encodings
ensurepip
enum
errno
faulthandler
filecmp
fileinput
fnmatch
fractions
ftplib
functools
gc
getopt
getpass
gettext
glob
graphlib
gzip
hashlib
heapq
hmac
html
http
idlelib
imaplib
imghdr
imp
importlib
inspect
io
json
keyword
linecache
locale
logging
lzma
mailbox
mailcap
marshal
math
mimetypes
mmap
modulefinder
msilib
msvcrt
multiprocessing
netrc
nntplib
numbers
nis
ntpath
operator
optparse
os
pathlib
pdb
pickle
pickletools
pipes
pkgutil
platform
plistlib
poplib
posix
pprint
profile
pstats
pty
pyclbr
pydoc
py_compile
queue
quopri
random
re
reprlib
resource
rlcompleter
runpy
sched
secrets
select
selectors
shelve
shlex
shutil
signal
site
smtplib
socket
socketserver
sqlite3
ssl
stat
statistics
string
stringprep
struct
subprocess
sunau
symtable
sys
sysconfig
tabnanny
tarfile
telnetlib
tempfile
termios
test
textwrap
threading
time
timeit
tkinter
token
tokenize
tomllib
trace
traceback
tracemalloc
tty
turtle
types
typing
unicodedata
unittest
urllib
uuid
venv
warnings
wave
weakref
webbrowser
wsgiref
xdrlib
xml
xmlrpc
zipapp
zipfile
zipimport
zlib
zoneinfo
Random Module
seed()
getstate()
setstate()
getrandbits()
randrange()
randint()
choice()
choices()
shuffle()
sample()
random()
uniform()
triangular()
Requests Module
Statistics Module
statistics.harmonic_mean()
statistics.mean()
statistics.median()
statistics.median_grouped()
statistics.median_high()
statistics.median_low()
statistics.mode()
statistics.pstdev()
statistics.stdev()
statistics.pvariance()
statistics.variance()
Math Module
math.acos()
math.acosh()
math.asin()
math.asinh()
math.atan()
math.atan2()
math.atanh()
math.ceil()
math.comb()
math.copysign()
math.cos()
math.cosh()
math.degrees()
math.dist()
math.erf()
math.erfc()
math.exp()
math.expm1()
math.fabs()
math.factorial()
math.floor()
math.fmod()
math.frexp()
math.fsum()
math.gamma()
math.gcd()
math.hypot()
math.isclose()
math.isfinite()
math.isinf()
math.isnan()
math.isqrt()
math.ldexp()
math.lgamma()
math.log()
math.log10()
math.log1p()
math.log2()
math.perm()
math.pow()
math.prod()
math.radians()
math.remainder()
math.sin()
math.sinh()
math.sqrt()
math.tan()
math.tanh()
math.trunc()
math.e
math.inf
math.nan
math.pi
math.tau
cMath Module
cmath.acos(x)
cmath.acosh(x)
cmath.asin(x)
cmath.asinh(x)
cmath.atan(x)
cmath.atanh(x)
cmath.cos(x)
cmath.cosh(x)
cmath.exp(x)
cmath.isclose()
cmath.isfinite(x)
cmath.isinf(x)
cmath.isnan(x)
cmath.log(x[, base])
cmath.log10(x)
cmath.phase()
cmath.polar()
cmath.rect()
cmath.sin(x)
cmath.sinh(x)
cmath.sqrt(x)
cmath.tan(x)
cmath.tanh(x)
cmath.e
cmath.inf
cmath.infj
cmath.nan
cmath.nanj
cmath.pi
cmath.tau
Machine Learning - Bootstrap Aggregation (Bagging)
Share
BaggingMethods such as Decision Trees, can be prone to overfitting on the training set which can lead to wrong predictions on new data. Bootstrap Aggregation (bagging) is a ensembling method that attempts to resolve overfitting for classification or regression problems. Bagging aims to improve the accuracy and performance of machine learning algorithms. It does this by taking random subsets of an original dataset, with replacement, and fits either a classifier (for classification) or regressor (for regression) to each subset. The predictions for each subset are then aggregated through majority vote for classification or averaging for regression, increasing prediction accuracy. Evaluating a Base ClassifierTo see how bagging can improve model performance, we must start by evaluating how the base classifier performs on the dataset. If you do not know what decision trees are review the lesson on decision trees before moving forward, as bagging is a continuation of the concept. We will be looking to identify different classes of wines found in Sklearn's wine dataset. Let's start by importing the necessary modules.
Next we need to load in the data and store it into X (input features) and y (target). The parameter as_frame is set equal to True so we do not lose the feature names when loading the data.
(
In order to properly evaluate our model on unseen data, we need to split X and y into train and test sets. For information on splitting data, see the Train/Test lesson.
With our data prepared, we can now instantiate a base classifier and fit it to the training data.
Result:
We can now predict the class of wine the unseen test set and evaluate the model performance.
Result:
ExampleImport the necessary data and evaluate base classifier performance.
from sklearn import datasets
Run example »
from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier data = datasets.load_wine(as_frame = True) X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 22) dtree = DecisionTreeClassifier(random_state = 22) dtree.fit(X_train,y_train) y_pred = dtree.predict(X_test) print("Train data accuracy:",accuracy_score(y_true = y_train, y_pred = dtree.predict(X_train))) print("Test data accuracy:",accuracy_score(y_true = y_test, y_pred = y_pred)) The base classifier performs reasonably well on the dataset achieving 82% accuracy on the test dataset with the current parameters (Different results may occur if you do not have the Now that we have a baseline accuracy for the test dataset, we can see how the Bagging Classifier out performs a single Decision Tree Classifier. Creating a Bagging ClassifierFor bagging we need to set the parameter n_estimators, this is the number of base classifiers that our model is going to aggregate together. For this sample dataset the number of estimators is relatively low, it is often the case that much larger ranges are explored. Hyperparameter tuning is usually done with a grid search, but for now we will use a select set of values for the number of estimators. We start by importing the necessary model.
Now lets create a range of values that represent the number of estimators we want to use in each ensemble.
To see how the Bagging Classifier performs with differing values of n_estimators we need a way to iterate over the range of values and store the results from each ensemble. To do this we will create a for loop, storing the models and scores in separate lists for later visualizations. Note: The default parameter for the base classifier in
With the models and scores stored, we can now visualize the improvement in model performance.
ExampleImport the necessary data and evaluate the
import matplotlib.pyplot as plt
from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.ensemble import BaggingClassifier data = datasets.load_wine(as_frame = True) X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 22) estimator_range = [2,4,6,8,10,12,14,16] models = [] scores = [] for n_estimators in estimator_range: # Create bagging classifier clf = BaggingClassifier(n_estimators = n_estimators, random_state = 22) # Fit the model clf.fit(X_train, y_train) # Append the model and score to their respective list models.append(clf) scores.append(accuracy_score(y_true = y_test, y_pred = clf.predict(X_test))) # Generate the plot of scores against number of estimators plt.figure(figsize=(9,6)) plt.plot(estimator_range, scores) # Adjust labels and font (to make visable) plt.xlabel("n_estimators", fontsize = 18) plt.ylabel("score", fontsize = 18) plt.tick_params(labelsize = 16) # Visualize plot plt.show() Result
Results ExplainedBy iterating through different values for the number of estimators we can see an increase in model performance from 82.2% to 95.5%. After 14 estimators the accuracy begins to drop, again if you set a different In this case, we see a 13.3% increase in accuracy when it comes to identifying the type of the wine. Another Form of EvaluationAs bootstrapping chooses random subsets of observations to create classifiers, there are observations that are left out in the selection process. These "out-of-bag" observations can then be used to evaluate the model, similarly to that of a test set. Keep in mind, that out-of-bag estimation can overestimate error in binary classification problems and should only be used as a compliment to other metrics. We saw in the last exercise that 12 estimators yielded the highest accuracy, so we will use that to create our model. This time setting the parameter ExampleCreate a model with out-of-bag metric.
from sklearn import datasets
Run example »
from sklearn.model_selection import train_test_split from sklearn.ensemble import BaggingClassifier data = datasets.load_wine(as_frame = True) X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 22) oob_model = BaggingClassifier(n_estimators = 12, oob_score = True,random_state = 22) oob_model.fit(X_train, y_train) print(oob_model.oob_score_) Since the samples used in OOB and the test set are different, and the dataset is relatively small, there is a difference in the accuracy. It is rare that they would be exactly the same, again OOB should be used quick means for estimating error, but is not the only evaluation metric. Generating Decision Trees from Bagging ClassifierAs was seen in the Decision Tree lesson, it is possible to graph the decision tree the model created. It is also possible to see the individual decision trees that went into the aggregated classifier. This helps us to gain a more intuitive understanding on how the bagging model arrives at its predictions. Note: This is only functional with smaller datasets, where the trees are relatively shallow and narrow making them easy to visualize. We will need to import ExampleGenerate Decision Trees from Bagging Classifier
from sklearn import datasets
from sklearn.model_selection import train_test_split from sklearn.ensemble import BaggingClassifier from sklearn.tree import plot_tree X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 22) clf = BaggingClassifier(n_estimators = 12, oob_score = True,random_state = 22) clf.fit(X_train, y_train) plt.figure(figsize=(30, 20)) plot_tree(clf.estimators_[0], feature_names = X.columns) Result
Here we can see just the first decision tree that was used to vote on the final prediction. Again, by changing the index of the classifier you can see each of the trees that have been aggregated. Free account Track your progress
XP earned 0
Day streak 0
Spaces 0
League —
New Learn in Adventure Mode W3Schools Adventure AppCoding fundamentals as bite-sized lessons and challenges.
×
Contact SalesIf you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: Report ErrorIf you want to report an error, or if you want to make a suggestion, send us an e-mail: Top TutorialsHTML TutorialCSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial Top ReferencesHTML ReferenceCSS Reference JavaScript Reference SQL Reference Python Reference W3.CSS Reference Bootstrap Reference PHP Reference HTML Colors Java Reference AngularJS Reference jQuery Reference
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy. Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |