vertopal.com_Untitled57
vertopal.com_Untitled57
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import mean_squared_error, mean_absolute_error,
r2_score
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from xgboost import XGBRegressor
from sklearn.preprocessing import StandardScaler
# For ANN
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
# Load dataset
df = pd.read_csv("Imbalanced_PV_Fault_Dataset.csv")
X = df.drop(columns=["Feature_0", "Fault_Flag"])
y = df["Feature_0"]
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
# Scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
rls = RecursiveLeastSquares(num_features=X.shape[1])
for i in range(len(X_train)):
rls.update(X_train.iloc[i].values, y_train.iloc[i])
y_rls_pred = [np.dot(rls.theta, x) for x in X_test.values]
# ----------- GridSearchCV Models -----------
# Decision Tree
dtr = DecisionTreeRegressor(random_state=42)
dtr_param = {'max_depth': [3, 5, 10, None]}
dtr_grid = GridSearchCV(dtr, dtr_param, cv=5)
dtr_grid.fit(X_train, y_train)
dtr_pred = dtr_grid.best_estimator_.predict(X_test)
# Random Forest
rfr = RandomForestRegressor(random_state=42)
rfr_param = {'n_estimators': [50, 100], 'max_depth': [5, 10, None]}
rfr_grid = GridSearchCV(rfr, rfr_param, cv=5)
rfr_grid.fit(X_train, y_train)
rfr_pred = rfr_grid.best_estimator_.predict(X_test)
# XGBoost
xgb = XGBRegressor(random_state=42, verbosity=0)
xgb_param = {'n_estimators': [50, 100], 'max_depth': [3, 5, 10]}
xgb_grid = GridSearchCV(xgb, xgb_param, cv=5)
xgb_grid.fit(X_train, y_train)
xgb_pred = xgb_grid.best_estimator_.predict(X_test)
/var/folders/tt/9tcd3n611x1_n7ww1jb91r500000gn/T/
ipykernel_27794/2130103562.py:1: DeprecationWarning: KerasRegressor is
deprecated, use Sci-Keras (https://github.com/adriangb/scikeras)
instead. See https://www.adriangb.com/scikeras/stable/migration.html
for help migrating.
ann = KerasRegressor(build_fn=build_ann, epochs=100, batch_size=16,
verbose=0)
comparison_df = pd.DataFrame(metrics)
print(comparison_df)
Best Parameters:
DTR: {'max_depth': None}
RFR: {'max_depth': None, 'n_estimators': 100}
XGB: {'max_depth': 3, 'n_estimators': 100}
import pandas as pd