【问题标题】:Adding pandas columns to a sparse matrix将 pandas 列添加到稀疏矩阵
【发布时间】:2017-06-15 03:08:11
【问题描述】:

我想在我的模型中使用 X 变量的其他派生值。

XAll = pd_data[['title','wordcount','sumscores','length']]
y = pd_data['sentiment']
X_train, X_test, y_train, y_test = train_test_split(XAll, y, random_state=1)

当我处理标题中的文本数据时,我首先将其单独转换为 dtm:

vect = CountVectorizer(max_df=0.5)
vect.fit(X_train['title'])
X_train_dtm = vect.transform(X_train['title'])
column_index = X_train_dtm.indices

print(type(X_train_dtm))    # This is <class 'scipy.sparse.csr.csr_matrix'>
print("X_train_dtm shape",X_train_dtm.get_shape())  # This is (856, 2016)
print("column index:",column_index)     # This is column index: [ 533  754  859 ...,  633  950 1339]

现在我将文本作为文档术语矩阵,我想将“wordcount”、“sumscores”、“length”等其他数字特征添加到 X_train_dtm。这我将使用新的 dtm 创建模型,因此会更准确,因为我会插入附加特征。

如何将 pandas 数据帧的其他数字列添加到稀疏 csr 矩阵?

【问题讨论】:

    标签: python pandas scikit-learn sklearn-pandas


    【解决方案1】:

    找到了解决办法。我们可以使用 sparse.hstack 来做到这一点:

    from scipy.sparse import hstack
    X_train_dtm = hstack((X_train_dtm,np.array(X_train['wordcount'])[:,None]))
    

    【讨论】:

    • 这将给出不支持索引的“COOrdinate 格式”的结果。 (在我的情况下是一个例外)。如何转换回压缩稀疏行格式?
    • 我发现它使用 .tocsr()
    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 2020-05-24
    • 2018-08-07
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多