【发布时间】:2022-01-19 17:17:54
【问题描述】:
我正在尝试根据每个产品的文本描述生成一系列产品分类器。我拥有的数据框与以下类似,但更复杂。使用 Python 和 sklearn 库。
data = {'description':['orange', 'apple', 'bean', 'carrot','pork','fish','beef'],
'level1':['plant', 'plant', 'plant', 'plant','animal','animal','animal'],
'level2:['fruit','fruit','vegatable','vegatable','livestock', 'seafood','livestock'}
# Create DataFrame
df = pd.DataFrame(data)
“描述”是文本数据。现在它只是一个词。但真正的是一个更长的句子。 “Level1”是顶级类别。 “Level2”是一个子类别。
我知道如何使用 sklearn 库训练分类模型以将产品分类为 1 级类别。
以下是我所做的:
import pandas as pd
import numpy as np
import nltk
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report, f1_score, accuracy_score, confusion_matrix
from sklearn.metrics import roc_curve, auc, roc_auc_score
import pickle
# Train/Test split
X_train, X_test, y_train, y_test = train_test_split(df['description'],
df[['Level1','Level2']], test_size = 0.4, shuffle=True)
#use the TF-IDF Vectorizer
tfidf_vectorizer = TfidfVectorizer(use_idf=True)
#transforming the training data into tf-idf matrix
X_train_vectors_tfidf = tfidf_vectorizer.fit_transform(X_train)
#transforming testing data into tf-idf matrix
X_test_vectors_tfidf = tfidf_vectorizer.transform(X_test)
#Create and save model for level 1
naive_bayes_classifier = MultinomialNB()
model_level1 = naive_bayes_classifier.fit(X_train_vectors_tfidf, y_train['Level1'])
with open('model_level_1.pkl','wb') as f:
pickle.dump(model_level1, f)
我不知道怎么做的是为每个 1 级类别建立一个分类模型,可以预测产品的 2 级类别。例如,基于上述数据集,应该有一个“植物”分类模型(预测水果或蔬菜)和另一个“动物”模型(预测海鲜或牲畜)。您有什么想法可以使用循环来保存模型吗?
【问题讨论】:
标签: python text classification hierarchy