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(crops.head(10))crops.crop.unique()crops.isnull().any()crops.describe()crops.info()crops['crop'].value_counts()features = ["N", "P", "K", "ph"]
target = "crop"
# Split the data into training and testing sets
X = crops[features]
y = crops[target]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize a dictionary to store f1 scores for each feature
f1_scores = {}
# Loop through feature names
for feature in features:
# Select the current feature for training and testing sets
X_train_feature = X_train[[feature]]
X_test_feature = X_test[[feature]]
# Create a Logistic Regression model with max_iter set to 2000 and appropriate multi_class value
model = LogisticRegression(max_iter=2000, multi_class='auto', random_state=42)
# Fit the model
model.fit(X_train_feature, y_train)
# Predict using the trained model
predictions = model.predict(X_test_feature)
# Calculate f1 score and store it in the dictionary
f1 = f1_score(y_test, predictions, average='weighted') # You can change the average parameter as needed
f1_scores[feature] = f1
# Print the f1 scores for each feature
for feature, score in f1_scores.items():
print(f"F1 Score for {feature}: {score}")
# Calculate the correlation matrix
crops_corr = crops[["N", "P", "K", "ph"]].corr()
# Create a heatmap using seaborn
sns.heatmap(crops_corr, annot=True)
plt.show()final_features= ["N", "ph", "K"]
# Split the data into training and testing sets using selected features
X = crops[final_features].values
y = crops[target].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize the Logistic Regression model with max_iter set to 2000 and appropriate multi_class value
log_reg = LogisticRegression(max_iter=2000, multi_class='auto', random_state=42)
# Train the model
log_reg.fit(X_train, y_train)
# Predict using the trained model
predictions = log_reg.predict(X_test)
# Calculate F1 score for the model
model_performance = f1_score(y_test, predictions, average='weighted')
print(f"F1 Score for the final model: {model_performance}")