# _imports_  
**import** pandas **as** pd  
**import** seaborn **as** sns```
import matplotlib.pyplot as plt importnumpyasnp from sklearn.ensembleimportRandomForestRegressor,GradientBoostingRegressor from sklearn.model_selectionimportcross_val_score,GridSearchCV,KFold, train_test_split from sklearn.preprocessingimportStandardScaler importtensorflowastf fromtensorflow.keras.modelsimportSequential fromtensorflow.keras.layers importDense,Dropout,LSTM fromtensorflow.keras.regularizersimportI2 fromtensorflow.keras.callbacksimportEarlyStopping from scikeras.wrappersimportKerasRegressor from sklearn.metricsimportmean_squared_error,mean_absolute_error,r2_score fromdatetimeimportdatetime,timedelta
```
#DataPreparation url=\"[[https://raw.githubusercontent.com/katulu-io/uniwear-dataset/main/data/nuaa_orthogonal_bundle_high_resolution.csv](https://raw.githubusercontent.com/katulu-io/uniwear-dataset/main/data/nuaa_orthogonal_bundle_high_resolution.csv)]([https://raw.githubusercontent.com/katulu-io/uniwear-dataset/main/data/nuaa_orthogonal_bundle_high_resolution.csv](https://raw.githubusercontent.com/katulu-io/uniwear-dataset/main/data/nuaa_orthogonal_bundle_high_resolution.csv))\" df=pd.read_csv(url) df=df.drop(columns=[\"Unnamed: 0','vibration1', 'vibration2','experiment_csv_n', 'dataset_tag','tool_wear_increment','wear_blade_1','wear_blade_2', 'wear_blade_3','wear_blade_4','experiment_tag']) columns_order=[\"timestamp','spindle_speed','axial_cutting_depth','feed_per_tooth', 'axial_force', 'bending_moment_x','bending_moment_y','torsion','spindle_power','spindle_current', 'force_z','vibration_x','vibration_y','tool_wear'] df=df[columns_order] df2=df.drop(columns=['tool_wear']) num_rows=df.shape[0] print(\"\
\"+str(num_rows)+\"rows\
\") print(df2.describe) print(\"\
\"+\"Missingvaluesineachcolumn:\") print(df2.isnull().sum()) df.fillna( 'bending_moment_x':df['bending_moment_x'].mean(), 'bending_moment_y':df['bending_moment_y'].mean(), 'torsion':df['torsion'].mean() ),inplace=True) ```
#ModelTraining df=df.apply(pd.to_numeric,errors='coerce') df=df.dropna() X=df.drop(columns='tool_wear') y=df['tool_wear'] scaler=StandardScaler() X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42) scaler=StandardScaler() X_train_scaled=scaler.fit_transform(X_train) X_test_scaled=scaler.transform(X_test)

rf = RandomForestRegressor(n_estimators=100, random_state=42) gb = GradientBoostingRegressor(n_estimators=100, random_state=42) kfold = KFold(n_splits=5, shuffle=True, random_state=42) ensemble_scores = cross_val_score(rf, X_train_scaled, y_train, cv=kfold, scoring=\"neg_mean_squared_error', verbose=3) print(f\"Cross-validated MSE (Random Forest): {-ensemble_scores.mean():12f} (std: {ensemble_scores.std():12f})\") ensemble_scores = cross_val_score(gb, X_train_scaled, y_train, cv=kfold, scoring=\"neg_mean_squared_error', verbose=3) print(f\"Cross-validated MSE (Gradient Boosting): {-ensemble_scores.mean():12f} (std: {ensemble_scores.std():12f})\") defcreate_sequences(X, y, time_window): X_time, y_time = [], [] if hasattr(y, 'values'): y = y.values if hasattr(X, 'values'): X = X.values fori inrange(len(X) - time_window): X_time.append(X[i:(i + time_window)]) y_time.append(y[i + time_window]) returnnp.array(X_time), np.array(y_time) time_window = 10 X_train_time, y_train_time = create_sequences(X_train_scaled, y_train, time_window) X_test_time, y_test_time = create_sequences(X_test_scaled, y_test, time_window) defcreate_lstm_model(input_shape): model = Sequential() model.add(LSTM(64, input_shape=input_shape)) model.add(Dropout(0.2)) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') returnmodel defbuild_fn(): returncreate_lstm_model(input_shape=(time_window, X_train_scaled.shape [1])) early_stopping = EarlyStopping( monitor='val_loss', patience=3, min_delta=0.001, restore_best_weights=True, verbose=0 ) lstm_model = KerasRegressor( model=build_fn, epochs=100, batch_size=32, verbose=3, validation_split=0.2 )kfold = KFold(n_splits=5, shuffle=True, random_state=42) lstm_scores = cross_val_score( lstm_model, X_train_time, y_train_time, cv=kfold, scoring='neg_mean_squared_error', fit_params={'callbacks': [early_stopping]] ) print(\"Cross-validated MSE (LSTM Model): {lstm_scores.mean():.12f}(std: {lstm_scores.std():.12f})\")
#ModelEvaluation(TestSet) rf.fit(X_train_scaled, y_train) rf_pred = rf.predict(X_test_scaled) rf_test_mse = mean_squared_error(y_test, rf_pred) print(\"Test MSE with Random Forest: {rf_test_mse:.12f}\")

gb.fit(X_train_scaled, y_train) gb_pred = gb.predict(X_test_scaled) gb_test_mse = mean_squared_error(y_test, gb_pred) print(\"Test MSE with Gradient Boosting: {gb_test_mse:.12f}\")

lstm_model.fit( X_train_time, y_train_time, callbacks=[early_stopping], validation_split=0.2, epochs=100, batch_size=32, verbose=3 ) lstm_pred = lstm_model.predict(X_test_time) lstm_test_mse = mean_squared_error(y_test_time, lstm_pred) print(\"Test MSE with LSTM Model: [lstm_test_mse:.12f]\")

#Flank ToolWearThresholdEvaluations model =gb input_data = { 'times stamp': int(df['times stamp'].min()),'spindle_speed': 1485, 'axial_cutting_depth': df['axial_cutting_depth'].mean(), 'feed_per_tooth': 0.11, 'axial_force': df['axial_force'].mean(), 'bending_moment_x': df['bending_moment_x'].mean(), 'bending_moment_y': df['bending_moment_y'].mean(), 'torsion': df['torsion'].mean(),'spindle_power': df['spindle_power'].mean(),'spindle_current': df['spindle_current'].mean(), 'force_z': df['force_z'].mean(),

'vibration_x': df['vibration_x'].mean(), 'vibration_y': df['vibration_y'].mean(), } target_wears = [0.1, 0.2, 0.3] results = {target_wear: **None for** target_wear **in** target_wears} timestamp_min = int(df['timestamp'].min()) timestamp_max = int(df['timestamp'].max()) timestamp_range = range(timestamp_min, timestamp_max, 100) for timestamp **in** timestamp_range: input_data['timestamp'] = timestamp input_data_df = pd.DataFrame([input_data]) input_data_scaled = scaler.transform(input_data_df) predicted_tool_wear = model.predict(input_data_scaled) predicted_wear = predicted_tool_wear [0] for target_wear **in** target_wears: if predicted_wear >= target_wear **and** results[target_wear] **is** None: results[target_wear] = (predicted_wear, timestamp) for target_wear, result **in** results.items(): if result: predicted_wear, timestamp = result mean_time_predicted_wear = datetime.fromtimestamp(timestamp).strftime(\"%H:%M:%S') print(f'For tool wear target {target_wear}mm:') print(f'Predicted Tool Wear: {predicted_wear.