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.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split,KFold,GridSearchCV,cross_val_score
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import accuracy_score

# Load the dataset
crops = pd.read_csv("soil_measures.csv")
X = crops.drop("crop", axis=1).values
y = crops['crop'].values


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

scores = []
 # I had excluded the target column 'crop'
feature = list(crops.drop('crop',axis=1).columns) 

for i, name in enumerate(feature):
    X_train_feature = X_train[:, i].reshape(-1,1)
    X_test_feature = X_test[:, i].reshape(-1,1)
    logreg = LogisticRegression()
    logreg.fit(X_train_feature, y_train)
    y_pred = logreg.predict(X_test_feature)
    score = logreg.score(X_test_feature, y_test)
    scores.append(score) 

sns.barplot(x=feature, y=scores)
plt.xlabel('Features')
plt.ylabel('Scores')
plt.title('Finding feature for predicting')
plt.show()

#Base from our bar graph below the feature that produces the best score for predicting in our Logistic Regression model is "K" or the potassium ratio content in our soil
best_predictive_feature = {"K": max(scores)}
# Now let's find the best model that performs best in our data set

models = {"Logistic Regression": LogisticRegression(), "KNN" : KNeighborsClassifier(), "Decision Tree Classifier" : DecisionTreeClassifier()}

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)  # Use transform instead of fit_transform for test set
results = []
accuracy = []
for name, model in models.items():
    kf = KFold(n_splits = 6, shuffle = True, random_state = 42)
    cv_results = cross_val_score(model, X_train_scaled, y_train , cv=kf)
    model.fit(X_train_scaled, y_train)  
    y_pred = model.predict(X_test_scaled)  
    acc = accuracy_score(y_test, y_pred)
    accuracy.append(acc)
    results.append(cv_results)
# Base from our box plot the highest performing model is Decision Tree Classifier
plt.boxplot(results, labels=models.keys())
plt.show()
"""
Base from the plot below Decision Tree Classifier has the highest accuracy which is also slightly more better than Knn, so the best model to use in the given problem and data set is Decision Tree Classifier
"""
model_names = list(models.keys())
plt.bar(model_names, accuracy, color=["orange","violet","green"])
plt.title("Model Accuracy Comparison")
plt.xlabel("Models")
plt.ylabel("Accuracy")
plt.show()