File size: 1,967 Bytes
e56a409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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()