如何用角班轮计算损失

发布于 2025-02-13 11:12:22 字数 847 浏览 2 评论 0 原文

我正在使用Sklearn的KerasClassifier来包装我的KERAS型号,以执行K-折叠验证。

model = KerasClassifier(build_fn=create_model, epochs=20, batch_size=8, verbose = 1)    
kfold = KFold(n_splits=10)
scoring = ['accuracy', 'precision', 'recall', 'f1']
results = cross_validate(estimator=model,
                               X=x_train,
                               y=y_train,
                               cv=kfold,
                               scoring=scoring,
                               return_train_score=True,
                              return_estimator=True)

然后,根据指标,我选择了函数返回的10个估计器之间的最佳模型:

best_model = results['estimators'][2] #for example the second model

现在,我想对 x_test 进行预测,并获得准确性和损失指标。我该怎么做?我尝试了 model.evaluate(x_test,y_test),但是模型是kerasclassifier,因此我会遇到错误。

I'm using KerasClassifier from sklearn to wrap my Keras model in order to perform K-fold cross validation.

model = KerasClassifier(build_fn=create_model, epochs=20, batch_size=8, verbose = 1)    
kfold = KFold(n_splits=10)
scoring = ['accuracy', 'precision', 'recall', 'f1']
results = cross_validate(estimator=model,
                               X=x_train,
                               y=y_train,
                               cv=kfold,
                               scoring=scoring,
                               return_train_score=True,
                              return_estimator=True)

Then I choose the best model between the 10 estimators returned by the function, according to metrics:

best_model = results['estimators'][2] #for example the second model

Now, I want to perform a predict on x_test and get accuracy and loss metrics. How can I do it? I tried model.evaluate(x_test, y_test) but the model is a KerasClassifier so I get an error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

两相知 2025-02-20 11:12:23

要点是,您的 实例模拟标准 Scikit-Learn 分类器。换句话说,它是 scikit-learn beast ,而且它不提供方法 .evaluate()

因此,您可能只会调用 best_model.score(x_test,y_test),它将自动返回准确性,因为标准的Sklearn分类器会返回。另一方面,您可以通过历史记录_ kerasclassifier 实例访问培训期间获得的损失值。

这是一个示例:

!pip install scikeras    

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_validate, KFold
import tensorflow as tf
import tensorflow.keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from scikeras.wrappers import KerasClassifier

X, y = make_classification(n_samples=100, n_features=20, n_informative=5, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

def build_nn():
    ann = Sequential()
    ann.add(Dense(20, input_dim=X_train.shape[1], activation='relu', name="Hidden_Layer_1"))
    ann.add(Dense(1, activation='sigmoid', name='Output_Layer'))
    ann.compile(loss='binary_crossentropy', optimizer= 'adam', metrics = 'accuracy')
return ann

keras_clf = KerasClassifier(model = build_nn, optimizer="adam", optimizer__learning_rate=0.001, epochs=100, verbose=0)

kfold = KFold(n_splits=10)
scoring = ['accuracy', 'precision', 'recall', 'f1']
results = cross_validate(estimator=keras_clf, X=X_train, y=y_train, scoring=scoring, cv=kfold, return_train_score=True, return_estimator=True)

best_model = results['estimator'][2]

# accuracy
best_model.score(X_test, y_test)

# loss values
best_model.history_['loss']

最终观察到,如有疑问,您可以调用 dir(object)获取指定对象的所有属性和方法的列表( dir(best_model)在您的情况下)。

Point is that your KerasClassifier instance mimics standard scikit-learn classifiers. In other terms, it is kind of a scikit-learn beast and, as is, it does not provide method .evaluate().

Therefore, you might just call best_model.score(X_test, y_test) which will automatically return the accuracy as standard sklearn classifiers do. On the other hand, you can access the loss values obtained during training via the history_ attribute of your KerasClassifier instance.

Here's an example:

!pip install scikeras    

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_validate, KFold
import tensorflow as tf
import tensorflow.keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from scikeras.wrappers import KerasClassifier

X, y = make_classification(n_samples=100, n_features=20, n_informative=5, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

def build_nn():
    ann = Sequential()
    ann.add(Dense(20, input_dim=X_train.shape[1], activation='relu', name="Hidden_Layer_1"))
    ann.add(Dense(1, activation='sigmoid', name='Output_Layer'))
    ann.compile(loss='binary_crossentropy', optimizer= 'adam', metrics = 'accuracy')
return ann

keras_clf = KerasClassifier(model = build_nn, optimizer="adam", optimizer__learning_rate=0.001, epochs=100, verbose=0)

kfold = KFold(n_splits=10)
scoring = ['accuracy', 'precision', 'recall', 'f1']
results = cross_validate(estimator=keras_clf, X=X_train, y=y_train, scoring=scoring, cv=kfold, return_train_score=True, return_estimator=True)

best_model = results['estimator'][2]

# accuracy
best_model.score(X_test, y_test)

# loss values
best_model.history_['loss']

Eventually observe that, when in doubt, you can call dir(object) to get the list of all properties and methods of the specified object (dir(best_model) in your case).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文