我是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)

最佳答案

MLP分类器是一个神经网络。从本质上讲,在使用反向传播学习隐藏层上的适当权重之前,需要对其进行多次迭代(时期)进行训练,然后才能对其进行正确分类。
如果您查看sklearns实现,则有一个默认参数max_iter
从本质上讲,它可以运行200个纪元,然后再为您提供0.98的准确性。这就是为什么您需要在tensorflow中运行相同的图形200次(我假设您所说的50次也足够)以获取完全相同的输出的原因。

10-02 03:15
查看更多