是否有可能得到每一次迭代的MLP分类的测试分数?

2024-06-06 18:54:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

不过,我还想在测试数据集上绘制性能图。这有空吗?


Tags: 数据fromimportnetworksklearn曲线fitcurve
3条回答

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

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

另一种可能是将warm_start=Truemax_iter=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()

输出:

enter image description here

或者更紧凑一点:

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

输出:

enter image description here

我使用jupyter,这是我的代码:

clf = MLPClassifier(hidden_layer_sizes=(10,10,10))
clf.fit(train_X,train_Y)
plt.ylabel('cost')
plt.xlabel('iterations')
plt.title("Learning rate =" + str(0.001))
plt.plot(pose_clf.loss_curve_)
plt.show()

graph

相关问题 更多 >