我在寻找一个使用Tensorflow解决简单文本分类问题的方案。我使用IMDB数据集构建了一个模型,以判断评论是正面还是负面的。数据通过word2vec处理后,我现在有一堆向量需要分类。我认为我的问题可能是因为y_labels的形状不好,因为它们是一维的,而我想通过Tensorflow对它们进行分类,输出为两个类别,或者可能是我错了。最后的信息是,模型运行得很好,准确率达到1.0,可能太好了!谢谢帮助!
X_train called train_vecs = (25000, 300) dtype: float64X_test called test_vecs = (25000, 300) dtype: float64y_test = shape (25000, 1) dtype: int64y_train = shape: (25000, 1) dtype: int64x = tf.placeholder(tf.float32, shape = [None, 300])y = tf.placeholder(tf.float32, shape = [None, 2])# Input -> Layer 1W1 = tf.Variable(tf.zeros([300, 2]))b1 = tf.Variable(tf.zeros([2]))#h1 = tf.nn.sigmoid(tf.matmul(x, W1) + b1)# Calculating difference between label and outputpred = tf.nn.softmax(tf.matmul(x, W1) + b1)cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))train_step = tf.train.GradientDescentOptimizer(0.3).minimize(cost)with tf.Session() as sess: for i in xrange(200): init_op = tf.initialize_all_variables() sess.run(init_op) train_step.run(feed_dict = {x: train_vecs, y: y_train}) correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print "Accuracy:", accuracy.eval({x: test_vecs, y: y_test})
回答:
你在示例中使用了softmax。Softmax为N个不同的类别分配概率,这些概率总和为1。基本上,模型是在N个选择中精确选择一个。为了使这有意义,你需要N至少为2。当N等于1时,该类的概率总是1。你有两个可能的解决方案:
- 创建两个类别,一个用于“正面情感”,一个用于“负面情感”,将N设置为2。
- 使用逻辑回归代替Softmax。在逻辑回归中,每个类别是独立的。这意味着你有N个问题,每个问题都有自己的“是”或“不是”答案,这在N等于1时是有意义的。