Мне нужно выполнить вложенную перекрестную проверку для проекта машинного обучения, задачи двоичной классификации, где я сравниваю LASSO и RandomForest. Я обычно использую R для анализа данных, но не могу найти функцию или какой-либо удобный фрагмент кода для вложенной перекрестной проверки в R, поэтому я обратился к Python. Код для вложенной перекрестной проверки с помощью Python приведен здесь: https://mlfromscratch.com/nested-cross-validation-python-code/#/
Предсказуемая (двоичная) переменная помечена как DIAG в кадре данных. Вот код, который я использую.
from nested_cv import NestedCV
import numpy as np
import pandas as pd
df1 = pd.read_excel("model1_past_history.xlsx")
df1['DIAG'] = np.where(df1['DIAG']=='MDD', '0', '1')
conditions = [
(df1['marital'] == 'married'),
(df1['marital'] == 'single'),
(df1['marital'] == 'divorced')]
choices = ['0', '1', '2']
df1['marital'] = np.select(conditions, choices)
df1.DIAG.value_counts()
df1.iloc[:,0:df1.columns.get_loc("BMI")] = df1.iloc[:,0:df1.columns.get_loc("BMI")].astype('category')
df1.info(verbose=True)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1635 entries, 0 to 1634
Data columns (total 70 columns):
DIAG 1635 non-null category
INC2_A 1635 non-null category
INC2_B 1635 non-null category
INC2_F 1635 non-null category
INC2_G 1635 non-null category
INC2_H 1635 non-null category
INC2_I 1635 non-null category
SEX 1635 non-null category
marital 1635 non-null category
inpatient 1635 non-null category
AD_1 1635 non-null category
AD_2 1635 non-null category
AD_3 1635 non-null category
AD_4 1635 non-null category
CMS_1 1635 non-null category
CMS_2 1635 non-null category
CMS_3 1635 non-null category
CMS_4 1635 non-null category
CMS_5 1635 non-null category
CMS_6 1635 non-null category
CMS_7 1635 non-null category
CMS_8 1635 non-null category
CMS_9 1635 non-null category
CMS_10 1635 non-null category
CMS_11 1635 non-null category
CMS_12 1635 non-null category
CMS_13 1635 non-null category
CMS_14 1635 non-null category
OCS_1 1635 non-null category
OCS_2 1635 non-null category
OCS_3 1635 non-null category
OCS_4 1635 non-null category
OCS_5 1635 non-null category
OCS_6 1635 non-null category
OCS_7 1635 non-null category
OCS_8 1635 non-null category
OCS_9 1635 non-null category
OCS_10 1635 non-null category
OCS_11 1635 non-null category
reta 1635 non-null category
MH_F1 1635 non-null category
CP_1BA 1635 non-null category
CP_1BS 1635 non-null category
MIXCLINICAL3 1635 non-null category
MIXCLINICAL2 1635 non-null category
MIXDS52Simpt 1635 non-null category
MIXDS53Simpt 1635 non-null category
PAN 1635 non-null category
OBS 1635 non-null category
PHO 1635 non-null category
GAD 1635 non-null category
EAT_0 1635 non-null category
ADHD 1635 non-null category
BORDERLINEPERSONALITY 1635 non-null category
AlcoolProbUse 1635 non-null category
SubstanceProbUse 1635 non-null category
BMI 1635 non-null float64
DEP_AGE 1635 non-null int64
NBD_P 1635 non-null int64
NBDEP 1635 non-null int64
NBSUI 1635 non-null int64
NBHOS 1635 non-null int64
DURDEP 1635 non-null int64
SEV_M 1635 non-null int64
SEV_D 1635 non-null int64
CMS_sum 1635 non-null int64
TOTMIXDSM5 1635 non-null int64
GAF 1635 non-null int64
Age 1635 non-null int64
Comorbidities_sum 1635 non-null int64
dtypes: category(55), float64(1), int64(14)
memory usage: 284.7 KB
X = df1.iloc[:, 1:len(df1.columns)]
y = df1.iloc[:,0]
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import Lasso
from sklearn.metrics import auc
models_to_run = [RandomForestClassifier(), Lasso()]
models_param_grid = [
{ # 1st param grid, corresponding to RandomForestClassifier
'n_estimators': [500,1000],
'max_features' : [8,12,16]
},
{ # 2nd param grid, corresponding to Lasso
'alpha': [0.0001,0.001,0.01,0.1,1,10],
}
]
for i,model in enumerate(models_to_run):
nested_CV_search = NestedCV(model=model, params_grid=models_param_grid[i], outer_kfolds=5, inner_kfolds=5, cv_options={'sqrt_of_score':False, 'metric':auc,'metric_score_indicator_lower':False})
nested_CV_search.fit(X=X,y=y)
Последняя строка кода вызывает эту ошибку:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Любая помощь, чтобы исправить это, будет высоко ценится.