【发布时间】:2020-12-25 13:46:24
【问题描述】:
我使用 NER 数据集 (https://www.kaggle.com/abhinavwalia95/entity-annotated-corpus) 训练了一个 LinearSVC 分类器,并希望它能够预测新数据。根据我的阅读,我需要创建模型并将其保存为管道来执行此操作。我一直在尝试根据 SO 上的其他示例来执行此操作,但无法使其正常工作。如何将现有模型转换为流水线版本?
第一个代码 sn-p 保存,第二个代码是我尝试将其放入管道的尝试之一,但我得到一个 'str' object has no attribute 'items' 错误。我认为它与 to_dict 过程有关,但不知道如何在流水线版本中复制它,任何人都可以帮忙。
dframe = pd.read_csv("ner.csv", encoding = "ISO-8859-1", error_bad_lines=False)
dframe.dropna(inplace=True)
dframe[dframe.isnull().any(axis=1)].size
x_df = dframe.drop(['Unnamed: 0', 'sentence_idx', 'tag'], axis=1)
vectorizer = DictVectorizer()
X = vectorizer.fit_transform(x_df.to_dict("records"))
y = dframe.tag.values
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)
model = LinearSVC(loss="squared_hinge",C=0.5,class_weight='balanced',multi_class='ovr')
model.fit(x_train, y_train)
dump(model, 'filename.joblib')
dframe = pd.read_csv("ner.csv", encoding = "ISO-8859-1", error_bad_lines=False)
dframe.dropna(inplace=True)
dframe[dframe.isnull().any(axis=1)].size
x_df = dframe.drop(['Unnamed: 0', 'sentence_idx', 'tag'], axis=1)
y = dframe.tag.values
x_train, x_test, y_train, y_test = train_test_split(x_df, y, test_size=0.1, random_state=0)
pipe = Pipeline([('vectorizer', DictVectorizer(x_df.to_dict("records"))), ('model', LinearSVC)])
pipe.fit(x_train, y_train)
【问题讨论】:
-
为什么不直接转储管道本身,这样对生产会更好?
-
为了使用您的模型进行预测,您不需要管道。您已经使用 model.fit(x_train,y_train) 训练了模型。现在您可以使用 model.predict() 对新数据进行预测。看看这个:scikit-learn.org/stable/modules/generated/…
-
是的,我可以在同一个数据集上进行预测,但是当我尝试预测新数据并使用 dictvectorizer 时,特征集与模型不同并给出错误。这就是为什么我认为我需要管道
标签: python python-3.x pandas scikit-learn pipeline