File size: 1,477 Bytes
bbdbcaf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
import pickle
# --- Configuration ---
target = "Level"
DROP_COLS = ["Patient Id", "index"]
# 1. Load and Clean
df = pd.read_csv("cancer patient data sets.csv")
df = df.dropna()
df.columns = df.columns.str.strip() # Clean column names
# 2. Encode Target Separately
target_encoder = LabelEncoder()
df[target] = target_encoder.fit_transform(df[target])
# 3. Drop Unnecessary Columns
df = df.drop(columns=[c for c in DROP_COLS if c in df.columns], errors='ignore')
# 4. Encode remaining string/object features (if any)
for col in df.columns:
if col != target and df[col].dtype == "object":
le = LabelEncoder()
df[col] = le.fit_transform(df[col])
# 5. Split and Train
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)
# 6. Save Model Artifacts
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.") |