您可以使用 TensorFlow 轻松构建文档分类模型并将其集成到 TF.Learn 库中。
examples文件夹中甚至还有各种文档分类模型的示例:https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/learn#text-classification
对于任何长度的文档,最快的模型将是词袋模型 - 一种平均词嵌入的模型。这也是任何文档分类问题的推荐基准。然后你可以尝试更复杂的模型,比如 RNN 或 CNN。
这是它的示例代码:
def bag_of_words_model(features, target):
"""A bag-of-words model. Note it disregards the word order in the text."""
target = tf.one_hot(target, 15, 1, 0)
features = tf.contrib.layers.bow_encoder(
features, vocab_size=n_words, embed_dim=EMBEDDING_SIZE)
logits = tf.contrib.layers.fully_connected(features, 15, activation_fn=None)
loss = tf.losses.softmax_cross_entropy(target, logits)
train_op = tf.contrib.layers.optimize_loss(
loss,
tf.contrib.framework.get_global_step(),
optimizer='Adam',
learning_rate=0.01)
return ({
'class': tf.argmax(logits, 1),
'prob': tf.nn.softmax(logits)
}, loss, train_op)
有关如何运行它的更多详细信息,请参阅此处 - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/text_classification.py
您可以通过在计算 logits 之前添加 tf.contrib.layers.fully_connected 轻松扩展更多全连接层(例如 DNN 部分)。
您还可以使用 word2vec 或其他嵌入从预训练的检查点初始化嵌入,方法是使用 tf.contrib.framework.init_from_checkpoint(see documentation)。