如果我正确理解您的问题,您正在寻找将您的句子编码为数字表示的方法。
假设您有如下数据:
data = ["Sarah, is that you? Hahahahahaha Todd give you another black eye??"
"Well, being slick comes with the job of being a propagandist, Andi..."
"Sad to lose a young person who was earnestly working for the common good and public safety when so many are in the basement smoking pot and playing computer games."]
labels = [0,1,0]
现在您要构建一个分类器,因为训练分类器数据应该是数字格式,所以在这里我们将文本数据转换为数字结构,我们将使用 tf-idf 矢量化器为文本数据创建矩阵,然后应用任何算法。
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
vectorizerPipe = Pipeline([
('tfidf', TfidfVectorizer(lowercase=True,stop_words='english')),
('classification', LinearSVC(penalty='l2',loss='hinge'))])
trained_model = vectorizerPipe.fit(data,labels)
这里构建了管道,第一步是特征向量提取(将文本数据转换为数字格式),下一步我们将对其应用算法。您可以尝试这两个步骤中的很多参数。
稍后我们使用 .fit 方法启动管道并传递数据和标签。