0% found this document useful (0 votes)
2 views7 pages

Python Codes

The document outlines a Python script for evaluating a Random Forest regression model using datasets for training and testing. It includes data loading, model training with cross-validation, performance metrics calculation, and feature importance analysis. The script specifically evaluates models for two outputs: Fc and Ra, generating plots for feature importance.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Python Codes

The document outlines a Python script for evaluating a Random Forest regression model using datasets for training and testing. It includes data loading, model training with cross-validation, performance metrics calculation, and feature importance analysis. The script specifically evaluates models for two outputs: Fc and Ra, generating plots for feature importance.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import pandas as pd

import numpy as np

import [Link] as plt

from [Link] import RandomForestRegressor

from sklearn.model_selection import KFold, cross_val_score,


cross_val_predict

from [Link] import (

r2_score,

mean_absolute_error,

mean_squared_error

#
============================================
=========

# LOAD DATASETS

#
============================================
=========

train_df = pd.read_excel("/content/AICTE QIP Main Project Turning Ti64 Big


[Link]")

test_df = pd.read_excel("/content/AICTE QIP Main Project Extra data


[Link]")

#
============================================
=========

# INPUT FEATURES

#
============================================
=========
X_train = train_df[['SS (rpm)', 'FR (mm/min.)', 'DoC (mm)']]

X_test = test_df[['SS (rpm)', 'FR (mm/min.)', 'DoC (mm)']]

#
============================================
=========

# RANDOM FOREST FUNCTION

#
============================================
=========

def evaluate_rf(X_train, y_train, X_test, y_test, output_name):

print("\n" + "="*80)

print(f"RANDOM FOREST MODEL FOR {output_name}")

print("="*80)

# Random Forest Model

rf = RandomForestRegressor(

n_estimators=200,

random_state=42

# -------------------------------------------------

# 5-FOLD CROSS VALIDATION

# -------------------------------------------------

kf = KFold(

n_splits=5,
shuffle=True,

random_state=42

r2_cv = cross_val_score(

rf,

X_train,

y_train,

cv=kf,

scoring='r2'

y_cv_pred = cross_val_predict(

rf,

X_train,

y_train,

cv=kf

mae_cv = mean_absolute_error(y_train, y_cv_pred)

mse_cv = mean_squared_error(y_train, y_cv_pred)

rmse_cv = [Link](mse_cv)

print("\n5-FOLD CROSS VALIDATION RESULTS")

print(f"Mean R² : {r2_cv.mean():.4f}")

print(f"Std R² : {r2_cv.std():.4f}")

print(f"MAE : {mae_cv:.4f}")

print(f"MSE : {mse_cv:.4f}")

print(f"RMSE : {rmse_cv:.4f}")
# -------------------------------------------------

# TRAIN FINAL MODEL

# -------------------------------------------------

[Link](X_train, y_train)

# -------------------------------------------------

# UNSEEN DATASET EVALUATION

# -------------------------------------------------

y_test_pred = [Link](X_test)

r2_test = r2_score(y_test, y_test_pred)

mae_test = mean_absolute_error(y_test, y_test_pred)

mse_test = mean_squared_error(y_test, y_test_pred)

rmse_test = [Link](mse_test)

print("\nUNSEEN DATASET RESULTS")

print(f"R² : {r2_test:.4f}")

print(f"MAE : {mae_test:.4f}")

print(f"MSE : {mse_test:.4f}")

print(f"RMSE : {rmse_test:.4f}")

# -------------------------------------------------

# FEATURE IMPORTANCE

# -------------------------------------------------

importance_df = [Link]({
'Feature': X_train.columns,

'Importance': rf.feature_importances_

})

importance_df = importance_df.sort_values(

by='Importance',

ascending=False

print("\nFEATURE IMPORTANCE")

print(importance_df)

# -------------------------------------------------

# FEATURE IMPORTANCE PLOT

# -------------------------------------------------

[Link](figsize=(6, 4))

[Link](

importance_df['Feature'],

importance_df['Importance']

[Link]("Importance")

[Link]("Feature")

[Link](f"Feature Importance - {output_name}")

plt.tight_layout()
[Link](

f"{output_name}_Feature_Importance.png",

dpi=300,

bbox_inches='tight'

[Link]()

return rf

#
============================================
=========

# Fc MODEL

#
============================================
=========

evaluate_rf(

X_train,

train_df['Fc (N)'],

X_test,

test_df['Fc (N)'],

"Fc"

#
============================================
=========

# Ra MODEL
#
============================================
=========

evaluate_rf(

X_train,

train_df['Ra (μm)'],

X_test,

test_df['Ra (μm)'],

"Ra"

You might also like