且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从sklearn的MLPClassifier检索最终隐藏的激活层输出

更新时间:2023-12-01 22:02:16

正如我在上面的评论中所说,看起来好像没有功能可以完全按照sklearn的要求进行操作,但是您可以破解_predict功能非常容易使它可以执行您想要的操作.以下代码将返回所有激活信息,您可以仅将其编辑为return activations[-2].

As I said in my comment above, it doesn't look like there's a function to do exactly what you want in sklearn but you can hack the _predict function very easily to make it do what you want. The following code will return all activations, you can edit this to return activations[-2] for just the bit that you're after.

def get_activations(clf, X):
        hidden_layer_sizes = clf.hidden_layer_sizes
        if not hasattr(hidden_layer_sizes, "__iter__"):
            hidden_layer_sizes = [hidden_layer_sizes]
        hidden_layer_sizes = list(hidden_layer_sizes)
        layer_units = [X.shape[1]] + hidden_layer_sizes + \
            [clf.n_outputs_]
        activations = [X]
        for i in range(clf.n_layers_ - 1):
            activations.append(np.empty((X.shape[0],
                                         layer_units[i + 1])))
        clf._forward_pass(activations)
        return activations