【发布时间】:2021-07-20 01:33:50
【问题描述】:
我有一个这样的数据框:
Text A B C Label
337 nobodi can explain gave what we did ... 0 1 0 1
338 provide an example 1 1 0 0
339 another one???? 1 0 0 1
我想了解如何构建 ML 分类器。 目前,我做了如下:
X = train[['Text','A','B','C']]
y = train['Label']
# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=40)
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.25, random_state=40)
# Returning to one dataframe
train_df = pd.concat([X_train, y_train], axis=1)
test_df = pd.concat([X_test, y_test], axis=1)
valid_df = pd.concat([X_valid, y_valid], axis=1)
然后我使用 BOW 和 TFIDF 创建特征:
countV = CountVectorizer()
train_count = countV.fit_transform(train_df['Text'].values)
# To create tfidf frequency features
tfidfV = TfidfTransformer()
train_tfidf = tfidfV.fit_transform(train_count)
tfidf_ngram = TfidfVectorizer(stop_words='english',ngram_range=. (1,2),use_idf=True,smooth_idf=True)
但是,当我构建模型时,例如 NB 模型:
nb_pipeline = Pipeline([
('NBCV', countV),
('nb_clf',MultinomialNB())])
nb_pipeline.fit(train_df['Text'],train_df['Label'])
predicted_nb = nb_pipeline.predict(test_df['Text'])
np.mean(predicted_nb == test_df['Label'])
有些东西不起作用,因为我丢失了关于我的虚拟变量 A、B、C 的信息。我只有 Text 的功能。当我尝试查看功能重要性时,我可以检查一下:
feature_names = nb_pipeline.named_steps["NBCV"].get_feature_names()
coefs = nb_pipeline.named_steps["nb_clf"].coef_.flatten()
import pandas as pd
zipped = zip(feature_names, coefs)
df = pd.DataFrame(zipped, columns=["feature", "value"])
df["ABS"] = df["value"].apply(lambda x: abs(x))
df["colors"] = df["value"].apply(lambda x: "green" if x > 0 else "red")
df = df.sort_values("ABS", ascending=True)
您能解释一下为什么我会丢失这些信息以及如何将我的虚拟变量保留在模型中吗?这些变量对模型应该非常有意义,因此我不能将它们从模型构建中排除。我需要检查模型的准确性并查看这些变量对此的影响。
【问题讨论】:
-
您要为此使用
pipeline吗?或者你会接受没有它的答案吗?此外,您永远不应该混合使用您的validation和test集。 -
你好 wundermanh。感谢您对有效和测试集的评论。如果可以在答案中显示所有步骤(包括管道和特征包含在特征选择中的“证明”),那就太好了。
-
好的,请稍等。请注意,我正在创建自己的数据,因为我只有几行您的数据,但大多数应该是复制粘贴。
-
谢谢@wundermahn。如果您还可以解释我做错了什么,这对于更好地理解和将来不会重犯同样的错误也将非常有帮助。
标签: python machine-learning scikit-learn pipeline feature-selection