A full-stack machine learning web application that predicts hydroponic plant health and growth outcomes using an XGBoost model. Features a modern React + Vite frontend, FastAPI backend, and comprehensive environmental analysis.
- Features
- Architecture
- Project Structure
- Prerequisites
- Setup Instructions
- Model Training
- Running the Application
- API Documentation
- Input Parameters
- Model Outputs
- Using Real Data
- Troubleshooting
- Real-time Health Status Classification: Healthy / Stressed / Diseased
- Growth Rate Estimation: Low / Moderate / High
- Yield Prediction: Regression-based growth score (0-100%)
- Confidence Scoring: Model prediction confidence level
- Nutrient Detection: Identifies deficiencies and toxicities
- Disease Risk Assessment: Calculates pest and disease likelihood
- Environmental Recommendations: Actionable pH, EC, temperature, and humidity adjustments
- Visual Plant Symptom Analysis: Considers leaf yellowing, wilting, curling, and spotting
- Modern Dashboard: Clean, intuitive design with TailwindCSS
- Interactive Forms: Input validation with preset optimal/stressed scenarios
- Rich Visualizations: Charts and gauges for data insights
- Mobile Responsive: Works seamlessly on all devices
- Dark Mode Compatible: Professional color scheme
- Multi-Output Regression: Simultaneous prediction of health, growth, and yield
- Synthetic Data Generation: 500+ training samples with realistic hydroponic conditions
- Scaler & Encoder Persistence: Automatic preprocessing consistency
- Cross-validation: Train/test split evaluation
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β React + Vite Frontend β
β (Port 5173) - Input Dashboard & Results Visualization β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β HTTP/REST (axios)
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FastAPI Backend β
β (Port 8000) - ML Prediction Engine β
β β
β β’ POST /predict β Model inference β
β β’ GET /health β Health check β
β β’ GET /model-info β Model metadata β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β XGBoost Model β
β (models/xgb_model.json + preprocessing files) β
β β
β Input: pH, EC, Temperature, Humidity, Visual Condition β
β Output: Health Score, Growth Score, Yield Score β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
hydroponics-app/
β
βββ backend/
β βββ main.py # FastAPI application
β βββ train_model.py # Model training script
β βββ requirements.txt # Python dependencies
β βββ models/ # (Created after training)
β βββ xgb_model.json # Trained XGBoost model
β βββ scaler.pkl # StandardScaler for features
β βββ encoder.pkl # LabelEncoder for visual condition
β
βββ frontend/
β βββ index.html # HTML entry point
β βββ package.json # Node dependencies
β βββ vite.config.js # Vite configuration
β βββ tailwind.config.js # TailwindCSS config
β βββ postcss.config.js # PostCSS config
β β
β βββ src/
β βββ main.jsx # React root
β βββ App.jsx # Main app component
β βββ App.css # Global styles
β βββ index.css # Tailwind directives
β β
β βββ pages/
β β βββ InputDashboard.jsx # User input form
β β βββ InputDashboard.css
β β βββ ResultsView.jsx # Results display
β β βββ ResultsView.css
β β
β βββ components/
β βββ Header.jsx # Top navigation
β βββ Footer.jsx # Footer with info
β
βββ README.md # This file
- Python 3.9+ (for backend)
- Node.js 16+ (for frontend)
- 2GB+ free disk space
- Python Package Manager:
pip(included with Python) - Node Package Manager:
npm(included with Node.js)
# Check Python
python --version
# Check Node.js
node --version
npm --versioncd hydroponics-appcd backend
# Windows
python -m venv venv
venv\Scripts\activate
# macOS/Linux
python -m venv venv
source venv/bin/activatepip install -r requirements.txtYou should see installations for:
- FastAPI (API framework)
- Uvicorn (ASGI server)
- XGBoost (ML model)
- scikit-learn (preprocessing)
- pandas & numpy (data handling)
cd ../frontend
npm installThis installs:
- React & React DOM
- Vite (build tool)
- TailwindCSS (styling)
- Axios (HTTP client)
- Recharts (visualization)
- Lucide React (icons)
IMPORTANT: You must train the model before running predictions.
cd backend
# Make sure your virtual environment is activated
# Windows: venv\Scripts\activate
# macOS/Linux: source venv/bin/activate
python train_model.py-
Generates 500 synthetic samples of hydroponic plant data
- pH: 3.0-9.0 (optimal: 5.5-6.5)
- EC/TDS: 200-3000 Β΅S/cm (optimal: 800-1800)
- Temperature: 5-35Β°C (optimal: 18-24Β°C)
- Humidity: 20-95% (optimal: 40-80%)
- Visual condition: 5 categories
-
Trains an XGBoost model to predict:
- Health Score (0-1)
- Growth Score (0-1)
- Yield Score (0-1)
-
Saves model artifacts:
models/xgb_model.json- Trained modelmodels/scaler.pkl- Feature scalermodels/encoder.pkl- Visual condition encoder
-
Displays training metrics:
Health Score: Train MSE: 0.0234 | Test MSE: 0.0241 Growth Score: Train MSE: 0.0198 | Test MSE: 0.0215 Yield Score: Train MSE: 0.0156 | Test MSE: 0.0167 -
Shows example predictions with optimal and stressed conditions
======================================================================
π± HYDROPONIC PLANT HEALTH MODEL TRAINING
======================================================================
π Dataset Information:
Training samples: 400
Test samples: 100
Features: 5
Targets: 3
π Training model...
π Model Evaluation:
Health Score:
Train MSE: 0.0234 | Test MSE: 0.0241
Train RΒ²: 0.9456 | Test RΒ²: 0.9312
...
πΎ Saving model and preprocessing objects...
β Model saved: backend/models/xgb_model.json
β Scaler saved: backend/models/scaler.pkl
β Encoder saved: backend/models/encoder.pkl
β¨ TRAINING COMPLETE!
cd backend
# Activate virtual environment if not already active
# Windows: venv\Scripts\activate
# macOS/Linux: source venv/bin/activate
python -m uvicorn main:app --reload --host 0.0.0.0 --port 8000Expected output:
INFO: Uvicorn running on http://0.0.0.0:8000
INFO: Application startup complete
INFO: β Model loaded successfully
Backend endpoints:
- Health check: http://localhost:8000/health
- API docs: http://localhost:8000/docs
- Model info: http://localhost:8000/model-info
cd frontend
npm run devExpected output:
β Local: http://localhost:5173/
β press h to show help
- Navigate to: http://localhost:5173
- You should see the π± Hydro Predictor dashboard
- Enter plant parameters and click "Get Prediction"
- View detailed analysis on the results page
http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
GET /healthResponse:
{
"status": "ok",
"model_loaded": true,
"version": "1.0.0"
}POST /predict
Content-Type: application/json
{
"ph_value": 6.0,
"ec_value": 1200,
"water_temperature": 21,
"air_humidity": 60,
"visual_condition": "Healthy"
}Response:
{
"plant_health_status": "Healthy",
"growth_rate": "High",
"yield_prediction": 85.5,
"disease_risk_percentage": 15.2,
"nutrient_issues": [
{
"nutrient": "General",
"issue": "All levels optimal",
"severity": "Low"
}
],
"environmental_recommendations": [
"β pH (6.0) is in optimal range.",
"β EC (1200 Β΅S/cm) is in good range.",
"β Temperature (21.0Β°C) is optimal.",
"β Humidity (60%) is acceptable."
],
"confidence_score": 0.95,
"model_version": "1.0.0"
}GET /model-infoResponse:
{
"status": "loaded",
"model_type": "XGBRegressor (Multi-output)",
"version": "1.0.0",
"features": [
"pH",
"EC/TDS",
"Water Temperature",
"Air Humidity",
"Visual Condition"
],
"outputs": [
"Health Score",
"Growth Score",
"Yield Score"
],
"input_ranges": {
"ph_value": "3.0 - 9.0",
"ec_value": "200 - 3000 Β΅S/cm",
"water_temperature": "5 - 35 Β°C",
"air_humidity": "20 - 95 %",
"visual_condition": [
"Healthy",
"Yellowing",
"Wilting",
"Leaf Curling",
"Spotting"
]
}
}- Range: 3.0 - 9.0
- Optimal: 5.5 - 6.5
- Impact: Nutrient availability, plant stress
- Range: 200 - 3000 Β΅S/cm
- Optimal: 800 - 1800 Β΅S/cm
- Impact: Nutrient concentration, plant health
- Range: 5 - 35Β°C
- Optimal: 18 - 24Β°C
- Impact: Nutrient uptake, root development, disease risk
- Range: 20 - 95%
- Optimal: 40 - 80%
- Impact: Transpiration, fungal disease risk
- Healthy: Normal appearance, vigorous growth
- Yellowing: Chlorosis symptoms, nitrogen deficiency indicator
- Wilting: Water stress, potassium deficiency indicator
- Leaf Curling: Calcium/boron deficiency, environmental stress
- Spotting: Magnesium/sulfur deficiency, pest/disease symptoms
Classification into three categories:
- π’ Healthy: All parameters optimal (score β₯ 0.66)
- π‘ Stressed: Suboptimal conditions (0.33 β€ score < 0.66)
- π΄ Diseased: Critical conditions (score < 0.33)
- π’ High: Rapid growth expected (score β₯ 0.66)
- π‘ Moderate: Normal growth (0.33 β€ score < 0.66)
- π΄ Low: Stunted growth (score < 0.33)
- Regression output: 0 - 100%
- Represents expected plant productivity relative to optimal conditions
- 0 - 100% likelihood of disease/pest infestation
- Based on:
- Temperature & humidity (fungal/bacterial conditions)
- pH & EC extremes (plant stress increases susceptibility)
- Visual symptoms (existing damage indicators)
Array of detected deficiencies/toxicities with:
- Nutrient affected
- Issue type (deficiency/toxicity)
- Severity (Low/Medium/High)
- Specific, actionable suggestions for:
- pH adjustment strategies
- EC optimization
- Temperature management
- Humidity control
- 0 - 1.0 (0 - 100%)
- Indicates prediction reliability
- Reduced for out-of-range inputs
- Helps users trust or question results
The model is trained on synthetic data. To use it with real-world hydroponic sensor data:
-
Prepare your CSV file with columns:
pH,EC,Temperature,Humidity,Visual_Condition,Health_Score,Growth_Score,Yield_Score 6.1,1150,20.5,55,Healthy,0.85,0.80,0.82 4.2,950,18.2,65,Yellowing,0.45,0.40,0.42 ...
-
Modify
train_model.py:# Replace generate_synthetic_data with your CSV: df = pd.read_csv('your_real_data.csv')
-
Retrain the model:
python train_model.py
# In train_model.py, after model training:
# Load real data and continue training
real_df = pd.read_csv('real_data.csv')
X_real, y_real = prepare_real_data(real_df)
# Continue training on real data
model.fit(X_real, y_real, xgb_model=model)Create a calibration layer that adjusts predictions based on known real-world outcomes:
# Collect predictions vs. actual outcomes
prediction_errors = []
# Then adjust future predictions
def calibrated_prediction(raw_pred, calibration_data):
adjustment = np.mean(calibration_data)
return raw_pred + adjustmentFor hydroponics, integrate with:
- pH Sensors: Analog/I2C/RS485
- EC Sensors: Conductivity probes
- Temperature Sensors: DHT22, DS18B20, or I2C sensors
- Humidity Sensors: DHT22, BME280
- Visual Analysis: Plant camera + manual inspection
# backend/sensor_integration.py
import pandas as pd
from datetime import datetime
def log_sensor_reading(ph, ec, temp, humidity, visual_notes):
"""Log sensor data for later retraining"""
data = {
'timestamp': datetime.now(),
'pH': ph,
'EC': ec,
'Temperature': temp,
'Humidity': humidity,
'Visual_Condition': visual_notes
}
# Append to CSV
df = pd.DataFrame([data])
df.to_csv('sensor_logs.csv', mode='a', header=False, index=False)Cause: Model files don't exist
Solution:
cd backend
python train_model.pyIssue: "Connection refused" on http://localhost:8000
Cause: Backend server not running
Solution: Start backend in Terminal 1:
python -m uvicorn main:app --reloadCause: Dependencies not installed
Solution:
pip install -r requirements.txtCause: Another process using the port
Solution: Change port in backend:
python -m uvicorn main:app --port 8001Then update frontend API URL in frontend/src/pages/InputDashboard.jsx:
const API_BASE_URL = 'http://localhost:8001'Cause: Frontend can't reach backend
Solution:
- Ensure backend is running (see above)
- Check API URL in InputDashboard.jsx matches backend port
- Verify CORS settings in main.py
Cause: npm cache issues
Solution:
rm -r node_modules
npm cache clean --force
npm installCause: Port 5173 already in use
Solution:
npm run dev -- --port 5174Solution: Check that values are within valid ranges:
- pH: 3.0 - 9.0
- EC: 200 - 3000
- Temperature: 5 - 35Β°C
- Humidity: 20 - 95%
Cause: Input parameters far from optimal ranges
Solution: This is expected behavior - use the "Optimal Values" button to test
Solution: Ensure Python 3.9 or higher:
python --versionModify train_model.py to experiment with:
- Different tree depths
- Learning rates
- Number of estimators
- Feature importance
# In train_model.py
model = xgb.XGBRegressor(
n_estimators=300, # More trees
max_depth=8, # Deeper trees
learning_rate=0.05, # Lower learning rate
subsample=0.7, # More regularization
)Extend the model to predict:
- Specific nutrient concentrations (NPK levels)
- Pest/disease identification
- Optimal harvesting time
- Energy consumption
Update main.py response schema:
class PredictionResponse(BaseModel):
# ... existing fields ...
nitrogen_level: float
phosphorus_level: float
potassium_level: floatCreate a batch endpoint for multiple predictions:
@app.post("/predict-batch")
def predict_batch(requests: List[PredictionRequest]):
results = []
for request in requests:
result = predict(request)
results.append(result)
return resultsStore predictions with PostgreSQL:
pip install sqlalchemy psycopg2Create a database table:
# models/prediction_log.py
from sqlalchemy import Column, String, Float, DateTime
from datetime import datetime
class PredictionLog(Base):
__tablename__ = "predictions"
id = Column(Integer, primary_key=True)
plant_health = Column(String)
yield_prediction = Column(Float)
timestamp = Column(DateTime, default=datetime.utcnow)Dockerfile (backend):
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]docker-compose.yml:
version: '3.8'
services:
backend:
build: ./backend
ports:
- "8000:8000"
frontend:
build: ./frontend
ports:
- "5173:5173"Frontend:
cd frontend
npm run build
npm run previewBackend with Gunicorn:
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 main:appFor issues or questions:
- Check the Troubleshooting section
- Review API documentation at http://localhost:8000/docs
- Inspect browser console for frontend errors
- Check backend logs for server errors
This project is provided as-is for educational and commercial use.
Built with:
- FastAPI: Modern Python web framework
- XGBoost: Gradient boosting machine learning
- React: UI library
- TailwindCSS: Utility-first CSS framework
- Recharts: React visualization library
| Task | Command |
|---|---|
| Train model | cd backend && python train_model.py |
| Start backend | cd backend && python -m uvicorn main:app --reload |
| Start frontend | cd frontend && npm run dev |
| Build frontend | cd frontend && npm run build |
| View API docs | http://localhost:8000/docs |
| Access app | http://localhost:5173 |
Happy growing! πΏ