mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 21:45:27 +08:00
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.
45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
# Random Forest Regressor Example
|
|
|
|
from sklearn.datasets import load_diabetes
|
|
from sklearn.ensemble import RandomForestRegressor
|
|
from sklearn.metrics import mean_absolute_error, mean_squared_error
|
|
from sklearn.model_selection import train_test_split
|
|
|
|
|
|
def main():
|
|
"""
|
|
Random Forest Regressor Example using sklearn function.
|
|
The diabetes dataset is used to demonstrate the algorithm.
|
|
|
|
Note: this example previously used the Boston house-price dataset,
|
|
which was removed from scikit-learn (>=1.2) for ethical reasons.
|
|
``load_diabetes`` is a drop-in bundled alternative that ships with
|
|
scikit-learn, so the example runs offline.
|
|
"""
|
|
# Load the diabetes dataset
|
|
diabetes = load_diabetes()
|
|
print(diabetes.keys())
|
|
|
|
# Split dataset into train and test data
|
|
x = diabetes["data"] # features
|
|
y = diabetes["target"]
|
|
x_train, x_test, y_train, y_test = train_test_split(
|
|
x, y, test_size=0.3, random_state=1
|
|
)
|
|
|
|
# Random Forest Regressor
|
|
rand_for = RandomForestRegressor(random_state=42, n_estimators=300)
|
|
rand_for.fit(x_train, y_train)
|
|
|
|
# Predict target for test data
|
|
predictions = rand_for.predict(x_test)
|
|
predictions = predictions.reshape(len(predictions), 1)
|
|
|
|
# Error printing
|
|
print(f"Mean Absolute Error:\t {mean_absolute_error(y_test, predictions)}")
|
|
print(f"Mean Square Error :\t {mean_squared_error(y_test, predictions)}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|