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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import sklearn
|
| 3 |
+
#for creating a folder
|
| 4 |
+
import os
|
| 5 |
+
#for data preprocessing and pipeline creation
|
| 6 |
+
from sklearn.model_selection import train_test_split
|
| 7 |
+
from sklearn.compose import make_column_transformer
|
| 8 |
+
from sklearn.pipeline import make_pipeline
|
| 9 |
+
from sklearn.preprocessing import StandardScaler
|
| 10 |
+
#for model traning,tuning and evaluation
|
| 11 |
+
import xgboost as xgb
|
| 12 |
+
from sklearn.model_selection import GridSearchCV
|
| 13 |
+
from sklearn.metrics import accuracy_score, classification_report,recall_score, precision_score, f1_score, confusion_matrix
|
| 14 |
+
#for model serialization
|
| 15 |
+
import joblib
|
| 16 |
+
#for converting text data into numerical representation
|
| 17 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 18 |
+
from sklearn.preprocessing import OneHotEncoder,LabelEncoder
|
| 19 |
+
import mlflow # Ensure mlflow is imported
|
| 20 |
+
|
| 21 |
+
DATASET_PATH = "hf://datasets/grkavi0912/ENG/engine.csv"
|
| 22 |
+
df=pd.read_csv(DATASET_PATH)
|
| 23 |
+
print("Dataset loaded successfully")
|
| 24 |
+
|
| 25 |
+
# Define the column name mapping to standardize names to snake_case
|
| 26 |
+
column_name_mapping = {
|
| 27 |
+
'Engine rpm': 'engine_rpm',
|
| 28 |
+
'Lub oil pressure': 'lub_oil_pressure',
|
| 29 |
+
'Fuel pressure': 'fuel_pressure',
|
| 30 |
+
'Coolant pressure': 'coolant_pressure',
|
| 31 |
+
'lub oil temp': 'lub_oil_temp',
|
| 32 |
+
'Coolant temp': 'coolant_temp',
|
| 33 |
+
'Engine Condition': 'engine_condition'
|
| 34 |
+
}
|
| 35 |
+
# Apply the renaming to the DataFrame
|
| 36 |
+
df.rename(columns=column_name_mapping, inplace=True)
|
| 37 |
+
print("Columns renamed to snake_case.")
|
| 38 |
+
|
| 39 |
+
#Define a target variable for this classification task
|
| 40 |
+
target="engine_condition"
|
| 41 |
+
|
| 42 |
+
#split into x(features) and y(target)
|
| 43 |
+
x=df.drop(columns=[target])
|
| 44 |
+
y=df[target]
|
| 45 |
+
|
| 46 |
+
#perform train and test split
|
| 47 |
+
xtrain,xtest,ytrain,ytest = train_test_split(
|
| 48 |
+
x,y, test_size=0.2,random_state=42
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
#set the class weight to handle class imbalance
|
| 52 |
+
class_weight = ytrain.value_counts()[0] / ytrain.value_counts()[1]
|
| 53 |
+
|
| 54 |
+
# Define numeric and categorical features
|
| 55 |
+
numeric_features = xtrain.select_dtypes(include=['number']).columns.tolist()
|
| 56 |
+
categorical_features = xtrain.select_dtypes(include=['object', 'category']).columns.tolist()
|
| 57 |
+
|
| 58 |
+
#Define the preprocessing steps
|
| 59 |
+
preprocessor = make_column_transformer(
|
| 60 |
+
(StandardScaler(),numeric_features),
|
| 61 |
+
(OneHotEncoder(handle_unknown='ignore'),categorical_features)
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
#Define base XGBoost model
|
| 65 |
+
xgb_model = xgb.XGBClassifier(scale_pos_weight=class_weight,random_state=42)
|
| 66 |
+
|
| 67 |
+
#Define hyperparameter grid
|
| 68 |
+
param_grid = {
|
| 69 |
+
'xgbclassifier__n_estimators': [50, 100],
|
| 70 |
+
'xgbclassifier__max_depth': [2, 4],
|
| 71 |
+
'xgbclassifier__colsample_bytree': [0.8, 1.0],
|
| 72 |
+
'xgbclassifier__colsample_bylevel': [0.8, 1.0],
|
| 73 |
+
'xgbclassifier__learning_rate': [0.01, 0.1],
|
| 74 |
+
'xgbclassifier__reg_lambda': [0.4, 0.6]
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
#model pipeline
|
| 78 |
+
model_pipeline = make_pipeline(preprocessor,xgb_model)
|
| 79 |
+
|
| 80 |
+
with mlflow.start_run():
|
| 81 |
+
#Hyperparameter tuning
|
| 82 |
+
grid_search = GridSearchCV(model_pipeline,param_grid,cv=3,n_jobs=-1)
|
| 83 |
+
grid_search.fit(xtrain,ytrain)
|
| 84 |
+
|
| 85 |
+
#log all parameter combinations and their mean test scores
|
| 86 |
+
results = grid_search.cv_results_
|
| 87 |
+
for i in range(len(results['params'])):
|
| 88 |
+
params_set = results['params'][i]
|
| 89 |
+
mean_score = results['mean_test_score'][i]
|
| 90 |
+
std_score = results['std_test_score'][i]
|
| 91 |
+
|
| 92 |
+
#log each combination as a separate MLflow run
|
| 93 |
+
with mlflow.start_run(nested=True):
|
| 94 |
+
mlflow.log_params(params_set)
|
| 95 |
+
mlflow.log_metric('mean_test_score',mean_score)
|
| 96 |
+
mlflow.log_metric('std_test_score',std_score)
|
| 97 |
+
|
| 98 |
+
#log best parameters separately in main run
|
| 99 |
+
mlflow.log_params(grid_search.best_params_)
|
| 100 |
+
|
| 101 |
+
#store and evaluate the best model
|
| 102 |
+
best_model = grid_search.best_estimator_
|
| 103 |
+
|
| 104 |
+
classification_threshold =0.45
|
| 105 |
+
|
| 106 |
+
y_pred_train_proba = best_model.predict_proba(xtrain)[:,1]
|
| 107 |
+
y_pred_train = (y_pred_train_proba >= classification_threshold).astype(int)
|
| 108 |
+
|
| 109 |
+
y_pred_test_proba = best_model.predict_proba(xtest)[:,1]
|
| 110 |
+
y_pred_test = (y_pred_test_proba >= classification_threshold).astype(int)
|
| 111 |
+
|
| 112 |
+
train_report = classification_report(ytrain, y_pred_train, output_dict=True)
|
| 113 |
+
test_report = classification_report(ytest, y_pred_test, output_dict=True)
|
| 114 |
+
|
| 115 |
+
# Log metrics individually
|
| 116 |
+
mlflow.log_metric("train_accuracy", train_report['accuracy'])
|
| 117 |
+
mlflow.log_metric("train_recall", train_report['1']['recall'])
|
| 118 |
+
mlflow.log_metric("train_precision", train_report['1']['precision'])
|
| 119 |
+
mlflow.log_metric("train_f1_score", train_report['1']['f1-score'])
|
| 120 |
+
mlflow.log_metric("test_accuracy", test_report['accuracy'])
|
| 121 |
+
mlflow.log_metric("test_recall", test_report['1']['recall'])
|
| 122 |
+
mlflow.log_metric("test_precision", test_report['1']['precision'])
|
| 123 |
+
mlflow.log_metric("test_f1_score", test_report['1']['f1-score'])
|
| 124 |
+
|
| 125 |
+
# Ensure eng/data and eng/model directories exist
|
| 126 |
+
os.makedirs('eng/data', exist_ok=True)
|
| 127 |
+
os.makedirs('eng/model', exist_ok=True)
|
| 128 |
+
|
| 129 |
+
# Save preprocessed data to eng/data
|
| 130 |
+
xtrain.to_csv("eng/data/xtrain.csv",index=False)
|
| 131 |
+
ytrain.to_csv("eng/data/ytrain.csv",index=False)
|
| 132 |
+
xtest.to_csv("eng/data/xtest.csv",index=False)
|
| 133 |
+
ytest.to_csv("eng/data/ytest.csv",index=False)
|
| 134 |
+
print("Train/test sets saved to eng/data/ CSV files.")
|
| 135 |
+
|
| 136 |
+
#save the model locally to eng/model
|
| 137 |
+
model_path = "eng/model/best_eng_model.joblib"
|
| 138 |
+
joblib.dump(best_model, model_path)
|
| 139 |
+
|
| 140 |
+
# log the model artifact
|
| 141 |
+
mlflow.log_artifact(model_path, artifact_path="model")
|
| 142 |
+
print(f"Model saved as artifact at {model_path}")
|
| 143 |
+
|
| 144 |
+
#upload to hugging face
|
| 145 |
+
repo_id = "grkavi0912/ENG"
|
| 146 |
+
repo_type="model"
|
| 147 |
+
|
| 148 |
+
# Initialize API client within this cell
|
| 149 |
+
from huggingface_hub import HfApi, RepositoryNotFoundError
|
| 150 |
+
api = HfApi(token=os.getenv("HFTOKEN"))
|
| 151 |
+
|
| 152 |
+
#step 1:check if the space exists
|
| 153 |
+
try:
|
| 154 |
+
api.repo_info(repo_id=repo_id,repo_type=repo_type)
|
| 155 |
+
print(f"Repo {repo_id} already exists")
|
| 156 |
+
except RepositoryNotFoundError:
|
| 157 |
+
print(f"Repo {repo_id} does not exist, creating...")
|
| 158 |
+
api.create_repo(repo_id=repo_id,repo_type=repo_type)
|
| 159 |
+
print(f"Repo {repo_id} created successfully")
|
| 160 |
+
|
| 161 |
+
#create_repo("tour_model",repo_type="model",private=False)
|
| 162 |
+
api.upload_file(
|
| 163 |
+
path_or_fileobj=model_path,
|
| 164 |
+
path_in_repo=os.path.basename(model_path), # Only upload the filename, not the full path
|
| 165 |
+
repo_id=repo_id,
|
| 166 |
+
repo_type=repo_type
|
| 167 |
+
)
|
| 168 |
+
print(f"Model uploaded to {repo_id}")
|