我训练了带有NER数据集(https://www.kaggle.com/abhinavwalia95/entity-annotated-corpus)的LinearSVC分类器,并希望它能够预测新数据。从我已阅读的内容中,我需要创建模型并将其保存为管道来执行此操作。我一直在尝试根据SO上的其他示例进行此操作,但无法使其正常工作。如何将现有模型转换为流水线版本?
第一个代码段被保存,第二个代码段是我尝试使其进入管道的尝试之一,但是我得到一个'str'对象,该对象没有属性'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)
答案 0 :(得分:1)
您必须像这样调整第二部分:
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.to_dict("records"), y, test_size=0.1, random_state=0)
pipe = Pipeline([('vectorizer', DictVectorizer()), ('model', LinearSVC(loss="squared_hinge",C=0.5,class_weight='balanced',multi_class='ovr'))])
pipe.fit(x_train, y_train)
您正尝试通过使用
在参数中传递DictVectorizer()
您的数据
DictVectorizer(x_df.to_dict(“ records”))
但这不起作用。 DictVectorizer唯一可用的参数可以在documentation中找到。
第二个错误是您试图用来自x_df的数据将管道中的DictVectorizer()拟合为
pipe.fit(x_train,y_train)
这里的问题是x_train数据将提供给您的DictVectorizer()
,但是x_train只是拆分的x_df,并且在代码的早期没有管道,您为D ictVectorizer()
提供了数据以x_df.to_dict("records")
的形式。
因此,您还需要在管道中传递相同类型的数据。这就是为什么我已经在调整后的代码中将x_df.to_dict("records")
与train_test_split()
分开,以便矢量化程序可以对其进行处理的原因。
最后一件事是,在定义LinearSVC()
('model',LinearSVC)