def get_word_embedding(word): input_ids = tokenizer.encode(word, return_tensors='pt', padding=True, truncation=True, max_length=128) with torch.no_grad(): output = Bertmodel(input_ids) last_hidden_states = output.last_hidden_state # 获取最后一层隐藏状态(向量表示) attention_mask = output.attentions # 获取每层的注意力分布 # 使用注意力分布计算加权平均向量表示 word_embedding = torch.matmul(attention_mask, last_hidden_states).mean(dim=1).squeeze().numpy() return word_embedding X_embeddings = [get_word_embedding(text) for text in X]
无法get_word_embedding(text)
最新推荐文章于 2024-09-14 18:24:21 发布