是否有可能获得MLPClassifier的每次迭代的测试分数?

cam*_*mil 10 python neural-network scikit-learn

我想并排查看训练数据和测试数据的损耗曲线.目前,使用clf.loss_curve(参见下文)获得每次迭代的训练集损失似乎很简单.

from sklearn.neural_network import MLPClassifier
clf = MLPClassifier()
clf.fit(X,y)
clf.loss_curve_ # this seems to have loss for the training set
Run Code Online (Sandbox Code Playgroud)

但是,我还想在测试数据集上绘制性能.这可用吗?

sas*_*cha 8

clf.loss_curve_不是API文档的一部分(尽管在某些示例中使用过)。它存在的唯一原因是因为它在内部用于早期停止

正如汤姆提到的,还有一些使用方法validation_scores_

除此之外,更复杂的设置可能需要以更手动的方式进行培训,您可以在其中控制何时,什么以及如何测量某物。

在阅读完汤姆的答案后,也许会说得很明智:如果只需要跨时间段计算,那么他的合并warm_startmax_iter保存一些代码的方法(并使用了sklearn的更多原始代码)。这里的代码也可以进行历时内计算(如果需要;与keras比较)。

简单(原型)示例:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_mldata
from sklearn.neural_network import MLPClassifier
np.random.seed(1)

""" Example based on sklearn's docs """
mnist = fetch_mldata("MNIST original")
# rescale the data, use the traditional train/test split
X, y = mnist.data / 255., mnist.target
X_train, X_test = X[:60000], X[60000:]
y_train, y_test = y[:60000], y[60000:]

mlp = MLPClassifier(hidden_layer_sizes=(50,), max_iter=10, alpha=1e-4,
                    solver='adam', verbose=0, tol=1e-8, random_state=1,
                    learning_rate_init=.01)

""" Home-made mini-batch learning
    -> not to be used in out-of-core setting!
"""
N_TRAIN_SAMPLES = X_train.shape[0]
N_EPOCHS = 25
N_BATCH = 128
N_CLASSES = np.unique(y_train)

scores_train = []
scores_test = []

# EPOCH
epoch = 0
while epoch < N_EPOCHS:
    print('epoch: ', epoch)
    # SHUFFLING
    random_perm = np.random.permutation(X_train.shape[0])
    mini_batch_index = 0
    while True:
        # MINI-BATCH
        indices = random_perm[mini_batch_index:mini_batch_index + N_BATCH]
        mlp.partial_fit(X_train[indices], y_train[indices], classes=N_CLASSES)
        mini_batch_index += N_BATCH

        if mini_batch_index >= N_TRAIN_SAMPLES:
            break

    # SCORE TRAIN
    scores_train.append(mlp.score(X_train, y_train))

    # SCORE TEST
    scores_test.append(mlp.score(X_test, y_test))

    epoch += 1

""" Plot """
fig, ax = plt.subplots(2, sharex=True, sharey=True)
ax[0].plot(scores_train)
ax[0].set_title('Train')
ax[1].plot(scores_test)
ax[1].set_title('Test')
fig.suptitle("Accuracy over epochs", fontsize=14)
plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

或更紧凑:

plt.plot(scores_train, color='green', alpha=0.8, label='Train')
plt.plot(scores_test, color='magenta', alpha=0.8, label='Test')
plt.title("Accuracy over epochs", fontsize=14)
plt.xlabel('Epochs')
plt.legend(loc='upper left')
plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明


Tom*_*DLT 5

使用MLPClassifier(early_stopping=True),停止标准从训练损失变为准确度分数,准确度分数是根据验证集(其大小由参数validation_fraction)计算得出的。

每次迭代的验证分数存储在内部clf.validation_scores_

另一种可能性是使用warm_start=Truemax_iter=1和手工计算所有你想每次迭代之后监视量。