Files
Python/machine_learning/random_forest_classifier.py
priya-sundaram-dev 35b7074d2d Re-enable five disabled algorithms and the perceptron (#15208)
Re-enable the four scikit-learn machine-learning examples and the
neural-network perceptron that had been disabled (renamed to
.broken.txt / .DISABLED), and modernize them so they import and run
cleanly on current scikit-learn and pass the doctest CI:

machine_learning/gaussian_naive_bayes.py
machine_learning/random_forest_classifier.py
  - Replace the removed sklearn.metrics.plot_confusion_matrix with
    ConfusionMatrixDisplay.from_estimator (removed in scikit-learn 1.2).
  - Drop the artificial time.sleep() calls.

machine_learning/gradient_boosting_regressor.py
machine_learning/random_forest_regressor.py
  - Replace the removed load_boston dataset (removed in scikit-learn
    1.2 for ethical reasons) with the bundled load_diabetes dataset so
    the examples run offline.
  - Avoid an unused-variable lint (RUF059).

neural_network/perceptron.py
  - Use a dedicated seeded random.Random instance instead of the global
    random state, so training is reproducible and thread-safe under the
    parallel test runner.
  - Cap training at epoch_number epochs so it always terminates even on
    non-linearly-separable data (previously an unbounded while True).
  - Have training() and sort() return their results instead of printing,
    per the contribution guidelines, and update the doctests accordingly.

Requested by @cclauss in #8029; perceptron follow-up to #15206.
2026-09-06 18:52:09 +02:00

44 lines
1.1 KiB
Python

# Random Forest Classifier Example
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
def main():
"""
Random Forest Classifier Example using sklearn function.
Iris type dataset is used to demonstrate algorithm.
"""
# Load Iris dataset
iris = load_iris()
# Split dataset into train and test data
x = iris["data"] # features
y = iris["target"]
x_train, x_test, y_train, y_test = train_test_split(
x, y, test_size=0.3, random_state=1
)
# Random Forest Classifier
rand_for = RandomForestClassifier(random_state=42, n_estimators=100)
rand_for.fit(x_train, y_train)
# Display Confusion Matrix of Classifier
ConfusionMatrixDisplay.from_estimator(
rand_for,
x_test,
y_test,
display_labels=iris["target_names"],
cmap="Blues",
normalize="true",
)
plt.title("Normalized Confusion Matrix - IRIS Dataset")
plt.show()
if __name__ == "__main__":
main()