Scikit Learn:调查错误分类的数据

Sci-Kit Learn: Investigating Incorrectly Classified Data

我想使用 sci-kit learn 分析被模型错误分类的数据,以便改进我的特征生成。我有一个方法可以做到这一点,但我是 sci-kit learn 和 pandas 的新手,所以我想知道是否有更多 efficient/direct 的方法来完成这个。这似乎是标准工作流程的一部分,但在我所做的研究中,我没有发现任何直接解决从模型分类到特征矩阵到原始数据的反向映射的问题。

这是我正在使用的context/workflow,以及我设计的解决方案。下面是示例代码。

上下文。我的工作流程如下所示:

  1. 从一堆 JSON 斑点开始,原始数据。这是 pandas 数据框。
  2. 为建模提取相关部分,称之为数据。这是一个 pandas 数据框。
  3. 此外,我们有所有数据的真值数据,因此我们称其为真值或 y。
  4. 在sci-kit learn中创建一个特征矩阵,称之为X。这是一个很大的稀疏矩阵。
  5. 创建一个随机森林对象,称之为森林。
  6. 使用 sci-kit learn split_train_test() 函数创建用于训练和测试的特征矩阵的随机子集。
  7. 在上面的训练数据上训练森林,X_train,这是一个很大的稀疏矩阵。
  8. 获取假阳性和假阴性结果的指标。这些是 X_test 的索引,一个稀疏矩阵。
  9. 从误报索引进入 X_test 回到原始数据
  10. 如有必要,从数据转到原始数据。

解决方案。

这是与使用推文的示例相关联的代码。同样,这行得通,但是还有更多 direct/smarter 的方法吗?

# take a sample of our original data
data=tweet_df[0:100]['texts']
y=tweet_df[0:100]['truth']

# create the feature vectors
vec=TfidfVectorizer(analyzer="char",ngram_range=(1,2))
X=vec.fit_transform(data) # this is now feature matrix

# split the feature matrix into train/test subsets, keeping the indices back into the original X using the
# array indices
indices = np.arange(X.shape[0])
X_train, X_test, y_train, y_test,idx_train,idx_test=train_test_split(X,y,indices,test_size=0.2,random_state=state)

# fit and test a model
forest=RandomForestClassifier()
forest.fit(X_train,y_train)
predictions=forest.predict(X_test)

# get the indices for false_negatives and false_positives in the test set
false_neg, false_pos=tweet_fns.check_predictions(predictions,y_test)

# map the false negative indices in the test set (which is features) back to it's original data (text)
print "False negatives: \n"
pd.options.display.max_colwidth = 140
for i in false_neg:
    original_index=idx_test[i]
    print data.iloc[original_index]

和检查预测函数:

def check_predictions(predictions,truth):
    # take a 1-dim array of predictions from a model, and a 1-dim truth vector and calculate similarity
    # returns the indices of the false negatives and false positives in the predictions. 

    truth=truth.astype(bool)
    predictions=predictions.astype(bool)
    print sum(predictions == truth), 'of ', len(truth), "or ", float(sum(predictions == truth))/float(len(truth))," match"

    # false positives
    print "false positives: ", sum(predictions & ~truth)
    # false negatives
    print "false negatives: ",sum( ~predictions & truth)
    false_neg=np.nonzero(~predictions & truth) # these are tuples of arrays
    false_pos=np.nonzero(predictions & ~truth)
    return false_neg[0], false_pos[0] # we just want the arrays to return

您的工作流程是:

原始数据->特征->分割->训练->预测->标签上的误差分析

预测和特征矩阵有row-for-row对应关系,所以如果要对特征做误差分析,应该没有问题。如果您想查看哪些原始数据与错误相关联,那么您必须对原始数据进行拆分,或者跟踪哪些数据行映射到哪些测试行(您当前的方法)。

第一个选项如下所示:

在原始数据上安装转换器 -> 拆分原始数据 -> 分别转换 train/test -> train/test -> ...

也就是说,它在拆分前使用 fit,在拆分后使用 transform,让您以与标签相同的方式对原始数据进行分区。