Skip to content
Project: Predictive Modeling for Agriculture
  • AI Chat
  • Code
  • Report
  • Sowing Success: How Machine Learning Helps Farmers Select the Best Crops

    Measuring essential soil metrics such as nitrogen, phosphorous, potassium levels, and pH value is an important aspect of assessing soil condition. However, it can be an expensive and time-consuming process, which can cause farmers to prioritize which metrics to measure based on their budget constraints.

    Farmers have various options when it comes to deciding which crop to plant each season. Their primary objective is to maximize the yield of their crops, taking into account different factors. One crucial factor that affects crop growth is the condition of the soil in the field, which can be assessed by measuring basic elements such as nitrogen and potassium levels. Each crop has an ideal soil condition that ensures optimal growth and maximum yield.

    A farmer reached out to you as a machine learning expert for assistance in selecting the best crop for his field. They've provided you with a dataset called soil_measures.csv, which contains:

    • "N": Nitrogen content ratio in the soil
    • "P": Phosphorous content ratio in the soil
    • "K": Potassium content ratio in the soil
    • "pH" value of the soil
    • "crop": categorical values that contain various crops (target variable).

    Each row in this dataset represents various measures of the soil in a particular field. Based on these measurements, the crop specified in the "crop" column is the optimal choice for that field.

    In this project, you will build multi-class classification models to predict the type of "crop" and identify the single most importance feature for predictive performance.

    # All required libraries are imported here for you.
    import pandas as pd
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import train_test_split
    from sklearn import metrics
    import matplotlib.pyplot as plt
    # Load the dataset
    crops = pd.read_csv("soil_measures.csv")
    
    # Write your code here
    crops.head()
    crops_train, crops_test = train_test_split(crops, random_state=42, test_size=0.2)
    import seaborn as sns
    sns.pairplot(data=crops_train, hue='crop')
    X_train.corr()
    from sklearn.metrics import accuracy_score
    def logreg_one_pred_coef(X_train, X_val, y_train, y_val, scorer):
        cols_pred = X_train.columns
        list_res = []
        for col in cols_pred:
            one_feature_model = LogisticRegression(random_state=42)
            one_feature_model.fit(X_train[[col]], y_train)
            train_score = scorer(y_train, one_feature_model.predict(X_train[[col]]))
            val_score = scorer(y_val, one_feature_model.predict(X_val[[col]]))
            res = {'pred': col, 'train_score': train_score, 'val_score': val_score}
            list_res.append(res)
        return pd.DataFrame(list_res)
    
    crops_train, crops_valid = train_test_split(crops_train, test_size=0.2, random_state=42)
    
    n_bootstrap = 30
    size_bootstrap = 3000
    col_target = 'crop'
    cols_pred = crops_train.drop(col_target, axis=1).columns
    list_df_score = []
    for i in range(n_bootstrap):
        crops_train_resample = crops_train.sample(n=size_bootstrap, replace=True, random_state=42+i)
        df_score = logreg_one_pred_coef(
            crops_train_resample[cols_pred], 
            crops_valid[cols_pred], 
            crops_train_resample[col_target], 
            crops_valid[col_target],
            scorer=accuracy_score
        )
        list_df_score.append(df_score)
    df_score = pd.concat(list_df_score, axis=0)
    fig, axes = plt.subplots(1,2, figsize=(20, 10))
    sns.boxplot(df_score, x='pred', y='train_score', ax=axes[0]).set(title='Train Score')
    sns.boxplot(df_score, x='pred', y='val_score', ax=axes[1]).set(title='Valid Score')
    plt.show()
    best_pred = df_score.groupby('pred')['val_score'].mean().sort_values(ascending=False).reset_index().iloc[0,0]
    logreg = LogisticRegression(random_state=42)
    logreg.fit(crops_train[[best_pred]], crops_train[col_target])
    score = accuracy_score(crops_test[col_target], logreg.predict(crops_test[[best_pred]]))
    print(score)
    best_predictive_feature = {best_pred: score}