【问题标题】:Reproducing scikit-learn's MLPClassifier in TensorFlow在 TensorFlow 中重现 scikit-learn 的 MLPClassifier
【发布时间】:2018-04-17 05:42:27
【问题描述】:

我是 Tensorflow 的新手,之前广泛使用过 scikit-learn。作为我尝试过渡到 TensorFlow 的第一个练习之一,我试图重现我使用 scikit-learn 的 MLPClassifier 获得的一些结果。

当我使用大多数默认设置的 MLPClassifier 时,我在测试集上的准确率高达 98%。然而,当我在 TensorFlow 中实现我认为等效的单层 ANN 时,我在测试集上得到的准确率不到 90%。让 TensorFlow 产生类似准确度的唯一方法是在训练集上训练多次(> 50 次)。

您知道差异可能来自哪里吗?或者我可以将我的代码与 Tensorflow 中的 sklearn MLPClassifier 实现进行比较吗?

就我而言,我在输出层使用相同的优化器 (Adam)、相同的学习率、具有相同参数的 L2 正则化、相同的激活函数 (ReLU) 和 softmax 评估。

我对 TensorFlow 图的实现如下:

n_units = 500

X = tf.placeholder(tf.float32, [None, n_features])
Y = tf.placeholder(tf.float32, [None, n_classes])    

# Create weights for all layers
W_input = tf.Variable(tf.truncated_normal([n_features, n_units]))
W_out = tf.Variable(tf.truncated_normal([n_units, n_classes]))

# Create biases for all layers
b_1 = tf.Variable(tf.zeros([n_units]))
b_2 = tf.Variable(tf.zeros(([n_classes])))

# Mount layers
hidden_layer = tf.nn.relu(tf.matmul(X, W_input) + b_1)
logits = tf.matmul(hidden_layer, W_out) + b_2

# Get all weights into a single list
all_weights = tf.concat([tf.reshape(W_input, [-1]), tf.reshape(W_out, [-1])], 0)

# Compute loss function
cross_entropy = tf.reduce_mean(
    tf.losses.softmax_cross_entropy(onehot_labels=Y, logits=logits))

# Compute regularization parameter
regularizer = 0.0001*tf.nn.l2_loss(all_weights)

# Train step
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy + regularizer)

# Get number of correct predictions
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1))

# Class prediction
prediction = tf.argmax(tf.nn.softmax(logits), 1)

# Get accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

我对sklearn模型的实现很简单:

clf = neural_network.MLPClassifier(hidden_layer_sizes = (500,), random_state=42)

【问题讨论】:

    标签: python tensorflow scikit-learn


    【解决方案1】:

    MLP 分类器是一个神经网络。本质上,它需要经过多次迭代(epochs)的训练,然后才能使用反向传播在隐藏层上学习适当的权重,然后才能正确分类。

    如果你看一下 sklearns 的实现,有一个默认参数叫做max_iter

    ma​​x_iter:int,可选,默认200

    最大迭代次数。求解器迭代直到收敛(由“tol”确定)或迭代次数。对于随机求解器(‘sgd’、‘adam’),请注意这决定了 epoch 的数量(每个数据点将被使用多少次),而不是梯度步数。

    基本上,它会运行 200 个 epoch,然后才能为您提供 0.98 的准确度。这就是为什么您需要在 tensorflow 中运行相同的图表 200 次(我假设您所说的 50 次也足够了)以获得完全相同的输出。

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 2018-11-13
      • 2017-04-18
      • 2018-08-31
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2017-09-23
      相关资源
      最近更新 更多