Skip to content

Commit f52b97f

Browse files
authored
Added Random Forest Regressor and tested with flake8 (TheAlgorithms#1733)
* Added Random Forest Regressor * Updated file to standard
1 parent 1608d75 commit f52b97f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Random Forest Regressor Example
2+
3+
from sklearn.datasets import load_boston
4+
from sklearn.model_selection import train_test_split
5+
from sklearn.ensemble import RandomForestRegressor
6+
from sklearn.metrics import mean_absolute_error
7+
from sklearn.metrics import mean_squared_error
8+
9+
10+
def main():
11+
12+
"""
13+
Random Tree Regressor Example using sklearn function.
14+
Boston house price dataset is used to demonstrate algorithm.
15+
"""
16+
17+
# Load Boston house price dataset
18+
boston = load_boston()
19+
print(boston.keys())
20+
21+
# Split dataset into train and test data
22+
X = boston["data"] # features
23+
Y = boston["target"]
24+
x_train, x_test, y_train, y_test = train_test_split(
25+
X, Y, test_size=0.3, random_state=1
26+
)
27+
28+
# Random Forest Regressor
29+
rand_for = RandomForestRegressor(random_state=42, n_estimators=300)
30+
rand_for.fit(x_train, y_train)
31+
32+
# Predict target for test data
33+
predictions = rand_for.predict(x_test)
34+
predictions = predictions.reshape(len(predictions), 1)
35+
36+
# Error printing
37+
print(f"Mean Absolute Error:\t {mean_absolute_error(y_test, predictions)}")
38+
print(f"Mean Square Error :\t {mean_squared_error(y_test, predictions)}")
39+
40+
41+
if __name__ == "__main__":
42+
main()

0 commit comments

Comments
 (0)