Random Forest

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

import pandas as pd

from sklearn.tree import DecisionTreeRegressor

from sklearn.ensemble import RandomForestRegressor

from sklearn.model_selection import train_test_split

from sklearn.metrics import mean_squared_error

# Load your dataset

# data = pd.read_csv('path_to_your_data.csv')

# For demonstration, let's create a simple dataset

data = pd.DataFrame({

'Feature1': [1, 2, 3, 4, 5],

'Feature2': [5, 4, 3, 2, 1],

'Target': [1.2, 2.1, 3.5, 4.8, 5.6]

})

# Split the data into features and target

X = data.drop('Target', axis=1)

y = data['Target']

# 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, random_state=42)

# Initialize the Decision Tree Regressor

decision_tree = DecisionTreeRegressor(random_state=42)

# Fit the model on the training data

decision_tree.fit(X_train, y_train)
# Predict on the test data

y_pred_tree = decision_tree.predict(X_test)

# Calculate the Mean Squared Error for the Decision Tree

mse_tree = mean_squared_error(y_test, y_pred_tree)

print(f'Decision Tree Mean Squared Error: {mse_tree:.4f}')

# Initialize the Random Forest Regressor

random_forest = RandomForestRegressor(random_state=42)

# Fit the model on the training data

random_forest.fit(X_train, y_train)

# Predict on the test data

y_pred_forest = random_forest.predict(X_test)

# Calculate the Mean Squared Error for the Random Forest

mse_forest = mean_squared_error(y_test, y_pred_forest)

print(f'Random Forest Mean Squared Error: {mse_forest:.4f}')

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy