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.

# 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

# Load the dataset
crops = pd.read_csv("soil_measures.csv")

# Write your code here
crops.isna().sum()

We found that there are no missing values in the dataset, so we don't need to handle nulls.

values=crops['crop'].value_counts().index
dict= {val: i for i, val in enumerate(values)}
crops['crop_index']=crops['crop'].replace(dict)

The crop types are consistent and properly labeled. We'll now convert them into numerical categories for modeling.

To determine which soil feature is most predictive of crop type, we'll evaluate each one individually using a logistic regression model. We'll record each feature's performance using accuracy and F1-score.


y=crops['crop_index'].values
feature_performance={}
for col in crops.columns:
    if(col=='crop'):
        break
    x=crops[col].values.reshape(-1,1)
    x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,stratify=y,random_state=1808)
    logreg=LogisticRegression(multi_class="multinomial")
    logreg.fit(x_train,y_train)
    y_pred=logreg.predict(x_test)
    score=min(metrics.accuracy_score(y_test,y_pred),metrics.f1_score(y_test,y_pred,average='weighted'))
    feature_performance[col]=score
print(feature_performance)
best_predictive_feature = {str(max(feature_performance,key=feature_performance.get)): max(feature_performance.values())}
best_predictive_feature

The best individual feature appears to be 'K' (Potassium), but we will also test combinations of features to improve the overall model performance.

We re going to test every possible combination of features to test which out come give us the best result

This code give us every possible combination in a list

def combination(arr):
    result=[]
    def backtrack(start,path):
        if path:
            result.append(path[:])
        for i in range(start,len(arr)):
            path.append(arr[i])
            backtrack(i+1,path)
            path.pop()
    backtrack(0,[])
    return result

Modeling every single features

arr=['N','P','K','ph']
comb=combination(arr)
scores={}

for c in comb:
    x=crops[c]
    x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=1808)
    logreg=LogisticRegression(multi_class="multinomial")
    logreg.fit(x_train,y_train)
    y_pred=logreg.predict(x_test)
    score=min(metrics.accuracy_score(y_test,y_pred),metrics.f1_score(y_test,y_pred,average='macro'))
    scores['+'.join(c)]=score
        
print(scores)