您似乎至少有两个任务:1.按主题进行序列分类; 2. 情绪分析。 [编辑,我现在才注意到您使用的是 Ruby/Rails,但下面的代码是 Python 中的。但也许这个答案对某些人仍然有用,并且这些步骤可以应用于任何语言。]
1.对于按主题进行的序列分类,您可以使用您所说的单词列表简单地定义类别。根据用例,这可能是最简单的选择。如果创建该单词列表过于耗时,您可以使用预训练的零样本分类器。我会推荐 HuggingFace 的零样本分类器,详情请参阅代码 here。
应用于您的用例,如下所示:
# pip install transformers # pip install in terminal
from transformers import pipeline
classifier = pipeline("zero-shot-classification")
sequence = ["Whenever I am out walking with my son, I like to take portrait photographs of him to see how he changes over time. My favourite is a pic of him when we were on holiday in Spain and when his face was covered in chocolate from a cake we had baked"]
candidate_labels = ['father', 'photography', 'travel', 'spain', 'cooking', 'chocolate']
classifier(sequence, candidate_labels, multi_class=True)
# output:
{'labels': ['photography', 'spain', 'chocolate', 'travel', 'father', 'cooking'],
'scores': [0.9802802205085754, 0.7929317951202393, 0.7469273805618286, 0.6030028462409973, 0.08006269484758377, 0.005216470453888178]}
分类器返回分数取决于每个候选标签在您的序列中表示的确定程度。它无法捕捉所有内容,但效果很好,并且可以快速付诸实践。
2。对于情绪分析,您可以使用 HuggingFace 的sentiment classification pipeline。在您的用例中,这看起来像这样:
classifier = pipeline("sentiment-analysis")
sequence = ["I hate cooking"]
classifier(sequence)
# Output
[{'label': 'NEGATIVE', 'score': 0.9984041452407837}]
将 1. 和 2. 放在一起:
我可能会(a)首先把你的整个文本分成几个句子(see here怎么做);然后 (b) 对每个句子运行情绪分类器并丢弃那些具有高负面情绪分数的句子(参见上面的步骤 2.),然后 (c) 对剩余的句子运行标签/主题分类(参见上面的 1.)。