Step into Dynamic Model Evaluator, where you’ll craft flexible ML evaluation queries using Dynamic Queries, Stored Procedures, and User-Defined Functions! This project builds a reusable evaluator for model metrics, a star for your ML-Interview-Preparation-Hub portfolio to show automation skills. 🚀
- Scenario: You’re an ML developer automating model evaluation. Your task is to create dynamic SQL to compute metrics based on user inputs and store reusable logic.
- Goals: Build dynamic queries, create procedures, and export results.
- SQL Skills: Dynamic Queries (EXECUTE), Stored Procedures, User-Defined Functions.
- Use
predictionsandmodel_configs(model_id INT, config JSON). - Insert sample data with JSON configs.
- Write a UDF to extract JSON metrics.
- Create a stored procedure for dynamic metric queries.
- Build a dynamic query to filter by date or model.
- Export results to a CSV.
- Document for portfolio use.
-- Task 1: Tables exist (predictions), create model_configs
CREATE TABLE model_configs (
model_id INT PRIMARY KEY,
config JSON
);
-- Task 2: Insert Sample Data
INSERT INTO model_configs VALUES
(101, '{"metric": "accuracy", "value": 0.85}'),
(102, '{"metric": "f1_score", "value": 0.90}');
INSERT INTO predictions VALUES
(1, 101, 0.85, '2025-04-15', 'BERT_v1'),
(2, 102, 0.90, '2025-04-20', 'XGBoost_v2');
-- Task 3: Create UDF
CREATE OR REPLACE FUNCTION get_json_metric(config JSON, metric_key VARCHAR)
RETURNS FLOAT AS $$
BEGIN
RETURN config->>metric_key::FLOAT;
END;
$$ LANGUAGE plpgsql;
-- Task 4: Stored Procedure
CREATE OR REPLACE PROCEDURE evaluate_models(metric_type VARCHAR)
LANGUAGE plpgsql AS $$
BEGIN
EXECUTE format('
SELECT p.model_id, AVG(p.score) AS avg_score, get_json_metric(c.config, %L) AS config_metric
FROM predictions p
JOIN model_configs c ON p.model_id = c.model_id
GROUP BY p.model_id, c.config
', metric_type);
END;
$$;
-- Task 5: Dynamic Query
DO $$
BEGIN
EXECUTE 'SELECT model_id, AVG(score) AS avg_score
FROM predictions
WHERE prediction_date >= ''2025-04-01''
GROUP BY model_id';
END $$;
-- Task 6: Export (Pseudo-code)
-- COPY (SELECT ...) TO 'model_metrics.csv' WITH CSV HEADER;
-- Task 7: Document (See Portfolio Tips)Explanation:
- DDL adds config table.
- UDF extracts JSON metrics.
- Stored Procedures and Dynamic Queries enable flexible evaluation.
- DML tests functionality.
- A dynamic evaluation query system.
- A CSV file (
model_metrics.csv) with model metrics. - A portfolio-ready automation showcase.
- Add
model_metrics.csvtoirohanportfolio.netlify.app. - Write a README explaining automation and ML use (e.g., model evaluation).
- Demo with Python’s
sqlalchemycalling the procedure. - Tag skills: Dynamic Queries, Stored Procedures, UDFs.
Add a Cursor to iterate over models for batch evaluation.