Crop_Analysis / app.py
Thrishul3549x's picture
Create app.py
e56a409 verified
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.preprocessing import LabelEncoder
import gradio as gr
# Load dataset
data = pd.read_csv("cpdata.csv")
# Split features and target
y = data["label"]
x = data.drop("label", axis=1)
# Encode target labels
encoder = LabelEncoder()
y_encoded = encoder.fit_transform(y)
# Train-test split
xtrain, xtest, ytrain, ytest = train_test_split(x, y_encoded, test_size=0.2, random_state=0)
# Train model
classifier = RandomForestClassifier(n_estimators=100, random_state=0)
classifier.fit(xtrain, ytrain)
# Evaluate
output = classifier.predict(xtest)
accuracy = accuracy_score(ytest, output)
precision = precision_score(ytest, output, average="weighted")
recall = recall_score(ytest, output, average="weighted")
f1 = f1_score(ytest, output, average="weighted")
print("Model Performance:")
print(f"Accuracy: {accuracy:.2f}")
print(f"Precision: {precision:.2f}")
print(f"Recall: {recall:.2f}")
print(f"F1-score: {f1:.2f}")
# Gradio prediction function
def predict(temp, humi, ph, rain, N, P, K):
new_data = [[temp, humi, ph, rain, N, P, K]]
pred = classifier.predict(new_data)
plant = encoder.inverse_transform(pred)[0]
return f"Predicted plant for given condition: {plant}"
# Gradio UI
demo = gr.Interface(
fn=predict,
inputs=[
gr.Number(label="Temperature"),
gr.Number(label="Humidity"),
gr.Number(label="pH"),
gr.Number(label="Rainfall"),
gr.Number(label="Nitrogen (N)"),
gr.Number(label="Phosphorus (P)"),
gr.Number(label="Potassium (K)")
],
outputs=gr.Textbox(label="Prediction"),
title="Crop Prediction App",
description="Enter soil and climate conditions to predict the best plant."
)
if __name__ == "__main__":
demo.launch()