python - MLPClassifier 的每次迭代都可以获得测试分数吗?

标签 python scikit-learn neural-network

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

不过,我还想绘制测试数据集的性能图。这个可以用吗?

最佳答案

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

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

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

读完 Tom 的回答后,明智的做法可能是:如果只需要跨时期的计算,他结合 warm_startmax_iter 的方法可以节省一些代码(并且使用更多 sklearn 的原始代码)。此处的代码也可以进行纪元内计算(如果需要;与 keras 进行比较)。

简单(原型(prototype))示例:

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

关于python - MLPClassifier 的每次迭代都可以获得测试分数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46912557/

相关文章:

matlab - 神经网络 : Sigmoid Activation Function for continuous output variable

Python - 当 url 可能被重写时确定正确的基本 url

python - 使用 Conda 在 Python 3.5 上安装 OpenCV

python - 从 sklearn 中的 Pipeline 对象返回系数

python - 获取与指定签名和转换错误匹配的无循环

artificial-intelligence - 我对聚类的理解正确吗?

python - Keras TimeDistributed - 权重共享吗?

python - 有序关闭Python环境

python - 在特定情况下触发时输入验证停止工作

python - sklearn 的预测是预测值超出范围