【问题标题】:Is it possible to get test scores for each iteration of MLPClassifier?是否可以获得 MLPClassifier 每次迭代的测试分数?
【发布时间】:2018-04-05 08:54:09
【问题描述】:

我想并排查看训练数据和测试数据的损失曲线。目前,使用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

但是,我还想在测试数据集上绘制性能图。这个可以吗?

【问题讨论】:

    标签: python scikit-learn neural-network


    【解决方案1】:

    clf.loss_curve_ 不是API-docs 的一部分(尽管在某些示例中使用)。它存在的唯一原因是因为它在内部用于提前停止

    正如 Tom 提到的,还有一些方法可以使用 validation_scores_

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

    看完Tom的回答,可能明智的说法是:如果只需要跨时代计算,他结合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()
    

    输出:

    或者更紧凑一点:

    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()
    

    输出:

    【讨论】:

      【解决方案2】:

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

      每次迭代的验证分数都存储在clf.validation_scores_中。

      另一种可能性是将warm_start=Truemax_iter=1 一起使用,并在每次迭代后手动计算您想要监控的所有数量。

      【讨论】:

        猜你喜欢
        • 2019-02-01
        • 1970-01-01
        • 2011-03-30
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 2018-05-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多