Как вернуть из функции настроенную (fit) модель случайного леса (RandomForestRegressor)?

Написал функцию, в которой должна обсчитываться модель RandomForestRegressor. Однако при последующем использовании возвращаемой модели возникает ошибка: NotFittedError: This RandomForestRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator, хотя в функции метод fit применялся. Помогите пожалуйста скорректировать код, чтобы возвращаемое значение уже было после fit.

Если делать все то же самое, но вне функции - то все работает. Заранее большое спасибо!

def my_random_forest_regressor(model, features, target, model_name="model",
                               criterion='mse', 
                               max_depth=20,   
                               min_samples_leaf=5,
                               n_estimators=1000,
                               random_state=42):
    
    model = RandomForestRegressor(criterion=criterion, 
                                 max_depth=max_depth, 
                                 min_samples_leaf=min_samples_leaf, 
                                 n_estimators=n_estimators, 
                                 random_state=random_state)
    model.fit(features, target)
   
    expected_y  = target
    predicted_y = model.predict(features)
    
    print(f'Model: {model_name}')
    print(f'R2: {metrics.r2_score(expected_y, predicted_y)}')
    
    plt.figure(figsize=(10,10))    
    sns.regplot(expected_y, predicted_y, fit_reg=True, scatter_kws={"s": 100})
    plt.xlabel('Таргет реальный')
    plt.ylabel('Таргет предсказанный')
    plt.title('True vs Predicted values')
           
    return model

Ответы (0 шт):