text_plain_output_2.png application_vnd.jupyter.stderr_output_1.png
from sklearn.ensemble import RandomForestRegressor

from sklearn.linear_model import ElasticNet

from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score

from sklearn.model_selection import train_test_split, GridSearchCV

import mlflow

import numpy as np

mlflow.set_tracking_uri('https://dagshub.com/ChiragChauhan4579/MLflow-integration.mlflow')
mlflow.set_experiment(experiment_name='wine-quality')

y_train.value_counts()

alpha = 0.6
l1_ratio = 0.9
with mlflow.start_run():
    mlflow.set_tag('model', 'elastic-net')
    mlflow.log_param('alpha', alpha)
    mlflow.log_param('l1_ratio', l1_ratio)
    lr = ElasticNet(alpha=alpha, l1_ratio=alpha)
    lr.fit(x_train, y_train)
    y_pred = lr.predict(x_test)
    rmse = np.sqrt(mean_squared_error(y_test, y_pred))
    mae = mean_absolute_error(y_test, y_pred)
    r2 = r2_score(y_test, y_pred)
    mlflow.log_metric('rmse', rmse)
    mlflow.log_metric('mae', mae)
    mlflow.log_metric('r2', r2)
    mlflow.sklearn.log_model(lr, 'elastic-net-base')

rf = RandomForestRegressor()

with mlflow.start_run():
    mlflow.set_tag('hyperparameter tuning', 'random forest')
    params = [{'n_estimators': [100, 250, 500, 1000], 'max_depth': list(range(3, 7)), 'max_features': list(range(0, 14))}]
    reg = GridSearchCV(rf, params, cv=10, scoring='neg_mean_absolute_error')
    reg.fit(x_train, y_train)
    y_pred = reg.predict(x_test)
    rmse = np.sqrt(mean_squared_error(y_test, y_pred))
    mae = mean_absolute_error(y_test, y_pred)
    r2 = r2_score(y_test, y_pred)
    mlflow.log_metric('rmse', rmse)
    mlflow.log_metric('mae', mae)
    mlflow.log_metric('r2', r2)
    mlflow.log_param('n_estimators', reg.best_params_['n_estimators'])
    mlflow.log_param('max_leaf_nodes', reg.best_params_['max_depth'])
    mlflow.sklearn.log_model(reg.best_estimator_, 'best_rf_model')