【问题标题】:How to get a "scoring" trained model(predict)如何获得“评分”训练模型(预测)
【发布时间】:2018-11-03 16:06:51
【问题描述】:

在函数GridSearchCV中有搜索和训练的数据(X, y)。 训练在自定义标准 T_scorer 上进行。 是否可以在 T_scorer 函数中使用经过训练的模型? 我需要“T_scorer”预测数据“X1”。 也就是说,模型在每次迭代时都在数据 (X,y) 上进行训练,并在 (X1,y1) 上进行预测 同样 (X1, y1) 根本不参与训练并且“GridSearchCV”这些数据看不到。

理想情况下,我们应该在数据 (X,y) 上进行训练,并在“评分”时传输基于预测 (X1,y1) 的结果)

def T_scorer(y_true, y_pred, clf, **kwargs):
    r = np.sum((y_pred == 0) & (y_pred == y_true))

    y_pred1 = clf.predict(X1)  #It doesn't work

    confmat = confusion_matrix(y, y_pred)
    print(confmat)
    print(r)
    return r

_scorer = make_scorer(T_scorer)

clf = RandomForestClassifier()
grid_searcher = GridSearchCV(clf, parameter_grid, cv=StratifiedKFold(shuffle =True,random_state=42),verbose=20, scoring=_scorer)
grid_searcher.fit(X, y)
clf_best = grid_searcher.best_estimator_
print('Best params = ', clf_best.get_params())

【问题讨论】:

  • 我想计算这个函数中的参数。并将其发送到“返回”。这是理想的。但是,如果您只是在每次迭代时输出“print”,它是合适的。

标签: python scikit-learn grid-search


【解决方案1】:

make_scorer() 应该仅在您具有签名(y_true, y_pred) 的功能时使用。当您在函数上使用make_scorer() 时,返回的签名是:

func(估计器, X, y)

然后在 GridSearchCV 中使用。因此,您可以将函数指定为:

,而不是使用make_scorer
# I am assuming this is the data you want to use
X1 = X[:1000]
y1 = y[:1000]

def T_scorer(clf, X, y):
    # Here X and y passed on to the function from GridSearchCV will not be used
    y_pred1 = clf.predict(X1)
    r = np.sum((y_pred1 == 0) & (y1 == y_pred1))
    confmat = confusion_matrix(y1, y_pred1)
    print(confmat)
    return r

# Now dont use make_scorer, pass directly
grid_searcher = GridSearchCV(clf,..., verbose=20, scoring=T_scorer)

【讨论】:

  • 有效。为什么函数“T_scorer(cf, X, y)”而不是“T_scorer(cf, X1, y1)”?提前问明白,所以经验少)
  • @user287629 函数中的参数将从 GridSearchCV 传递。你可以给它们起任何名字。但那样他们就不会是你希望他们成为的人了。
  • 除此之外,是否可以仅在“打印”中输出带有 (X, y) 的结果?
  • @user287629 是的。只需像使用 X1 和 y1 一样使用 X 和 y
猜你喜欢
  • 2019-10-10
  • 2019-10-05
  • 1970-01-01
  • 2017-08-20
  • 2020-03-18
  • 1970-01-01
  • 2022-10-19
  • 2021-09-06
  • 1970-01-01
相关资源
最近更新 更多