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 apply machine learning to build a multi-class classification model to predict the type of "crop", while using techniques to avoid multicollinearity, which is a concept where two or more features are highly correlated.

    # All required libraries are imported here for you.
    import matplotlib.pyplot as plt
    import pandas as pd
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import train_test_split
    import seaborn as sns
    from sklearn.metrics import f1_score
    
    # Load the dataset
    crops = pd.read_csv("soil_measures.csv")
    # Print out crops first five lines
    crops.head()
    # Determine the number of crops
    num_crops = crops["crop"].value_counts()
    print(num_crops)
    # Check for missing values
    any_missing_values = crops.isnull().any().any()
    print("Any missing values?", any_missing_values)
    # Verify that the data in each potential feature column is numeric
    N_num = pd.api.types.is_numeric_dtype(crops["N"])
    P_num = pd.api.types.is_numeric_dtype(crops["P"])
    K_num = pd.api.types.is_numeric_dtype(crops["K"])
    pH_num = pd.api.types.is_numeric_dtype(crops["ph"])
    
    print("N numeric?", N_num)
    print("P numeric?", P_num)
    print("K numeric?", K_num)
    print("pH numeric?", pH_num)
    # Split the data into training and test sets
    # Select the features/independent variables
    X = crops.drop(columns="crop")
    print(X.head())
    print(" ")
    
    # Select the target/dependent variable
    y = crops["crop"]
    print(y.head())
    print(" ")
    
    # Split the data
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    
    # Test that the data was split correctly
    print("X_train shape:", X_train.shape)
    print("X_test shape:", X_test.shape)
    print("y_train shape:", y_train.shape)
    print("y_test shape:", y_test.shape)
    # Instantiate the model
    logreg = LogisticRegression(max_iter=2000, multi_class="multinomial")
    
    # Fit the training set
    logreg.fit(X_train, y_train)
    
    # Predict the y-values of the test features
    y_pred = logreg.predict(X_test)
    
    # Compare the predicted y-values with the test y-values
    accuracy = f1_score(y_test, y_pred, average="micro")
    print(accuracy)
    correlation_matrix = crops.corr()
    print(correlation_matrix)

    K and P seem to be highly correlated, so we will remove these from the analysis.

    # Split the data into training and test sets
    # Select the features/independent variables
    final_features = crops[["N", "K", "ph"]]
    print(final_features.head())
    print(" ")
    
    # Split the data
    X_train, X_test, y_train, y_test = train_test_split(final_features, y, test_size=0.2, random_state=42)
    
    # Test that the data was split correctly
    print("X_train shape:", X_train.shape)
    print("X_test shape:", X_test.shape)
    print("y_train shape:", y_train.shape)
    print("y_test shape:", y_test.shape)
    # Instantiate the model
    log_reg = LogisticRegression(max_iter=2000, multi_class="multinomial")
    
    # Fit the training set
    log_reg.fit(X_train, y_train)
    
    # Predict the y-values of the test features
    y_pred = log_reg.predict(X_test)
    
    # Compare the predicted y-values with the test y-values
    model_performance = f1_score(y_test, y_pred, average="micro")
    print(model_performance)