我们的团队正在处理一个自然语言处理问题。我们有一组带有标签的句子数据集,我们需要将它们分类为两个类别,0或1。
我们对数据进行了预处理,并使用词嵌入,因此每个句子有300个特征,然后我们使用一个简单的神经网络来训练模型。
由于数据非常倾斜,我们用F1分数来衡量模型的得分,在训练集(80%)和测试集(20%)上都计算了这个分数。
Spark
我们使用了PySpark的MLlib中提供的多层感知机分类器:
layers = [300, 600, 2]trainer = MultilayerPerceptronClassifier(featuresCol='features', labelCol='target', predictionCol='prediction', maxIter=10, layers=layers, blockSize=128)model = trainer.fit(train_df)result = model.transform(test_df)predictionAndLabels = result.select("prediction", "target").withColumnRenamed("target", "label")evaluator = MulticlassClassificationEvaluator(metricName="f1")f1_score = evaluator.evaluate(predictionAndLabels)
通过这种方式,我们获得的F1分数在0.91到0.93之间变化。
TensorFlow
然后我们主要为了学习目的,选择切换到TensorFlow,因此我们使用与MLlib相同的架构和公式实现了一个神经网络:
# Network Parametersn_input = 300n_hidden_1 = 600n_classes = 2# TensorFlow graph inputfeatures = tf.placeholder(tf.float32, shape=(None, n_input), name='inputs')labels = tf.placeholder(tf.float32, shape=(None, n_classes), name='labels')# Initializes weights and biasesinit_biases_and_weights()# Layers definitionlayer_1 = tf.add(tf.matmul(features, weights['h1']), biases['b1'])layer_1 = tf.nn.sigmoid(layer_1)out_layer = tf.matmul(layer_1, weights['out']) + biases['out']out_layer = tf.nn.softmax(out_layer)# Optimizer definitionlearning_rate_ph = tf.placeholder(tf.float32, shape=(), name='learning_rate')loss_function = tf.losses.log_loss(labels=labels, predictions=out_layer)optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate_ph).minimize(loss_function)# Start TensorFlow sessioninit = tf.global_variables_initializer()tf_session = tf.InteractiveSession()tf_session.run(init)# Train Neural Networklearning_rate = 0.01iterations = 100batch_size = 256total_batch = int(len(y_train) / batch_size)for epoch in range(iterations): avg_cost = 0.0 for block in range(total_batch): batch_x = x_train[block * batch_size:min(block * batch_size + batch_size, len(x_train)), :] batch_y = y_train[block * batch_size:min(block * batch_size + batch_size, len(y_train)), :] _, c = tf_session.run([optimizer, loss_function], feed_dict={learning_rate_ph: learning_rate, features: batch_x, labels: batch_y}) avg_cost += c avg_cost /= total_batch print("Iteration " + str(epoch + 1) + " Logistic-loss=" + str(avg_cost))# Make predictionspredictions_train = tf_session.run(out_layer, feed_dict={features: x_train, labels: y_train})predictions_test = tf_session.run(out_layer, feed_dict={features: x_test, labels: y_test})# Compute F1-scoref1_score = f1_score_tf(y_test, predictions_test)
支持函数:
def initialize_weights_and_biases(): global weights, biases epsilon_1 = sqrt(6) / sqrt(n_input + n_hidden_1) epsilon_2 = sqrt(6) / sqrt(n_classes + n_hidden_1) weights = { 'h1': tf.Variable(tf.random_uniform([n_input, n_hidden_1], minval=0 - epsilon_1, maxval=epsilon_1, dtype=tf.float32)), 'out': tf.Variable(tf.random_uniform([n_hidden_1, n_classes], minval=0 - epsilon_2, maxval=epsilon_2, dtype=tf.float32)) } biases = { 'b1': tf.Variable(tf.constant(1, shape=[n_hidden_1], dtype=tf.float32)), 'out': tf.Variable(tf.constant(1, shape=[n_classes], dtype=tf.float32)) }def f1_score_tf(actual, predicted): actual = np.argmax(actual, 1) predicted = np.argmax(predicted, 1) tp = tf.count_nonzero(predicted * actual) fp = tf.count_nonzero(predicted * (actual - 1)) fn = tf.count_nonzero((predicted - 1) * actual) precision = tp / (tp + fp) recall = tp / (tp + fn) f1 = 2 * precision * recall / (precision + recall) return tf.Tensor.eval(f1)
通过这种方式,我们获得的F1分数在0.24到0.25之间变化。
问题
我能看到的两个神经网络之间的唯一区别是:
- 优化器:Spark使用L-BFGS,TensorFlow使用梯度下降
- 权重和偏置的初始化:Spark进行自己的初始化,而我们在TensorFlow中手动初始化
我认为这两个参数不会导致模型性能之间如此大的差异,但Spark似乎在很少的迭代中就能获得非常高的分数。
我无法理解TensorFlow是否表现得非常差,或者也许Spark的分数并不真实。在这两种情况下,我认为我们都没有看到一些重要的东西。
回答:
将权重初始化为均匀分布,将偏置初始化为1显然不是一个好主意,这很可能是造成这种差异的原因。
请使用normal
或truncated_normal
代替,权重使用默认的零均值和小方差:
weights = { 'h1': tf.Variable(tf.truncated_normal([n_input, n_hidden_1], stddev=0.01, dtype=tf.float32)), 'out': tf.Variable(tf.truncated_normal([n_hidden_1, n_classes], stddev=0.01, dtype=tf.float32)) }
偏置使用零值:
biases = { 'b1': tf.Variable(tf.constant(0, shape=[n_hidden_1], dtype=tf.float32)), 'out': tf.Variable(tf.constant(0, shape=[n_classes], dtype=tf.float32)) }
尽管如此,我对在二分类问题中使用MulticlassClassificationEvaluator
的正确性不太确定,我建议进行一些进一步的手动检查,以确认该函数确实返回你认为它返回的内容…