如何使用经过训练的文本分类模型

2024-06-16 18:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我实现了一个支持向量机模型,可以将给定的文本分为两类。使用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 '


Tags: textin模型testnewdatamodeltrain
2条回答

我也遇到了同样的问题,并通过根据训练数据的形状调整单个字符串数据的大小来解决

完整代码:

joblib.dump(clf, "model.pkl") 
classifer = joblib.load("model.pkl")
textFeature = "Dengue soaring in ......" 
vocabulary=pre_process(textFeature) 
vocabulary_df =pd.Series(vocabulary)

#### Feature extraction using Tfidf Vectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(stop_words='english')

test_ = vectorizer.fit_transform(vocabulary_df.values)

test_.resize(1, features_train.shape[1])
classifer.predict(test_)

您应该在将new_observation馈送到模型之前对其进行预处理。在您的情况下,您只为培训预处理了textFeatures,您也必须为new_observation重复预处理步骤

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

相关问题 更多 >