gpt4 book ai didi

python - 如何阻止梯度提升机过度拟合?

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:47 25 4
gpt4 key购买 nike

我正在比较针对多分类问题的几个模型(梯度提升机、随机森林、逻辑回归、SVM、多层感知器和 keras 神经网络)。我在我的模型上使用了嵌套交叉验证和网格搜索,在我的实际数据和随机数据上运行它们来检查过度拟合。然而,对于我正在寻找的梯度提升机器,无论我如何更改我的数据或模型参数,它每次都会给我 100% 的随机数据准确率。我的代码中是否有可能导致此问题的原因?

这是我的代码:

dataset= pd.read_csv('data.csv')
data = dataset.drop(["gene"],1)
df = data.iloc[:,0:26]
df = df.fillna(0)
X = MinMaxScaler().fit_transform(df)

le = preprocessing.LabelEncoder()
encoded_value = le.fit_transform(["certain", "likely", "possible", "unlikely"])
Y = le.fit_transform(data["category"])

sm = SMOTE(random_state=100)
X_res, y_res = sm.fit_resample(X, Y)

seed = 7
logreg = LogisticRegression(penalty='l1', solver='liblinear',multi_class='auto')
LR_par= {'penalty':['l1'], 'C': [0.5, 1, 5, 10], 'max_iter':[100, 200, 500, 1000]}

rfc =RandomForestClassifier(n_estimators=500)
param_grid = {"max_depth": [3],
"max_features": ["auto"],
"min_samples_split": [2],
"min_samples_leaf": [1],
"bootstrap": [False],
"criterion": ["entropy", "gini"]}


mlp = MLPClassifier(random_state=seed)
parameter_space = {'hidden_layer_sizes': [(50,50,50)],
'activation': ['relu'],
'solver': ['adam'],
'max_iter': [10000],
'alpha': [0.0001],
'learning_rate': ['constant']}

gbm = GradientBoostingClassifier()
param = {"loss":["deviance"],
"learning_rate": [0.001],
"min_samples_split": [2],
"min_samples_leaf": [1],
"max_depth":[3],
"max_features":["auto"],
"criterion": ["friedman_mse"],
"n_estimators":[50]
}

svm = SVC(gamma="scale")
tuned_parameters = {'kernel':('linear', 'rbf'), 'C':(1,0.25,0.5,0.75)}

inner_cv = KFold(n_splits=10, shuffle=True, random_state=seed)

outer_cv = KFold(n_splits=10, shuffle=True, random_state=seed)


def baseline_model():

model = Sequential()
model.add(Dense(100, input_dim=X_res.shape[1], activation='relu')) #dense layers perform: output = activation(dot(input, kernel) + bias).
model.add(Dropout(0.5))
model.add(Dense(50, activation='relu')) #8 is the dim/ the number of hidden units (units are the kernel)
model.add(Dense(4, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model

models = []

models.append(('GBM', GridSearchCV(gbm, param, cv=inner_cv,iid=False, n_jobs=1)))
models.append(('RFC', GridSearchCV(rfc, param_grid, cv=inner_cv,iid=False, n_jobs=1)))
models.append(('LR', GridSearchCV(logreg, LR_par, cv=inner_cv, iid=False, n_jobs=1)))
models.append(('SVM', GridSearchCV(svm, tuned_parameters, cv=inner_cv, iid=False, n_jobs=1)))
models.append(('MLP', GridSearchCV(mlp, parameter_space, cv=inner_cv,iid=False, n_jobs=1)))
models.append(('Keras', KerasClassifier(build_fn=baseline_model, epochs=100, batch_size=50, verbose=0)))

results = []
names = []
scoring = 'accuracy'
X_train, X_test, Y_train, Y_test = train_test_split(X_res, y_res, test_size=0.2, random_state=0)


for name, model in models:
nested_cv_results = model_selection.cross_val_score(model, X_res, y_res, cv=outer_cv, scoring=scoring)
results.append(nested_cv_results)
names.append(name)
msg = "Nested CV Accuracy %s: %f (+/- %f )" % (name, nested_cv_results.mean()*100, nested_cv_results.std()*100)
print(msg)
model.fit(X_train, Y_train)
print('Test set accuracy: {:.2f}'.format(model.score(X_test, Y_test)*100), '%')

输出:

Nested CV Accuracy GBM: 90.952381 (+/- 2.776644 )
Test set accuracy: 90.48 %
Nested CV Accuracy RFC: 79.285714 (+/- 5.112122 )
Test set accuracy: 75.00 %
Nested CV Accuracy LR: 91.904762 (+/- 4.416009 )
Test set accuracy: 92.86 %
Nested CV Accuracy SVM: 94.285714 (+/- 3.563483 )
Test set accuracy: 96.43 %
Nested CV Accuracy MLP: 91.428571 (+/- 4.012452 )
Test set accuracy: 92.86 %

随机数据代码:

ran = np.random.randint(4, size=161)
random = np.random.normal(500, 100, size=(161,161))
rand = np.column_stack((random, ran))
print(rand.shape)
X1 = rand[:161]
Y1 = rand[:,-1]
print("Random data counts of label '1': {}".format(sum(ran==1)))
print("Random data counts of label '0': {}".format(sum(ran==0)))
print("Random data counts of label '2': {}".format(sum(ran==2)))
print("Random data counts of label '3': {}".format(sum(ran==3)))

for name, model in models:
cv_results = model_selection.cross_val_score(model, X1, Y1, cv=outer_cv, scoring=scoring)
names.append(name)
msg = "Random data CV %s: %f (+/- %f)" % (name, cv_results.mean()*100, cv_results.std()*100)
print(msg)

随机数据输出:

Random data CV GBM: 100.000000 (+/- 0.000000)
Random data CV RFC: 62.941176 (+/- 15.306485)
Random data CV LR: 23.566176 (+/- 6.546699)
Random data CV SVM: 22.352941 (+/- 6.331220)
Random data CV MLP: 23.639706 (+/- 7.371392)
Random data CV Keras: 22.352941 (+/- 8.896451)

无论我是否减少特征数量、更改网格搜索中的参数,此梯度提升分类器 (GBM) 都是 100%(我确实输入了多个参数,但是这对我来说可能会运行数小时而没有结果,所以我离开了现在这个问题),如果我尝试二进制分类数据也是一样的。

随机森林 (RFC) 也更高,为 62%,是我做错了什么吗?

我使用的数据主要是二元特征,例如如下所示(并预测类别列):

gene   Tissue    Druggable Eigenvalue CADDvalue Catalogpresence   Category
ACE 1 1 1 0 1 Certain
ABO 1 0 0 0 0 Likely
TP53 1 1 0 0 0 Possible

如有任何指导,我们将不胜感激。

最佳答案

一般来说,您可以使用一些参数来减少过度拟合。概念上最容易理解的是增加 min_samples_split 和 min_samples_leaf。为这些设置更高的值将不允许模型记住如何正确识别单个数据或非常小的数据组。对于大型数据集(约 100 万行),我会将这些值设置在 50 左右(如果不是更高的话)。您可以进行网格搜索以查找适合您的特定数据的值。

您还可以使用 subsample 和 max_features 来减少过拟合。这些参数基本上不会让您的模型查看某些阻止它内存的数据。

关于python - 如何阻止梯度提升机过度拟合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com