我的数据框架中有一个文本列,其中包含(S)段,在数据帧的每个实例/示例/行中都有多个可变的句子。然后,我使用nltk的sent_tokenizer创建了该段的句子标记,并将其放入另一列。
所以我的数据框架是这样的:
index text class
0 ["Hello i live in berlin", 'I'm xxx'] 1
1 ["My name is xx", "I have a cat", "Love is life"] 0现在当我使用:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('distilbert-base-nli-stsb-mean-tokens')
sentences = df['text']
sentences = sentences.tolist()
embeddings = model.encode(sentences)我得到了:
TypeError: expected string or bytes-like objectencode方法不以句子列表作为参数。
发布于 2020-09-02 17:08:58
我终于解决了这个问题。
我的数据看起来是这样的:
index text class
0 ["Hello i live in berlin", 'I'm xxx'] 1
1 ["My name is xx", "I have a cat", "Love is life"] 0Text列包含每一行中的句子列表。我应用了以下功能:
df['Embeddings'] = df['text'].apply(lambda x: model.encode(x))它创建了一个名为嵌入式的新列。嵌入列现在包含每一行大小为768的向量列表。现在,我将使用lambda对新创建的嵌入列的and元素应用平均函数,该元素将为每一行创建一个长度为768的向量,然后将其存储在一个新列中,比如'X‘。然后,我将把X与类标签一起提供给SVM。
基本上,我们要做的是,平均为文本列中的句子生成嵌入向量的数量。
例如,对于df“文本”中的索引0,我们有两个句子:
["Hello i live in berlin", 'I'm xxx'] 现在,在编码之后,它将如下所示:
[v1,v2] # where length of v1 and v2 vectors is 768接下来,我们将使用np.average获取这两个向量的平均值。它将产生一个单一的载体:
[v]这个单一的向量现在可以很容易地输入到支持向量机。当然,我们将对所有行执行此操作,然后将其提供给支持向量机。
发布于 2020-09-02 08:27:08
encode方法只作为字符串处理单个句子,也就是说,您需要对每个句子单独调用它:
embeddings = [model.encode(s) for s in sentences]https://datascience.stackexchange.com/questions/81089
复制相似问题