Final Code Classification
Final Code Classification
df = pd.read_csv(r"C:\Users\sahay\OneDrive\Desktop\Classification_Problem\Final_
X = [Link]('Machine_failure', axis=1)
y = df['Machine_failure']
#Split
#1st split
X_train, X_temp, y_train, y_temp = train_test_split(
X,
y,
test_size=0.40,
random_state=42,
stratify=y
)
#2nd split
X_val, X_test, y_val, y_test = train_test_split(
X_temp,
y_temp,
test_size=0.50,
random_state=42,
[Link] 1/20
3/14/26, 11:19 PM final_code_classification
stratify=y_temp
)
In [ ]: import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
target_col = 'Machine_failure'
numerical_features = df.select_dtypes(include=[Link]).[Link](target_col
sns.set_theme(style="whitegrid")
plt.tight_layout()
[Link]()
[Link] 2/20
3/14/26, 11:19 PM final_code_classification
[Link] 3/20
3/14/26, 11:19 PM final_code_classification
In [ ]: [Link](figsize=(12, 10))
corr_matrix = [Link]()
[Link] 4/20
3/14/26, 11:19 PM final_code_classification
In [ ]: pipe = Pipeline([
('scaler', StandardScaler()),
('smote', SMOTE(random_state=29)),
('selector', None),
('extractor', None),
('reducer', None),
('clf',LogisticRegression())
])
# Dictionary
scalers = {
'standard': StandardScaler(),
'robust': RobustScaler(),
'power': PowerTransformer(),
'quantile': QuantileTransformer(),
'minmax': MinMaxScaler(),
}
selectors = {
'kbest': SelectKBest(f_classif, k=6),
'rfe': RFE(RandomForestClassifier(random_state=29), n_features_to_select=6),
None: None
}
extractors = {
'pls_regression': PLSRegression(n_components=3),
'pls_canonical': PLSCanonical(n_components=3),
'lda': LDA(n_components=1),
None: None
}
[Link] 5/20
3/14/26, 11:19 PM final_code_classification
reducers = {
'pca': PCA(n_components=0.95),
'kpca': KernelPCA(n_components=5, kernel='rbf'),
'ica': FastICA(n_components=5, random_state=29),
None: None
}
models = {
'logreg': LogisticRegression(max_iter=1000),
'rf': RandomForestClassifier(random_state=29),
'svc': SVC(random_state=29),
'mlp': MLPClassifier(max_iter=300, random_state=29),
'extratrees': ExtraTreesClassifier(random_state=29),
'xgb': XGBClassifier(eval_metric='logloss', random_state=29),
'catboost': CatBoostClassifier(verbose=0, random_state=29),
}
In [14]: pipe.set_params(
selector=None,
extractor=None,
reducer=None,
clf=models['rf']
)
print("The best scaler-")
scaler_results=[]
for name, scalers in [Link]():
pipe.set_params(scaler=scaler)
[Link](X_train, y_train)
y_pred = [Link](X_val)
f1 = f1_score(y_val, y_pred, pos_label=1)
scaler_results.append({'Scaler': name, 'F1': f1})
print(f"{name}: F1-Score = {f1:.4f}")
In [49]: pipe.set_params(
selector=None,
extractor=None,
reducer=None,
clf=models['rf']
)
print("The best scaler-")
scaler_results=[]
for scaler_name, scaler in [Link]():
[Link] 6/20
3/14/26, 11:19 PM final_code_classification
pipe_copy = clone(pipe)
pipe_copy.set_params(scaler=scaler)
pipe_copy.set_params(scaler=scaler)
pipe_copy.fit(X_train, y_train)
y_pred = pipe_copy.predict(X_val)
f1 = f1_score(y_val, y_pred, pos_label=1)
scaler_results.append({'Scaler': scaler_name, 'F1': f1})
print(f"{scaler_name}: F1-Score = {f1:.4f}")
# Dictionary
scalers = {
'standard': StandardScaler(),
'robust': RobustScaler(),
'power': PowerTransformer(),
'quantile': QuantileTransformer(),
'minmax': MinMaxScaler(),
}
selectors = {
'kbest': SelectKBest(f_classif, k=6),
'rfe': RFE(RandomForestClassifier(random_state=29), n_features_to_select=6),
None: None
}
extractors = {
'pls_regression': PLSRegression(n_components=3),
'pls_canonical': PLSCanonical(n_components=3),
'lda': LDA(n_components=1),
None: None
}
reducers = {
'pca': PCA(n_components=0.95),
'kpca': KernelPCA(n_components=5, kernel='rbf'),
'ica': FastICA(n_components=5, random_state=29),
None: None
}
models = {
'logreg': LogisticRegression(max_iter=1000),
'rf': RandomForestClassifier(random_state=29),
'svc': SVC(random_state=29),
'mlp': MLPClassifier(max_iter=300, random_state=29),
'extratrees': ExtraTreesClassifier(random_state=29),
[Link] 7/20
3/14/26, 11:19 PM final_code_classification
In [51]: pipe.set_params(
selector=None,
extractor=None,
reducer=None,
clf=models['rf']
)
print("The best scaler-")
scaler_results=[]
for scaler_name, scaler in [Link]():
pipe_copy = clone(pipe)
pipe_copy.set_params(scaler=scaler)
pipe_copy.set_params(scaler=scaler)
pipe_copy.fit(X_train, y_train)
y_pred = pipe_copy.predict(X_val)
f1 = f1_score(y_val, y_pred, pos_label=1)
scaler_results.append({'Scaler': scaler_name, 'F1': f1})
print(f"{scaler_name}: F1-Score = {f1:.4f}")
In [52]: pipe.set_params(
scaler=scalers['robust'],
extractor=None,
reducer=None,
clf=models['rf']
)
print("The best feature selector -")
selector_results = []
for name, selector in [Link]():
pipe_copy = clone(pipe)
pipe_copy.set_params(selector=selector)
pipe_copy.fit(X_train, y_train)
y_pred = pipe_copy.predict(X_val)
[Link] 8/20
3/14/26, 11:19 PM final_code_classification
In [53]: pipe.set_params(
scaler=scalers['robust'],
selector = None,
reducer=None,
clf=models['rf']
)
print("The best feature extractor -")
extractor_results = []
for name, extractor in [Link]():
pipe_copy = clone(pipe)
pipe_copy.set_params(extractor=extractor)
pipe_copy.fit(X_train, y_train)
y_pred = pipe_copy.predict(X_val)
[Link] 9/20
3/14/26, 11:19 PM final_code_classification
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[53], line 13
10 pipe_copy = clone(pipe)
11 pipe_copy.set_params(extractor=extractor)
---> 13 pipe_copy.fit(X_train, y_train)
14 y_pred = pipe_copy.predict(X_val)
16 f1 = f1_score(y_val, y_pred, pos_label=1)
File c:\Users\sahay\AppData\Local\Programs\Python\Python313\Lib\site-packages\skl
earn\[Link], in _fit_context.<locals>.decorator.<locals>.wrapper(estimator,
*args, **kwargs)
1329 estimator._validate_params()
1331 with config_context(
1332 skip_parameter_validation=(
1333 prefer_skip_nested_validation or global_skip_validation
1334 )
1335 ):
-> 1336 return fit_method(estimator, *args, **kwargs)
File c:\Users\sahay\AppData\Local\Programs\Python\Python313\Lib\site-packages\imb
learn\[Link], in [Link](self, X, y, **params)
516 if self._final_estimator != "passthrough":
517 last_step_params = self._get_metadata_for_step(
518 step_idx=len(self) - 1,
519 step_params=routed_params[[Link][-1][0]],
520 all_params=params,
521 )
--> 522 self._final_estimator.fit(Xt, yt, **last_step_params["fit"])
523 return self
File c:\Users\sahay\AppData\Local\Programs\Python\Python313\Lib\site-packages\skl
earn\[Link], in _fit_context.<locals>.decorator.<locals>.wrapper(estimator,
*args, **kwargs)
1329 estimator._validate_params()
1331 with config_context(
1332 skip_parameter_validation=(
1333 prefer_skip_nested_validation or global_skip_validation
1334 )
1335 ):
-> 1336 return fit_method(estimator, *args, **kwargs)
File c:\Users\sahay\AppData\Local\Programs\Python\Python313\Lib\site-packages\skl
earn\ensemble\_forest.py:359, in [Link](self, X, y, sample_weight)
356 if issparse(y):
357 raise ValueError("sparse multilabel-indicator for y is not supporte
d.")
--> 359 X, y = validate_data(
360 self,
361 X,
362 y,
363 multi_output=True,
364 accept_sparse="csc",
365 dtype=DTYPE,
366 ensure_all_finite=False,
367 )
368 # _compute_missing_values_in_feature_mask checks if X has missing values
and
369 # will raise an error if the underlying tree base estimator can't handle
missing
[Link] 10/20
3/14/26, 11:19 PM final_code_classification
370 # values. Only the criterion is required to determine if the tree support
s
371 # missing values.
372 estimator = type([Link])(criterion=[Link])
File c:\Users\sahay\AppData\Local\Programs\Python\Python313\Lib\site-packages\skl
earn\utils\[Link], in validate_data(_estimator, X, y, reset, validate
_separately, skip_check_array, **check_params)
2917 y = check_array(y, input_name="y", **check_y_params)
2918 else:
-> 2919 X, y = check_X_y(X, y, **check_params)
2920 out = X, y
2922 if not no_val_X and check_params.get("ensure_2d", True):
File c:\Users\sahay\AppData\Local\Programs\Python\Python313\Lib\site-packages\skl
earn\utils\[Link], in check_X_y(X, y, accept_sparse, accept_large_spa
rse, dtype, order, copy, force_writeable, ensure_all_finite, ensure_2d, allow_nd,
multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
1309 estimator_name = _check_estimator_name(estimator)
1310 raise ValueError(
1311 f"{estimator_name} requires y to be passed, but the target y is N
one"
1312 )
-> 1314 X = check_array(
1315 X,
1316 accept_sparse=accept_sparse,
1317 accept_large_sparse=accept_large_sparse,
1318 dtype=dtype,
1319 order=order,
1320 copy=copy,
1321 force_writeable=force_writeable,
1322 ensure_all_finite=ensure_all_finite,
1323 ensure_2d=ensure_2d,
1324 allow_nd=allow_nd,
1325 ensure_min_samples=ensure_min_samples,
1326 ensure_min_features=ensure_min_features,
1327 estimator=estimator,
1328 input_name="X",
1329 )
1331 y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric, estimator
=estimator)
1333 check_consistent_length(X, y)
File c:\Users\sahay\AppData\Local\Programs\Python\Python313\Lib\site-packages\skl
earn\utils\[Link], in check_array(array, accept_sparse, accept_large_
sparse, dtype, order, copy, force_writeable, ensure_all_finite, ensure_non_negati
ve, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, inpu
t_name)
1063 raise ValueError(
1064 "dtype='numeric' is not compatible with arrays of bytes/strings."
1065 "Convert your data to numeric values explicitly instead."
1066 )
1067 if not allow_nd and [Link] >= 3:
-> 1068 raise ValueError(
1069 f"Found array with dim {[Link]},"
1070 f" while dim <= 2 is required{context}."
1071 )
1073 if ensure_all_finite:
1074 _assert_all_finite(
1075 array,
[Link] 11/20
3/14/26, 11:19 PM final_code_classification
1076 input_name=input_name,
1077 estimator_name=estimator_name,
1078 allow_nan=ensure_all_finite == "allow-nan",
1079 )
ValueError: Found array with dim 3, while dim <= 2 is required by RandomForestCla
ssifier.
# Dictionary
scalers = {
'standard': StandardScaler(),
'robust': RobustScaler(),
'power': PowerTransformer(),
'quantile': QuantileTransformer(),
'minmax': MinMaxScaler(),
}
selectors = {
'kbest': SelectKBest(f_classif, k=6),
'rfe': RFE(RandomForestClassifier(random_state=29), n_features_to_select=6),
None: None
}
extractors = {
'lda': LDA(n_components=1),
None: None
}
reducers = {
'pca': PCA(n_components=0.95),
'kpca': KernelPCA(n_components=5, kernel='rbf'),
'ica': FastICA(n_components=5, random_state=29),
None: None
}
models = {
'logreg': LogisticRegression(max_iter=1000),
'rf': RandomForestClassifier(random_state=29),
'svc': SVC(random_state=29),
'mlp': MLPClassifier(max_iter=300, random_state=29),
'extratrees': ExtraTreesClassifier(random_state=29),
'xgb': XGBClassifier(eval_metric='logloss', random_state=29),
'catboost': CatBoostClassifier(verbose=0, random_state=29)
}
In [55]: pipe.set_params(
scaler=scalers['robust'],
selector = None,
reducer=None,
clf=models['rf']
)
print("The best feature extractor -")
extractor_results = []
for name, extractor in [Link]():
pipe_copy = clone(pipe)
pipe_copy.set_params(extractor=extractor)
[Link] 12/20
3/14/26, 11:19 PM final_code_classification
pipe_copy.fit(X_train, y_train)
y_pred = pipe_copy.predict(X_val)
In [57]: pipe.set_params(
scaler=scalers['robust'],
selector = None,
extractor=None,
clf=models['rf']
)
print("The best feature reducer -")
reducer_results = []
for name, reducer in [Link]():
pipe_copy = clone(pipe)
pipe_copy.set_params(reducer=reducer if name != 'none' else None)
pipe_copy.fit(X_train, y_train)
y_pred = pipe_copy.predict(X_val)
# Dictionary
scalers = {
'standard': StandardScaler(),
'robust': RobustScaler(),
'power': PowerTransformer(),
'quantile': QuantileTransformer(),
'minmax': MinMaxScaler(),
[Link] 13/20
3/14/26, 11:19 PM final_code_classification
}
selectors = {
'kbest': SelectKBest(f_classif, k=6),
'rfe': RFE(RandomForestClassifier(random_state=29), n_features_to_select=6),
None: None
}
extractors = {
'lda': LDA(n_components=1),
None: None
}
reducers = {
'pca': PCA(n_components=0.95),
'kpca': KernelPCA(n_components=5, kernel='rbf'),
'ica': FastICA(n_components=5, random_state=29),
None: None
}
models = {
'logreg': LogisticRegression(max_iter=1000),
'rf': RandomForestClassifier(random_state=29),
'svc': SVC(random_state=29),
'mlp': MLPClassifier(max_iter=300, random_state=29),
'extratrees': ExtraTreesClassifier(random_state=29),
'xgb': XGBClassifier(eval_metric='logloss', random_state=29),
'catboost': CatBoostClassifier(verbose=0, random_state=29),
'ridge': RidgeClassifier(class_weight='balanced', random_state=29),
'nb': GaussianNB(),
'knn': KNeighborsClassifier(n_neighbors=5, weights='distance'),
'dt': DecisionTreeClassifier(class_weight='balanced', random_state=29),
'adaboost': AdaBoostClassifier(random_state=29),
'hist_gb': HistGradientBoostingClassifier(class_weight='balanced', random_st
}
In [ ]: pipe = Pipeline([
('scaler', RobustScaler()),
('clf', LogisticRegression())
])
models = {
'logreg': LogisticRegression(max_iter=1000, class_weight='balanced', random_
'ridge': RidgeClassifier(class_weight='balanced', random_state=29),
'svc': SVC(class_weight='balanced', random_state=29),
'nb': GaussianNB(),
'knn': KNeighborsClassifier(n_neighbors=5, weights='distance'),
[Link] 14/20
3/14/26, 11:19 PM final_code_classification
'adaboost': AdaBoostClassifier(random_state=29),
'hist_gb': HistGradientBoostingClassifier(class_weight='balanced', random_st
'xgb': XGBClassifier(eval_metric='logloss', scale_pos_weight=30, random_stat
'catboost': CatBoostClassifier(verbose=0, auto_class_weights='Balanced', ran
}
pipe_copy.set_params(clf=model)
cv_scores = cross_val_score(
pipe_copy,
X_train,
y_train,
cv=skf,
scoring='f1',
n_jobs=-1
)
mean_f1 = cv_scores.mean()
std_f1 = cv_scores.std()
model_results.append({
'Model': name,
'Mean F1': mean_f1,
'Std Dev': std_f1
})
[Link] 15/20
3/14/26, 11:19 PM final_code_classification
HYPERPARAMETER TUNING
In [ ]: import time
from sklearn.model_selection import GridSearchCV
final_pipe = Pipeline([
('scaler', RobustScaler()),
('clf', XGBClassifier(eval_metric='logloss', scale_pos_weight=30, random_sta
])
param_grid = {
'clf__n_estimators': [100, 300],
'clf__max_depth': [3, 5, 7],
'clf__learning_rate': [0.01, 0.1]
}
grid_search = GridSearchCV(
estimator=final_pipe,
param_grid=param_grid,
scoring='f1',
cv=skf,
n_jobs=-1
)
[Link] 16/20
3/14/26, 11:19 PM final_code_classification
grid_search.fit(X_train, y_train)
In [ ]: import time
from [Link] import uniform, randint
from sklearn.model_selection import RandomizedSearchCV
param_dist = {
'clf__n_estimators': randint(100, 400),
'clf__max_depth': randint(3, 8),
'clf__learning_rate': uniform(0.01, 0.15)
}
random_search.fit(X_train, y_train)
[Link] 17/20
3/14/26, 11:19 PM final_code_classification
param_bayes = {
'clf__n_estimators': Integer(100, 400),
'clf__max_depth': Integer(3, 8),
'clf__learning_rate': Real(0.01, 0.15, prior='log-uniform')
}
bayes_search = BayesSearchCV(
estimator=final_pipe,
search_spaces=param_bayes,
n_iter=60,
scoring='f1',
cv=skf,
n_jobs=-1,
random_state=42
)
bayes_search.fit(X_train, y_train)
final_optimized_pipe = Pipeline([
('scaler', RobustScaler()),
('clf', XGBClassifier(
n_estimators=305,
max_depth=6,
learning_rate=0.11372963888953223,
eval_metric='logloss',
scale_pos_weight=30,
random_state=29
))
])
[Link] 18/20
3/14/26, 11:19 PM final_code_classification
[Link](figsize=(6, 4))
cm = confusion_matrix(y_test, y_test_pred)
[Link](cm, annot=True, fmt='d', cmap='Blues', cbar=False)
[Link]('Final Confusion Matrix (Test Data)', fontweight='bold')
[Link]('Predicted: 0=Healthy, 1=Broken')
[Link]('Actual: 0=Healthy, 1=Broken')
[Link]()
[Link] 19/20
3/14/26, 11:19 PM final_code_classification
[Link] 20/20