当我使用 sklearn 的交叉验证时,我对特征矩阵的大小感到困惑。这是我的代码:
'''Cross-Validation'''
skf = cross_validation.StratifiedKFold(data_label, n_folds=10, shuffle=True, random_state=None)
'''For each fold, Do the classification'''
for train_index, test_index in skf:
train_data = np.array(data_content[train_index])
train_label = np.array(data_label[train_index])
test_data = np.array(data_content[test_index])
test_label = np.array(data_label[test_index])
'''Create feature matrix'''
cont_vect = CountVectorizer(analyzer='word')
train_data_matrix = cont_vect.fit_transform(train_data)
test_data_matrix = cont_vect.transform(test_data)............the classification
在 10 折交叉验证的每个循环中。如果训练数据集创建的特征文档度量(这里是词袋)与测试特征文档度量不同怎么办。例如,单词“happy”是测试数据集中的一个特征,但不是训练数据集中的特征。我不确定我的代码是否正确,因为我在这里使用了:
cont_vect.fit_transform
创建训练特征矩阵,并使用
cont_vect.transform
为了创建测试特征矩阵,代码可以运行,但我不知道为什么,比如 fit_transform 和 transform 之间有什么区别?我假设测试矩阵是基于训练矩阵创建的。
如果是真的,另一个问题是,每个循环的特征尺寸是否应该相同?因为,当使用 10-fold CV 时,无论训练数据集来自原始数据集的哪一部分,训练+测试(原始数据集)都是相同的,因此每个循环的特征矩阵大小应该相等。但是当我检查结果时,特征的大小是不同的,相似但不相等。我不知道为什么会这样?谢谢。
请您参考如下方法:
这是一个很好的问题! ML 领域的许多年轻研究人员忘记了这个问题。
让我们从头开始
what's difference between with fit_transform and transform?
scikit-learn 中的转换器是能够将一种类型的数据转换为另一种类型的数据的类,此外,它们通常通过分析数据来学习如何做到这一点。
.fit(X)使模型从X 中学习一些参数集
.transform(X)要求模型使用经过训练的模型转换X.fit_transform(X)只是调用.fit(X)后跟.transform(X)的缩写形式,没什么更多的。由于这是转换我们正在学习的数据的常用做法,因此这种快捷方式真正广泛用于基于 sklearn 的代码;
What if the feature-document metrix (here is bag of words) created by the training dataset is different with test feature-document metrix. for example, word 'happy' is a feature in test dataset, but not in the training dataset
它会做最合理的事情 - 它会忽略在训练阶段看不到的对象。对于您的特定情况,当您在训练数据上调用 fit(在 fit_transform 内)时,您的转换器(向量化器)构建了内部词汇表 - 在训练期间看到的一组单词。这些是它唯一识别的单词。当您对新文本调用 transform 时,不在 transformer vocablurary 中的单词将被简单地忽略(因为它对它们一无所知,显然它会混淆其上的分类器)。如果测试集转换中不存在词汇表中的某些单词怎么办?这些值只是获取 0 值(或其他默认值,意思是“现在没有这样的对象”)。
I'm not sure my code is correct, because here I used:
cont_vect.fit_transformto create the training feature matrix, and use
cont_vect.transform
是的,您的代码非常好,这正是您应该做的。
总结一下。
What if the feature-document metrix (here is bag of words) created by the training dataset is different with test feature-document metrix.
矩阵总是相同的,因为它的大小(维数)是在您调用fit 和transform 调用后确定的永远不会影响内部词汇表(其大小是矩阵的大小)。
