Spaces:
Runtime error
Runtime error
Download data_pipeline/preprocess.py from KaustavMP/NetWokie-AI: direct link, hf CLI and curl.
- Browser
- Download file 4.46 kB
-
https://huggingface.co/spaces/KaustavMP/NetWokie-AI/resolve/main/data_pipeline/preprocess.py
- Command line
-
hf download hf://spaces/KaustavMP/NetWokie-AI/data_pipeline/preprocess.py
-
curl -L -o preprocess.py https://huggingface.co/spaces/KaustavMP/NetWokie-AI/resolve/main/data_pipeline/preprocess.py
4.46 kB
| import os | |
| import pandas as pd | |
| from sklearn.preprocessing import StandardScaler, LabelEncoder | |
| from sklearn.model_selection import train_test_split | |
| def run_preprocessing(input_file, output_train_x, output_test_x, output_train_y, output_test_y, le_output, scaler_output): | |
| print(f"Loading processed dataset from {input_file}...") | |
| df = pd.read_csv(input_file, low_memory=False) | |
| # 1. Remove specific columns | |
| cols_to_drop = ['IP address', 'MAC address', 'timestamp'] | |
| # If columns might have slightly different names, handle case-insensitivity or allow strict dropping | |
| for col in cols_to_drop: | |
| if col in df.columns: | |
| df = df.drop(columns=[col]) | |
| else: | |
| # Some datasets might use different case | |
| matching_cols = [c for c in df.columns if c.lower().replace("_", " ") == col.lower()] | |
| if matching_cols: | |
| df = df.drop(columns=matching_cols) | |
| # Make sure device_type exists | |
| if 'device_type' not in df.columns: | |
| # User defined labels could be different, fall back to "User Behavior Class" or standard | |
| if 'User Behavior Class' in df.columns: | |
| df.rename(columns={'User Behavior Class': 'device_type'}, inplace=True) | |
| else: | |
| print("Warning: 'device_type' column not found! Ensure the labels exist.") | |
| # If no device_type is found, perhaps the target is 'Label' or similar | |
| if 'Label' in df.columns: | |
| df.rename(columns={'Label': 'device_type'}, inplace=True) | |
| elif 'Protocol' in df.columns and len(df.columns) < 10: | |
| pass # placeholder logic | |
| # We expect features: packet_size, protocol, packet_rate, flow_duration according to step 4 | |
| # Ensure they exist or keep all numerical | |
| X = df.drop(columns=['device_type']) if 'device_type' in df.columns else df.iloc[:, :-1] | |
| y = df['device_type'] if 'device_type' in df.columns else df.iloc[:, -1] | |
| # 2. Encode device_type labels | |
| print("Encoding labels...") | |
| le = LabelEncoder() | |
| y_encoded = le.fit_transform(y.astype(str)) | |
| # 3. Normalize numeric features | |
| print("Normalizing numerical features...") | |
| numeric_columns = X.select_dtypes(include=['number']).columns | |
| non_numeric_columns = X.select_dtypes(exclude=['number']).columns | |
| # If there are string columns other than what we dropped, we might need to encode them (like standard 'protocol' strings). | |
| # Since instruction only says 'Normalize numeric features', we'll just normalize them. | |
| # However, if 'protocol' is a string like 'TCP', we should map it. | |
| if 'protocol' in X.columns and X['protocol'].dtype == object: | |
| X['protocol'] = LabelEncoder().fit_transform(X['protocol'].astype(str)) | |
| numeric_columns = X.select_dtypes(include=['number']).columns | |
| scaler = StandardScaler() | |
| X[numeric_columns] = scaler.fit_transform(X[numeric_columns]) | |
| # Drop any remaining non-numeric columns for model training | |
| X = X[numeric_columns] | |
| # 4. Split dataset (80% train, 20% test) | |
| print("Splitting dataset 80/20...") | |
| X_train, X_test, y_train, y_test = train_test_split(X, y_encoded, test_size=0.2, random_state=42) | |
| # Save processed outputs | |
| print("Saving preprocessed datasets...") | |
| pd.DataFrame(X_train, columns=numeric_columns).to_csv(output_train_x, index=False) | |
| pd.DataFrame(X_test, columns=numeric_columns).to_csv(output_test_x, index=False) | |
| pd.DataFrame(y_train, columns=['device_type']).to_csv(output_train_y, index=False) | |
| pd.DataFrame(y_test, columns=['device_type']).to_csv(output_test_y, index=False) | |
| import joblib | |
| joblib.dump(le, le_output) | |
| joblib.dump(scaler, scaler_output) | |
| print("Preprocessing completed.") | |
| if __name__ == "__main__": | |
| input_file = r"C:\Users\KAUSTAV\OneDrive\Desktop\NetWokie\NetWokie-AI\datasets\processed_dataset.csv" | |
| output_dir = r"C:\Users\KAUSTAV\OneDrive\Desktop\NetWokie\NetWokie-AI\datasets" | |
| run_preprocessing( | |
| input_file=input_file, | |
| output_train_x=os.path.join(output_dir, "X_train.csv"), | |
| output_test_x=os.path.join(output_dir, "X_test.csv"), | |
| output_train_y=os.path.join(output_dir, "y_train.csv"), | |
| output_test_y=os.path.join(output_dir, "y_test.csv"), | |
| le_output=os.path.join(output_dir, "label_encoder.pkl"), | |
| scaler_output=os.path.join(output_dir, "scaler.pkl") | |
| ) | |