如何处理这个 NLP 算法解决方案?

How to approach this NLP algorithm solution?

我想做一个算法,只是不确定如何处理这个概念。我有一些取自亚马逊评论(我的数据集)的词袋,其中包含对产品评论的评分(0-5 星)。我的目标是制作一种算法,使用这些词对没有评论的评论进行评分。我该如何解决这个问题?

我想到的解决方案是首先将单词映射到评论,并根据所述评论的评分给出该评分的单词作为分数,然后对所有有评分的评论重复此过程,然后平均出单词的分数以及其中包含单词的评分(我仍然需要弄清楚当单词在评论中出现两次时该怎么做)。然后最后使用分数,我将在没有评级的评论中使用该模型,然后根据使用了包中的单词数来平均该分数。

像这样:

review_one = {'food is nice': 4}
review_two = {'its alright': 3}
review_three = {'bad' : 1}
review_four = {'its nice': 3}

bag_of_words = ['bad', 'nice', 'alright', 'food']

trained_model = {'bad': 1, 'nice': 3.5, 'alright': 3, 'food': 4}

test_review = "service bad but food nice"

trained_model.predict(test_review)

output = test_review_rating = 2.83 #(1+3.5+4)/3

我的解决方案似乎太乏味了,所以我想知道是否有更好的方法来解决这个问题,还是我在做一些完全不同的事情?

我会创建一个包含弓 (bag_of_words) 和相关重量的 class 模型。还包含一种训练权重的方法和其他用于预测的方法。 有很多方法可以做到这一点。但一种实现可能是:

class Simple_npl_model():
    def __init__(self,bag_of_words,weights=None):
        self.bow = bag_of_words
        if weights is None:
            self.weights = len(bag_of_words)*[0]

    def train(self,train_dict): 
        #simple train method that trhows your result
        for idx,word in enumerate(self.bow):
            word_score = 0
            word_count = 0
            for key,val in train_dict.items():
                if word in key:
                    word_count += 1
                    word_score += val
            if word_count :
                self.weights[idx]=word_score/word_count

    def predict(self,phrase):
        #evaluation of phrase
        phrase_score = 0
        bow_count = 0
        for idx,word in enumerate(self.bow):
            if word in phrase:
                phrase_score += self.weights[idx]
                bow_count += 1
        if bow_count:
           return phrase_score/bow_count
        else:
            return 0

    @property
    def bow_dict(self):
        #property that shows your trained params
        return {word:score for word,score in zip(self.bow,self.weights)}

然后您可以创建一个实例并使用您的数据进行训练。为了方便工作, 我把所有的评论都写在一个字典里了。

review_one = {'food is nice': 4}
review_two = {'its alright': 3}
review_three = {'bad' : 1}
review_four = {'its nice': 3}

reviews  = {**review_one, **review_two, **review_three, **review_four}

bag_of_words = ['bad', 'nice', 'alright', 'food']

model= Simple_npl_model(bag_of_words)
model.train(reviews)

#trained_model = {'bad': 1, 'nice': 3.5, 'alright': 3, 'food': 4}
print(model.bow_dict)

最后一次使用模型进行预测

#test
test_review = "service bad but food nice"
print(f"Review Rating: {model.predict(test_review)}")