| import pandas as pd
|
| from sklearn.model_selection import train_test_split
|
| from sklearn.ensemble import RandomForestClassifier
|
| from sklearn.preprocessing import LabelEncoder
|
| import pickle
|
|
|
|
|
| target = "Level"
|
| DROP_COLS = ["Patient Id", "index"]
|
|
|
|
|
| df = pd.read_csv("cancer patient data sets.csv")
|
| df = df.dropna()
|
| df.columns = df.columns.str.strip()
|
|
|
|
|
| target_encoder = LabelEncoder()
|
| df[target] = target_encoder.fit_transform(df[target])
|
|
|
|
|
| df = df.drop(columns=[c for c in DROP_COLS if c in df.columns], errors='ignore')
|
|
|
|
|
| for col in df.columns:
|
| if col != target and df[col].dtype == "object":
|
| le = LabelEncoder()
|
| df[col] = le.fit_transform(df[col])
|
|
|
|
|
| X = df.drop(target, axis=1)
|
| y = df[target]
|
| X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
|
|
| model = RandomForestClassifier(n_estimators=200, random_state=42)
|
| model.fit(X_train, y_train)
|
|
|
|
|
| pickle.dump(model, open("model.pkl", "wb"))
|
| pickle.dump(X.columns.tolist(), open("model_features.pkl", "wb"))
|
| pickle.dump(target_encoder, open("target_encoder.pkl", "wb"))
|
|
|
| print("✅ Training complete. model.pkl, model_features.pkl, and target_encoder.pkl saved.")
|
| print(f"Model trained on {len(X.columns)} features.") |