我对word2vec模型进行了培训,列出了杂货店的所有产品名称。然后,我用下面列出的常用短语和单词建立了词汇表:
from gensim.models.phrases import Phrases, Phraser
from gensim.models import Word2Vec
phrases = Phrases(product_list, min_count=30, progress_per=10000)
bigram = Phraser(phrases)
common_texts = bigram[product_list]
w2v_model = Word2Vec(min_count=5,
window=2,
size=300,
sample=6e-5,
alpha=0.03,
min_alpha=0.0007,
negative=20,
workers=1,
sorted_vocab=1)
w2v_model.build_vocab(sentences=common_texts, progress_per=10000)
w2v_model.train(sentences=common_texts, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1)我的总体目标是将产品映射到类别。我创建了一个函数,它以products类型的产品和类型类别的类别作为参数。然后找出每一对产品名称和类别名称之间的相似性,并指定产品的类别--具有最高相似性的类别。
def assign_category(products, categories):
max_similarity = 0
for product in products:
for category in categories:
current_similarity = w2v_model.wv.similarity(Product.get_name(product), Category.get_name(category))
if current_similarity > max_similarity:
max_similarity = current_similarity
product.set_category(category)
product.set_match_rate(max_similarity)我的问题是,w2v_model.wv.similarity 函数不接受模型词汇表中不包含的单词或短语。因此,当我用以下产品名称和类别测试该函数时
product = Product("salty potato chips with cheese and oninon")
category = Category("potato chips")我知道错误了
word 'salty potato chips with cheese and oninon' not in vocabulary
Examples of words in vocabulary: *chicken, milk, ice cream, potato chips, etc.备注:当我用产品名称而不是普通的短语和单词构建词汇表时,当然,词汇表不足以包含产品名称。我知道没有任何方法的词汇包括每一个单一的产品名称。但是,由于我的模型在词汇中(如“面包”和“面包”)能够很好地找到相似的产品/类别,所以我想找到一种方法来使用这个模型来达到我的目标。
如何使用Word2Vec模型并检查任意两个字符串的相似性,而不受词汇表的限制?如果这是不可能的,你会给我什么建议来达到我的目标?
发布于 2022-08-15 11:55:36
我不确定在这种情况下Word2Vec是否是最好的选择,但我可能错了。我认为采用文本分类的方法更合适,因为您有一个产品列表,以及它们所属的各个类别。
但是,在这种情况下,您可以简单地过滤掉模型词汇表中没有包含的OOV令牌,然后再获得相似信息。
# pip install gensim==4.2.0
from gensim.models import Word2Vec
from typing import Text, List, NoReturn
def preprocess_sentence(tokens: Text) -> Text:
"""
preprocesses a given sentence
"""
token_list = [token.lower() for token in tokens.split()]
# apply other preprocessing steps here
return token_list
def filter_tokens(tokens) -> List[Text]:
"""
generates a list of tokens and removes any token that
is not present in the w2v_model's vocabulary
"""
return [token for token in preprocess_sentence(tokens) if token in vocabulary]
def assign_categories(product_list: List, category_list: List) -> NoReturn:
"""
loops through the list of products and categories and
dumps the assigned category details into a dict
"""
product_categories = dict()
for product in product_list:
filtered_product_tokens = filter_tokens(product)
product_categories.update({product: {'category': None, 'similarity': 0}})
if not filtered_product_tokens:
continue
for category in categories:
filtered_category_tokens = filter_tokens(category)
if not filtered_category_tokens:
continue
similarity = w2v_model.wv.n_similarity(filtered_product_tokens, filtered_category_tokens)
if similarity > product_categories[product]['similarity']:
product_categories[product] = {'category': category, 'similarity': similarity}
for product, category in product_categories.items():
print(f"Product: {product}\nCategory: {category['category']}\n")
# lists of products and categories
products = ["strawberry milk", "milk powder", "vAnilla yoghurt", "mozzarella cheese", "happy cow cheese"]
categories = ["milk", "yoghurt", "cheese"]
# preprocessing
list_of_product_tokens = [preprocess_sentence(product) for product in products]
list_of_category_tokens = [preprocess_sentence(category) for category in categories]
list_of_tokens = list_of_product_tokens + list_of_category_tokens
# model building and training
w2v_model = Word2Vec(sentences=list_of_tokens, min_count=1)
vocabulary = w2v_model.wv.index_to_key
# assigning categories
products.append("pineapple juice")
products
assign_categories(
product_list=products,
category_list=categories
)产出:
Product: strawberry milk
Category: milk
Product: milk powder
Category: milk
Product: vAnilla yoghurt
Category: yoghurt
Product: mozzarella cheese
Category: cheese
Product: happy cow cheese
Category: cheese
Product: pineapple juice
Category: None注意,我使用列表来存储产品和类别,而不是使用对象。也不使用短语,也许使用短语可以稍微改善我得到的答案
发布于 2022-08-15 18:41:35
首先&最重要的是:一个不知道单词的word2vec模型不能给出该单词的向量。因此,你应该期待错误传递一个模型词,它没有经过训练-知道。你不能用锤子来拧紧螺丝钉;你不能用word2vec模型告诉你单词的向量,据它所知,这些词都是无稽之谈。
第二:看起来您正在尝试从Word2Vec模型中获取多字字符串的向量。这样的模型对于多个字串的向量应该是什么也没有任何固有的概念。他们只在训练中学习单个单词,所以你只能直接查找单个单词。在某些情况下,考虑单词运行的向量为所有单个单词向量的平均值可能是有意义的。你可以试试。
但是还有:如果你增加了一个Phrases步骤,你实际上已经修改了你的训练数据,根据经验统计规则,把一些单词组合成大写。例如,3个标记['salty', 'potato', 'chips']可能变成['salty', 'potato_chips'] (取决于您的语料库中的实际相对概率)。因此,在查找训练后文本的向量之前,您应该应用相同的双图组合,使用与以前相同的训练Phrasesr来实现自我一致性。但是,实际上:使用Phrases是一种更先进的技术,需要其他的权衡和考虑,所以我建议您不要使用它,除非/直到您进一步了解了更基本的方法。只有到那时,如果你有一个合理的理论,它可能有帮助,并有一种方法来评估它是否有帮助,然后再加上它。
但是,更一般地&基本地说:实际上是要完成的任务是“分类”:从一个固定的已知集合中提取未知类别/标签/类的项目,然后推荐一个最适合的类别/标签/类。尝试的方法有很多很多,这取决于(除其他外)如何将项目量化为“特性”,从而提示它们的类别(特征提取),以及可以推断类别的规则(算法的选择和参数化),以及现有知识--通常是带有正确类标记的项的已知示例--如何被收集和训练到所选的模型中。
你临时建立了一个临时分类系统,它的思想是把你的类别概括为单一向量,然后把新产品概括为单一向量,然后用最近的向量将每个产品分配给类别。
这是一种常见的想法,也是一种直观的方法--但与免费/基本库(如scikit-learn)中提供的所有可训练的分类算法相比,也非常简单。它对任何过程都非常敏感,并且受到任何过程的限制--将先验知识转化为奇异category向量,新产品转化为奇异product向量。在某些方面,它类似于"K近邻“分类器,但更受限制:限制只找到最近已知的示例;使已知的--示例--成为单个向量(而不是该类别中所有先前已知的成员的集合)。
因此,如果你真正的目标是很好地完成这个分类,我建议把你目前的努力放在一边,并研究一些介绍性的Python机器--学习‘分类’示例--理想的情况下,既包括一些要分类的项目已经具有数量特征的例子,也有一些项目是需要成为各种类型的向量的文本(通常是作为一个基线的‘袋子’--单词‘)。这将升级您的一般方法,最后,您甚至可能根本不使用word2vec。(这只是帮助将文本转化为分类算法的量化特征的一种方法-通常有助于在特定情况下,文本的模糊感是有价值的,但在刚开始的时候也往往会过度使用。)
如果你的目标是学习和玩word2vec,你可以继续你现有的方法,但是:
Phrases似乎为时过早,而且您独特的模型参数alpha=0.03, min_alpha=0.0007往往出现在糟糕的在线教程中&在没有理解的情况下重新思考。(大多数用户,尤其是初学者,根本不需要指定这样的非缺省值。)FastText:它可以为从未见过的单词提供猜测向量,由单词片段构造,因此当新单词是其他已知单词的无效形式(键入/更改时态/共享词-词根)时,通常比没有更好的选择。(尽管如此,这并不是你的方法的主要问题-所以只有在其他一切都很好的情况下,你才会在你的训练后数据中看到一个几乎但不太为人所知的词的问题,你会考虑在角落案例中添加FastText作为一些剩余的改进吗?)https://stackoverflow.com/questions/73359137
复制相似问题