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, Lasso
from sklearn.model_selection import train_test_split
from sklearn  import metrics
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

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

# Separate features (X) and target variable (y)
X = crops.drop('crop', axis=1).values
y = crops['crop'].values
names = crops.drop('crop', axis=1).columns

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Standardize the features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Initialize the Logistic Regression model
logreg = LogisticRegression(max_iter=100)

# Fit the model on the training data
logreg.fit(X_train_scaled, y_train)

# Get the coefficients of the features
coefs = logreg.coef_[0]

# Create a dataframe to visualize feature importance
feature_importance = pd.DataFrame({'feature': names, 'coefficient': coefs})

# Calculate the absolute value of the coefficients to determine importance
feature_importance['abs_coef'] = feature_importance['coefficient'].abs()

# Sort the dataframe by absolute coefficient to see the most important features
feature_importance = feature_importance.sort_values(by='abs_coef', ascending=False)

# Display the feature importance
feature_importance[['feature', 'coefficient']]

# Dictionary to store the best predictive feature and its coefficient
best_predictive_feature = {
    'K': 4.0462222304
}