我想用GridSearchCV来调整我的keras神经网络,因为我在数据集中有很高的不平衡性。这是一个二元分类问题。这是我尝试过的
def f1(y_true, y_pred):
y_pred = K.round(y_pred)
tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)
# tn = K.sum(K.cast((1-y_true)*(1-y_pred), 'float'), axis=0)
fp = K.sum(K.cast((1-y_true)*y_pred, 'float'), axis=0)
fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)
p = tp / (tp + fp + K.epsilon())
r = tp / (tp + fn + K.epsilon())
f1 = 2*p*r / (p+r+K.epsilon())
f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)
return K.mean(f1)
def create_model():
model = Sequential()
model.add(Dense(899, activation = 'relu', input_dim = 899))
model.add(Dense(100, activation = 'relu'))
model.add(Dense(1, activation = 'sigmoid'))
model.compile(optimizer= 'adamax', loss = 'binary_crossentropy', metrics = [f1])
return model
param_grid = dict(batch_size = batch_size, epochs = epochs,class_weight = class_weight)
grid = GridSearchCV(estimator = model, param_grid = param_grid, n_jobs =7, cv = 2, scoring = f1 )
但我得到了错误
^{2}$看来我也需要创造一个得分手?如何才能正确地做到这一点呢?在
更新:
这似乎解决了这个问题,我认为它是按计划工作的
from sklearn.metrics import f1_score
from sklearn.metrics import make_scorer
f1_scorer = make_scorer(f1_score)
然后传递给GridsearchCV函数
grid = GridSearchCV(estimator = model, param_grid = param_grid, n_jobs =7, cv = 2, scoring = f1_scorer )
目前没有回答
相关问题 更多 >
编程相关推荐