"""Session 16 (extra lab) - two classic agricultural classification datasets. A) UCI Rice (Cammeo vs Osmancik) - shipped in datasets/rice_cammeo_osmancik.csv (CC BY 4.0) Cinar & Koklu (2019). https://archive.ics.uci.edu/dataset/545/rice+cammeo+and+osmancik B) Crop Recommendation (N, P, K, temperature, humidity, ph, rainfall -> crop) Download Crop_recommendation.csv from Kaggle (free account): https://www.kaggle.com/datasets/atharvaingle/crop-recommendation-dataset and put it in datasets/ - the script skips part B if the file is missing. """ import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.model_selection import cross_val_score, train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from common import DATA # ---------------- A) Rice rice = pd.read_csv(DATA / "rice_cammeo_osmancik.csv") X, y = rice.drop(columns="Class"), rice["Class"] X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0) for name, m in {"LogisticRegression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=500)), "RandomForest": RandomForestClassifier(n_estimators=200, random_state=0)}.items(): m.fit(X_tr, y_tr) print(f"[Rice] {name:18s} test accuracy = {accuracy_score(y_te, m.predict(X_te)):.3f}") print(confusion_matrix(y_te, m.predict(X_te))) # ---------------- B) Crop recommendation path = DATA / "Crop_recommendation.csv" if not path.exists(): print("\n[Crop] Crop_recommendation.csv not found - download it from Kaggle (see docstring).") else: crop = pd.read_csv(path) Xc, yc = crop.drop(columns="label"), crop["label"] rf = RandomForestClassifier(n_estimators=300, random_state=0) scores = cross_val_score(rf, Xc, yc, cv=5) print(f"\n[Crop] 5-fold accuracy = {scores.mean():.3f} ± {scores.std():.3f}") rf.fit(Xc, yc) print(pd.Series(rf.feature_importances_, index=Xc.columns).sort_values(ascending=False).round(3)) # Example: KFS farm soil test (edit with your lab results) sample = pd.DataFrame([{"N": 90, "P": 42, "K": 43, "temperature": 26.0, "humidity": 65, "ph": 7.8, "rainfall": 30.0}]) print("Recommended crop for the sample soil:", rf.predict(sample)[0])