因此,根据我收集到的信息,您在问如何预处理未出现在训练集中的新(我想是未观察到的)电子邮件。在这种情况下,您应该将您的电子邮件文本转换为 1000 维向量,其中每个值对应一个特定的特征值。
我将根据您简单地计算新电子邮件中最常见的 1000 个单词中出现的次数(我们称之为)。x(1)test
要将电子邮件转换为矢量形式,这是一种方法:
import pandas as pd
import numpy as np
words = ["blah", "tea", "tetra", "pak"]
def vectorise_email(words, e_mail):
"""Vectorise email to a vector of word counts based on a list of words.
:param words: (List of Strings) List of frequent words in training set
:param e_mail: (String) E-mail string
:return word_counts: (Numpy Array) containing counts of words based on words list.
"""
e_mail = pd.DataFrame(e_mail.split())
e_mail = e_mail[e_mail[0].isin(words)][0].value_counts()
word_counts = np.zeros(len(words))
for w_idx, word in enumerate(words):
word_counts[w_idx] = e_mail.at[word]
return word_counts
print(vectorise_email(words, "this is a blah tetra pak tea tea blah blahh"))
这里我们首先将句子标记为单词(我使用了标准的字符串拆分方法,但您可以使用 nltk 的标记方法 [ https://www.nltk.org/api/nltk.tokenize.html])。然后我们将此列表转换为 pandas DataFrame 以使用 value_counts 方法(参考:https ://stackoverflow.com/questions/22391433/count-the-frequency-that-a-value-occurs-in-a-dataframe-column ) 以获取出现在单词列表中的单词的单词计数。然后我们通过将这些计数映射到一个 Numpy 数组来完成向量化过程,其中数组中的每个元素对应于输入电子邮件中的特定字数。
希望有帮助