CoolFace
Apppublic

Chidubhai/Crop_Recommendation_System

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
app.py117 linesDownload Raw Back to root
1import pandas as pd2import matplotlib.pyplot as plt3import numpy as np4import warnings5import seaborn as sns6from sklearn.model_selection import train_test_split7import sklearn.metrics as metrics8from sklearn.linear_model import LogisticRegression9import gradio as gr10import os11 12os.system("./startup.sh")13# Suppress all warnings14warnings.filterwarnings("ignore")15 16# Load your data17data = pd.read_csv('/content/Crop_recommendation.csv')  # Ensure you have the correct path to your data file18# Get the unique crop labels19unique_crops = data['label'].unique()20 21# Print the unique crops22print("Crops present in the dataset:")23for crop in unique_crops:24    print(crop)25# Plotting the distribution of features26features = ['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall']27plt.rcParams['figure.figsize'] = (10, 10)28plt.rcParams['figure.dpi'] = 6029 30for i, feat in enumerate(features):31    plt.subplot(4, 2, i + 1)32    sns.histplot(data[feat], color='greenyellow', kde=True)33    if i < 3:34        plt.title(f'Ratio of {feat}', fontsize=12)35    else:36        plt.title(f'Distribution of {feat}', fontsize=12)37    plt.tight_layout()38    plt.grid()39plt.show()40 41# Put all the input variables into features vector42features = data[['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall']]43 44# Put all the output into labels array45labels = data['label']46X_train, X_test, Y_train, Y_test = train_test_split(features, labels, test_size=0.2, random_state=42)47 48# Pass the training set into the LogisticRegression model from Sklearn49LogReg = LogisticRegression(random_state=42).fit(X_train, Y_train)50 51# Predict the values for the test dataset52predicted_values = LogReg.predict(X_test)53 54# Measure the accuracy of the test set using accuracy_score metric55accuracy = metrics.accuracy_score(Y_test, predicted_values)56print("Logistic Regression accuracy: ", accuracy)57 58# Get detailed metrics59print(metrics.classification_report(Y_test, predicted_values))60 61# Define the prediction function62def predict_soil(N, P, K, temperature, humidity, ph, rainfall):63    input_data = [N, P, K, temperature, humidity, ph, rainfall]64    input_df = pd.DataFrame([input_data], columns=["N", "P", "K", "temperature", "humidity", "ph", "rainfall"])65    prediction = LogReg.predict(input_df)[0]66 67    # Map crop names to image paths (ensure you have the correct paths to your images)68    crop_images = {69        "rice": "/content/rice.jpg",70        "apple": "/content/apple.jpg",71        "banana": "/content/banana.jpg",72        "blackgram": "/content/blackgram.jpg",73        "chickpea": "/content/chickpea.jpg",74        "coconut": "/content/coconut.jpg",75        "coffee": "/content/coffee.jpg",76        "cotton": "/content/cotton.jpg",77        "grapes": "/content/grapes.jpg",78        "jute": "/content/jute.jpg",79        "kidneybeans": "/content/kidneybeans.jpg",80        "lentil": "/content/lentil.jpg",81        "maize": "/content/maize.jpg",82        "mango": "/content/mango.jpg",83        "mothbeans": "/content/mothbeans.jpg",84        "mungbean": "/content/mungbean.jpg",85        "muskmelon": "/content/muskmelon.jpg",86        "oreange": "/content/oreange.jpg",87        "papaya": "/content/papaya.jpg",88        "pigeonpeas": "/content/pigeonpeas.jpg",89        "pomegranate": "/content/pomegranate.jpg",90        "watermelon": "/content/watermelon.jpg",91    }92 93    image_path = crop_images.get(prediction, "/content/default.jpg")  # Default image if crop not found94    return prediction, image_path95 96# Define the Gradio interface97iface = gr.Interface(98    fn=predict_soil,99    inputs=[100        gr.Slider(minimum=0, maximum=100, step=1, label="Enter Nitrogen value between 0 to 100"),101        gr.Slider(minimum=0, maximum=100, step=1, label="Enter Phosphorous value between 0 to 100"),102        gr.Slider(minimum=0, maximum=100, step=1, label="Enter Potassium value between 0 to 100"),103        gr.Slider(minimum=-20, maximum=48, step=1, label="Enter Temperature value between -20 to 48"),104        gr.Slider(minimum=0, maximum=100, step=1, label="Enter Humidity value between 0 to 100"),105        gr.Slider(minimum=0, maximum=14, step=1, label="Enter pH value between 0 to 14"),106        gr.Slider(minimum=0, maximum=100, step=1, label="Enter Rainfall value between 0 to 100")107    ],108    outputs=[gr.Textbox(label="Predicted Crop"), gr.Image(label="Crop Image")],109    title="Crop Recommendation System",110    theme="freddyaboulton/dracula_revamped",111    description="Enter the values below to get a crop recommendation",112    article="<p style='text-align: center;'>Made by Chidananda Bhattacharjee P.A.(Comp.), KVK Dhalai</p>",113)114 115iface.launch(share=True)116 117