python - 如何使用训练好的文本分类模型

标签 python scikit-learn svm pickle

我实现了一个 SVM 模型,可以将给定文本分为两类。该模型使用 data.csv 数据集进行训练和测试。 现在我想将此模型与实时数据一起使用。为此,我使用了 pickle python 库。 首先我保存了模型。

joblib.dump(clf, "model.pkl")

然后我已经加载了该模型。

classifer = joblib.load("model.pkl")

然后我使用下面的输入作为要分类的文本。

new_observation = "this news should be in one category"
classifer.predict([new_observation])

但是运行后,出现错误。

ValueError: could not convert string to float: 'this news should be in one category'

我引用了下面的链接来了解如何保存和加载经过训练的模型。 [https://scikit-learn.org/stable/modules/model_persistence.html][1]

编辑

这是我用来创建 svm 模型的代码。

data = pd.read_csv('data1.csv',encoding='cp1252')

def pre_process(text):

    text = text.translate(str.maketrans('', '', string.punctuation))

    text = [word for word in text.split() if word.lower() not in 
    stopwords.words('english')]

    words = ""

    for i in text:

            stemmer = SnowballStemmer("english")

            words += (stemmer.stem(i))+" "

    return words

textFeatures = data['textForCategorized'].copy()

textFeatures = textFeatures.apply(pre_process)

vectorizer = TfidfVectorizer("english")

features = vectorizer.fit_transform(textFeatures)

features_train, features_test, labels_train, labels_test = train_test_split(features, data['class'], test_size=0.3, random_state=111)

    svc = SVC(kernel='sigmoid', gamma=1.0)

    clf = svc.fit(features_train, labels_train)

    prediction = svc.predict(features_test)

实现模型后,这是我尝试向模型提供输入的方式。

joblib.dump(clf, "model.pkl")

classifer = joblib.load("model.pkl")

new_observation = "This news should be in one category"

classifer.predict(new_observation)

编辑

joblib.dump(clf, "model.pkl") 
classifer = joblib.load("model.pkl")
textFeature = "Dengue soaring in ......" 
textFeature =pre_process(textFeature) 
classifer.predict(textFeature.encode())

这是我用来加载模型并向模型输入文本的代码。这样做之后,我添加了代码来获取预测值。但我得到了一个错误。

ValueError: could not convert string to float: b'dengu soar '

最佳答案

您应该在将 new_observation 输入到模型之前对其进行预处理。在您的情况下,您仅预处理了 textFeatures 进行训练,您也必须对 new_observation 重复预处理步骤。

  1. new_observation 应用 pre_process() 函数
  2. 使用向量化器转换从pre_process(new_observation)获得的输出

关于python - 如何使用训练好的文本分类模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60025289/

相关文章:

python - 按日期对 Python 对象列表进行排序(当有些为 None 时)

Python:如何将列表字典转换为 JSON 对象?

python - 如何使用 scikit-learn 训练/升级非常大的数据集?

python - patsy 中的单热编码

r - plot 不会显示 svm 对象,也不会返回错误

matlab - 下标索引必须是正实整数或 svmclassify matlab 中的逻辑数

python - 如何在 Django 模板中显示我过滤对象的其他条目

python - 如何通过多行和每行单元格的表格中的部分文本查找元素?

machine-learning - 选择特征后显示特征名称

python - 可以在 scikit-learn 中使用预先计算的内核从 SVM 绘制 ROC 图吗?