Skip to content

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.

# Import libraries

import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score


def analyze_soil_data(data_path="soil_measures.csv"):

    """
    Analyzes a soil measures dataset to find the most predictive feature
    for crop type.

    Args:
        data_path (str, optional): Path to the soil measures CSV file.
            Defaults to "soil_measures.csv".

    Returns:
        dict: A dictionary containing the most predictive feature and its
            corresponding accuracy score.
    """

    # Load the dataset
    crops = pd.read_csv(data_path)

    # Check for missing values
    print(crops.isna().sum())

    # Check for crop types
    print(crops["crop"].unique())

    # Create training and test sets using all features
    # Split data into features (X) and target variable (y)
    X = crops.drop("crop", axis=1)
    y = crops["crop"]

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)

    # Predict the crop using each feature individually
    # Dictionary to store feature performance
    feature_performance = {}

    # Loop through each feature
    for feature in X.columns:
        # Create a Logistic Regression model
        logreg = LogisticRegression()

        # Select current feature as X_train and X_test
        X_train_single = X_train[[feature]]
        X_test_single = X_test[[feature]]

        # Train the model on the single feature
        logreg.fit(X_train_single, y_train)

        # Make predictions on the test set using the single feature
        y_pred = logreg.predict(X_test_single)

        # Evaluate performance of each feature
        accuracy = accuracy_score(y_test, y_pred)

        # Store performance for the current feature
        feature_performance[feature] = accuracy

    # Find feature with maximum accuracy
    max_feature, max_accuracy = max(feature_performance.items(), key=lambda item: item[1])
    best_feature_accuracy = {max_feature: max_accuracy}

    return best_feature_accuracy


# Example usage
best_predictive_feature = analyze_soil_data()
print(best_predictive_feature)